I am trying to encrypt text using the AES encryption algorithm , save this encrypted text to a file and then reopen later and decrypt these. Following is my encryption and decryption logic
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] stringBytes = clear_text.getBytes();
byte[] raw = cipher.doFinal(stringBytes);
return Base64.encodeBase64String(raw);
And this is the decryption logic
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] raw = Base64.decodeBase64(encText);
byte[] stringBytes = cipher.doFinal(raw);
String clear_text = new String(stringBytes, "UTF8");
return clear_text;
I get a BadPaddingSize exception. My guess is that by using the SecureRandom class, both the methods use different keys while encrypting or decypting text. Is there a way I can use the same key in both the routines?
Yes, you can use the same key; it is even required to use the same key. You should however never use the same key / IV combination as that is not secure. So often the IV gets prefixed to the ciphertext instead.
Note that the following implementation shows you how to generate the random IV without
SecureRandom
, but that's a bit disingenious as theCipher
class will just use the default one internally to create the IV. For CBC the IV may be known to an attacker, but the attacker should not be able to distinguish it from random data.In this example the key data is simply stored within a "constant". Storing the key within source code may not provide enough security. Instead it is often encrypted with a public key, password, stored on a USB key, stored within a smartcard or HSM etc. etc. Key management is however a vast subject so I won't discuss it further for this answer.
In Java you should however use
SecretKey
/SecretKeySpec
to create keys from known data andIvParameterSpec
for a known IV (or Nonce).With a key store (you have to use JCEKS for now):