1

只要私钥保密,我就会寻求安全的机密性,并且在解密时我的应用程序中出现以下错误: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

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

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

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

*编辑:*代码更新和更正

4

1 回答 1

4

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

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

于 2011-11-30T01:44:56.463 回答