我知道之前已经问过这个问题,我不会再问我是否不明白我读过的内容 - 我实现了一个简单的RSA算法演示 - 加密消息,解密和打印输出,但控制台显示代码中抛出的BadPaddingException:
这是代码和控制台输出:
代码
public class RSA {
public static void main (String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048); // 1024 or 2048
KeyPair kp = kpg.generateKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();
Cipher cipher = generateCipher();
String data = "abcdefghijklmnop\0\0\0";
System.out.println("Plaintext: " + data);
byte[] ciphertext = rsaEncrypt(data.getBytes(), publicKey, cipher);
System.out.println("Ciphertext: " + ciphertext);
byte[] plaintext = rsaDecrypt(data.getBytes(), privateKey, cipher);
System.out.println("Decrypted Plaintext: " + plaintext);
}
public static Cipher generateCipher() throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher cipher = Cipher.getInstance("RSA");
return cipher;
}
public static byte[] rsaEncrypt(byte[] data, Key publicKey, Cipher cipher) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
}
public static byte[] rsaDecrypt(byte[] data, Key privateKey, Cipher cipher) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherData = cipher.doFinal(data); // error line: at learning.RSA.rsaDecrypt(RSA.java:43)
return cipherData;
}
}
控制台
Plaintext: abcdefghijklmnop
Ciphertext: [B@346cd0f9
Exception in thread "main" javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:329)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:272)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at learning.RSA.rsaDecrypt(RSA.java:43)
at learning.RSA.main(RSA.java:26)
同样,不是要求解决方案,而是希望对概念填充的解释 - 如果您有任何有关实施RSA的示例代码的良好资源,我也会喜欢这些建议。
谢谢:)
答案 0 :(得分:1)
此
byte[] plaintext = rsaDecrypt(data.getBytes(), privateKey, cipher);
应该是
byte[] plaintext = rsaDecrypt(ciphertext, privateKey, cipher);