I fully agree with Ulf and have already created a hardcoded key using byte[]. Per Pat, I don't plan to ask the user for a key, and neither do I plan to store a key (since it's hardcoded).
So what am I trying to do? Below is an implementation similar to the one I'm attempting... the critical question is how to use the SAME key (i.e., keyBytes or something else) to call in m_cipher.init()? Note that the TODO label is the location where the key is newly GENERATED everytime- something I do NOT want to do. This is because the data encrypted in the database may have used a different GENERATED key (I want a hardcoded key, not a GENERATED key). Any help would be appreciated:
=====================================================
private static Cipher m_cipher = null;
private static SecretKeySpec m_keySpec = null;
private static void initEncryption() throws Exception {
final byte[] keyBytes = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
//TODO: how can I use a hardcoded (not GENERATED) key each time?
m_keySpec = new SecretKeySpec(keyBytes, "AES");
System.out.println("Key: " + asHex(m_keySpec.getEncoded()));
m_cipher = Cipher.getInstance(m_keySpec.getAlgorithm());
}
public static
String decryptString(String encrypted) throws Exception {
System.out.println("decryptString- input text: " + encrypted);
byte[] input = encrypted.getBytes();
String decryptedText = null;
byte[] decryptedByte = null;
m_cipher.init(Cipher.DECRYPT_MODE, m_keySpec);
decryptedByte = m_cipher.doFinal(input);
decryptedText = new String(decryptedByte);
System.out.println("decrypted text: " + decryptedText);
return decryptedText;
}
public static String encryptString(String decrypted) throws Exception {
System.out.println("encryptString- input text: " + decrypted);
byte[] input = decrypted.getBytes();
String encryptedText = null;
byte[] encryptedByte = null;
m_cipher.init(Cipher.ENCRYPT_MODE, m_keySpec);
encryptedByte = m_cipher.doFinal(input);
encryptedText = new String(encryptedByte);
System.out.println("encrypted text: " + encryptedText);
return encryptedText;
}