I'm working on an implementation related to encryption and decryption of a string and store it in the DB. I tried the following code for encrypting and decrypting using the singleton pattern. So that the instances are initialized only once in the application. But when restarting the application, the decryption fails with BadPaddingException. How can I handle it
public String encrypt(String strToEncrypt, EncryptionProperties encryptionProperties) {
try {
final IvParameterSpec ivspec = encryptionProperties.getIvParameterSpec();
encryptionProperties.getCipher().init(Cipher.ENCRYPT_MODE, encryptionProperties.getSecretKeySpec(), ivspec);
byte[] cipherText = encryptionProperties.getCipher().doFinal(strToEncrypt.getBytes("UTF-8"));
byte[] encryptedData = new byte[ivspec.getIV().length + cipherText.length];
System.arraycopy(ivspec.getIV(), 0, encryptedData, 0, ivspec.getIV().length);
System.arraycopy(cipherText, 0, encryptedData, ivspec.getIV().length, cipherText.length);
return Base64.encodeAsString(encryptedData);
} catch (Exception e) {
// Handle the exception properly
e.printStackTrace();
return null;
}
}
public String decrypt(String strToDecrypt, EncryptionProperties encryptionProperties) {
try {
byte[] encryptedData = Base64.decode(strToDecrypt);
final IvParameterSpec ivspec = encryptionProperties.getIvParameterSpec();
encryptionProperties.getCipher().init(Cipher.DECRYPT_MODE, encryptionProperties.getSecretKeySpec(), ivspec);
byte[] cipherText = new byte[encryptedData.length - 16];
System.arraycopy(encryptedData, 16, cipherText, 0, cipherText.length);
byte[] decryptedText = encryptionProperties.getCipher().doFinal(cipherText);
return new String(decryptedText, "UTF-8");
} catch (Exception e) {
// Handle the exception properly
e.printStackTrace();
return null;
}
}
I'm expecting to encrypt and decrypt the text seamlessly regardless of the classes it is accessed and service being restarted