只要私鑰保持祕密我要爲安全保密,解密,當我在我的應用程序出現以下錯誤:javax.crypto中.BadPaddingException:鑑於最終塊未正確填充的Java加密通過客戶端和解密的服務器,使用PBKDF2WithHmacSHA1和AES/CBC/PKCS5Padding
代碼:
// 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
是它的鹽是導致問題的隨機性?
我可以罰款解密它,當我使用在客戶端的對象引用的,但我需要在服務器上我自己的情況。
十分感謝提前糾正我的錯誤(S)!
* 編輯:*代碼更新和糾正
的襯墊例外指向該代碼順便說一句:字符串明文=新字符串(cipher2.doFinal(密文), 「UTF-8」); – gorn
你有沒有使用SSL的原因? – NullUserException