Reputation: 8177
I'm going for secure confidentiality as long as the private key stays secret, and I get following error in my app when decrypting: javax.crypto.BadPaddingException: Given final block not properly padded
The code:
// Encryption, client side
byte[] plainData = "hello plaintext!".getBytes("UTF-8");
byte[] salt = new byte[64];
new SecureRandom().nextBytes(salt);
KeySpec spec = new javax.crypto.spec.PBEKeySpec("password".toCharArray(), salt, 1024, 256);
SecretKey sk = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sk.getEncoded(), "AES"));
byte[] iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal(plainData);
System.out.println("ciphertext: "+new String(ciphertext, "UTF-8")); // cipher
// Decryption, server side
KeySpec spec2 = new javax.crypto.spec.PBEKeySpec("password".toCharArray(), salt, 1024, 256);
SecretKey sk2 = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec2);
Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher2.init(Cipher.DECRYPT_MODE, new SecretKeySpec(sk2.getEncoded(), "AES"), new IvParameterSpec(iv)); // Get the same IV value from client/encryptor aswell, still random
String plaintext = new String(cipher2.doFinal(ciphertext), "UTF-8");
System.out.println("decrypted plaintext: "+plaintext); // plain
Is it the randomness of salt that causing the problem?
I can decrypt it fine when I make use of the object references on the client side, but I need my own instances on the server.
Great thanks in advance for correcting my error(s)!
*EDIT: * Code updated and corrected
Upvotes: 1
Views: 6744
Reputation: 378
Just from quickly looking at your code I can see that you are creating a different salt at the client and server side. In order for the server side to be able to decrypt that salt and the key have to be the same.
Now I'm not a Java developer but all the other code to me looks ok but like I said if you are creating a different salt at each end the decryption is not going to work.
Upvotes: 4