I'm a bit of an encryption newbie, but need to encrypt sensitive personal data before storing in a database. I was planning to use AES with CBC, but also wanted to use a salt. I couldn't however find a way to do this (other than with BouncyCastle which my host is not prepared to allow for some reason) so I decided to add one myself by adding a random string to end of the text to be encrypted:
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
String plainText = "This is my plain text";
System.out.println("**plainText: " + plainText);
String saltedPlainText = plainText + UUID.randomUUID().toString().substring(0, 8);
byte[] encrypted = cipher.doFinal(saltedPlainText.getBytes());
String encryptedText = new String(new Hex().encode(encrypted));
System.out.println("**encryptedText: " + encryptedText);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
byte[] decrypted = cipher.doFinal(new Hex().decode(encryptedText.getBytes()));
saltedPlainText = new String(decrypted);
plainText = saltedPlainText.substring(0, saltedPlainText.length()-8);
System.out.println("**plainText: " + plainText);
I guess I have 3 questions:
- Is there a better way of including a salt in my encryption?
- In examples similar to this one, it always seems that a random key is generated at the start and the decryption is done immediately after the encryption. This is an unlikely scenario - so I've worked on the basis that I should use the same key each time (seems like a no-brainer but all examples I've seen seem to go random). Can't see how else it would work, but can someone confirm :)
- Working with a fixed key, I've noticed that if I keep encrypting the same string I do get a different result but only the end part of the encrypted result changes. Doesn't seem right. How come?
Many thanks, Neil