Recently I had to work on encrypting some data, after doing some research on AES, DES, RC4, I settled on AES. I thought it might be useful to others as well; please feel free to use it. Basically I read key (string) from a file and do the encryption.
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
/**
* This program generates a AES key, retrieves its raw bytes, and
* then reinstantiates a AES key from the key bytes.
* The reinstantiated key is used to initialize a AES cipher for
* encryption and decryption.
*/
public class Encoders {
public static String doAes (String EncodeSring) throws Exception {
//get key(string) from a file
StringBuilder key = TemplateHandler.getTemplate("aesKeyFile");
byte[] rawKey = stringToKey (key.toString());
SecretKeySpec secretKey = new SecretKeySpec(rawKey, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypted = cipher.doFinal(EncodeSring.getBytes());
return asHex(encrypted);
}
/**
* Turns array of bytes into string
*
* @param buf Array of bytes to convert to hex string
* @return Generated hex string
*/
public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static byte[] stringToKey (String password) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance ("MD5");
} catch (NoSuchAlgorithmException ex) {
return new byte[0];
}
byte[] passwordBytes = null;
try {
passwordBytes = password.getBytes ("ISO-8859-1");
} catch (UnsupportedEncodingException ex) {
passwordBytes = new byte[0];
}
return md.digest(passwordBytes);
}
}
Wednesday, June 4, 2008
Subscribe to:
Posts (Atom)