Hi,
I am trying to encrypt a symmetric key with a public key and then store the result in a database. This works fine but when I read the ciphertext from the database and try to decrypt the key with the corresponding private key I get a padding exception. I also encode the cipher text base64 before it is written to the DB and decode it once it is read from the DB.
The code to perform encryption is
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
byte[] enc_key = cipher.doFinal(secretKey.getEncoded());
key = new
String(new BASE64Encoder().encode(enc_key));
key written to database.
key read from database.
The code to perform decryption is:
key = new String(new BASE64Decoder().decodeBuffer(old_key));
Cipher cipher1 = Cipher.getInstance("RSA");
cipher1.init(Cipher.DECRYPT_MODE,privateKey);
byte[] clear_key = cipher1.doFinal(key.getBytes()); // Padding error here
Error:
javax.crypto.BadPaddingException: Not PKCS#1 block type 2 or Zero padding
at com.ibm.crypto.provider.RSA.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(Unknown Source)
at encryptdata_.readkey(encryptdata_.java:98)
at encryptdataClient_.main(encryptdataClient_.java:19)
Does anyone have any ideas as I have run out of options. Thanks in advance.