Saturday, July 17, 2010

Programmatic Encryption in Java

I'm working on a program in my spare time that requires, among other things, storing a user's password. To avoid storing the password in plain text, I dug around the internet and cobbled together code that will encrypt and decrypt the password. Here's the code:


import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

private static final char[] password = new char[] {/*array of any number of
random characters*/};
private static final byte[] salt = new byte[] {/*array of 8 random bytes*/};
private static final String ENCRYPTION_ALGORITHM = "PBEWithMD5AndDES";
private static final PBEKeySpec key = new PBEKeySpec(password, salt, /*random
number, doesn't really matter what the number is*/);

private String decrypt(String value) {
return crypto(value, Cipher.DECRYPT_MODE);
}

private String encrypt(String value) {
return crypto(value, Cipher.ENCRYPT_MODE);
}

private String crypto(String value, int mode) {
String result = "ERROR";
try {
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
cipher.init(mode, SecretKeyFactory.getInstance(
ENCRYPTION_ALGORITHM).generateSecret(key),
new PBEParameterSpec(key.getSalt(),
key.getIterationCount()));
result = new String(cipher.doFinal(value.getBytes()));
} catch (Exception e) {
log.info("cryption failed: " + e.getMessage());
e.printStackTrace();
}
return result;
}