[英]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 只要私钥保密,我就会安全保密,并且在解密时我的应用程序中出现以下错误:javax.crypto.BadPaddingException:给定最终块没有正确填充
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. 只需快速查看代码,我就可以看到您在客户端和服务器端创建了不同的salt。 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. 现在我不是Java开发人员,但是对我来说所有其他代码看起来还不错,但就像我说的那样,如果你在每一端创建一个不同的盐,那么解密就不会起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.