客户端Java加密和服务器解密,使用PBKDF2WithHmacSHA1和AES / CBC / PKCS5Padding

时间:2011-11-30 01:33:36

标签: java encryption cryptography padding jce

只要私钥保密,我就会采取安全保密措施,并且在解密时我的应用程序中出现以下错误:javax.crypto.BadPaddingException:给定最终块没有正确填充

代码:

// 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

导致问题的是盐的随机性吗?

当我在客户端使用对象引用时,我可以解密它,但我需要在服务器上使用自己的实例。

非常感谢您提前纠正我的错误!

* 编辑:* 代码已更新并更正

1 个答案:

答案 0 :(得分:4)

只需快速查看代码,我就可以看到您在客户端和服务器端创建了不同的salt。为了让服务器端能够解密该盐,密钥必须相同。

现在我不是Java开发人员,但对我来说所有其他代码看起来还不错,但就像我说的那样,如果你在每一端创建一个不同的盐,那么解密就不会起作用。