Sunday, July 17, 2011

Encrypting Passwords is easy

Well atleast it is when you use JASYPT (Java Simplified Encryption)

Lets use the BasicPasswordEncryptor for our first attempt

    BasicPasswordEncryptor basicEncryptor = new BasicPasswordEncryptor();
    System.out.println(basicEncryptor.encryptPassword("My Very Strong Password"));

The thing that I find interesting here is every time I run this simple program i get a different encrypted password


HqFktdLI4FRmm1FZRpl1aPwaZwMZHHKx
C1G24DHVoApEBMo2OGboQCU92bM4Vz3/
PN1Bfp2C1SKp+jWMIbfwv4FryTvbi48b
sr54VjzHllbIOZkCMT8+5gpEJYvOMZZ/
leS3xZ9eavcmLdpry16TWShD84YqDZBf

That can't be right, can it? Lets check

   System.out.println(basicEncryptor.checkPassword("My Very Strong Password", "HqFktdLI4FRmm1FZRpl1aPwaZwMZHHKx"));
   System.out.println(basicEncryptor.checkPassword("My Very Strong Password", "C1G24DHVoApEBMo2OGboQCU92bM4Vz3/"));
   System.out.println(basicEncryptor.checkPassword("My Very Strong Password", "sr54VjzHllbIOZkCMT8+5gpEJYvOMZZ/"));
   System.out.println(basicEncryptor.checkPassword("My Very Strong Password", "PN1Bfp2C1SKp+jWMIbfwv4FryTvbi48b"));
   System.out.println(basicEncryptor.checkPassword("My Very Strong Password", "leS3xZ9eavcmLdpry16TWShD84YqDZBf"));

This outputs:

true
true
true
true
true



errrr huh? Whats going on here? The answer is salting. For a fuller explanation read the JASYPT explanation

The BasicEncryptor uses MD5 as its encryption algorithm, if you decide that this isn't good enough for your needs you can always use the StrongPasswordEncryptor  that uses SHA-256 for its encryption.

   StrongPasswordEncryptor strongEncryptor = new StrongPasswordEncryptor();
   System.out.println(strongEncryptor.encryptPassword("My Very Strong Password"));

Which outputs pFzPnk1H8aitAjf4BdMRmKKQ1v6TzXUBCXAlsz+VXN/GK/bhd68IYO4f6+Wu2aRh

So whats your excuse for not doing it?