我知道以前曾问过这个问题,我不会再问我是否不明白我所读的内容-我正在实现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的示例代码,我也很喜欢这些建议。
谢谢 :)
这
byte[] plaintext = rsaDecrypt(data.getBytes(), privateKey, cipher);
应该
byte[] plaintext = rsaDecrypt(ciphertext, privateKey, cipher);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句