Java passphrase encryption

skiphoppy picture skiphoppy · Dec 16, 2008 · Viewed 16k times · Source

I'm trying to learn how to do passphrase-based encryption with Java. I'm finding several examples online, but none (yet) on Stack Overflow. The examples are a little light on explanation for me, particularly regarding algorithm selection. There seems to be a lot of passing strings around to say what algorithms to use, but little documentation as to where the strings came from and what they mean. And it also seems like the different algorithms may require different implementations of the KeySpec class, so I'm not sure what algorithms can use the PBEKeySpec class I'm looking at. Furthermore, the examples all seem a little out of date, many requiring you to get an older cryptography package that used to not be part of the JDK, or even a third-party implementation.

Can someone provide a straightforward introduction to what I need to do to implement encrypt(String data, String passphrase) and decrypt(byte[] data, String passphrase)?

Answer

Zach Scrivena picture Zach Scrivena · Dec 17, 2008

I'll be cautious about giving or taking security-related advice from a forum... the specifics are quite intricate, and often become outdated quickly.

Having said that, I think Sun's Java Cryptography Architecture (JCA) Reference Guide is a good starting point. Check out the accompanying code example illustrating Password-Based Encryption (PBE).

Btw, the standard JRE provides only a few options out-of-the-box for PBE ("PBEWithMD5AndDES" is one of them). For more choices, you'll need the "strong encryption pack" or some third-party provider like Bouncy Castle. Another alternative would be to implement your own PBE using the hash and cipher algorithms provided in the JRE. You can implement PBE with SHA-256 and AES-128 this way (sample encrypt/decrypt methods).

Briefly, the encrypt method for PBE may involve the following steps:

  1. Get password and cleartext from the user, and convert them to byte arrays.
  2. Generate a secure random salt.
  3. Append the salt to the password and compute its cryptographic hash. Repeat this many times.
  4. Encrypt the cleartext using the resulting hash as the initialization vector and/or secret key.
  5. Save the salt and the resulting ciphertext.