简体   繁体   中英

Java encryption by client and decryption by server, using PBKDF2WithHmacSHA1 and AES/CBC/PKCS5Padding

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM