Exception in thread "main" javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.a(DashoA12275)
at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA12275)
at javax.crypto.Cipher.doFinal(DashoA12275)
at CipherTest.rsaEncrypt(CipherTest.java:33)
at CipherTest.main(CipherTest.java:40)
RSA是一种对称加密算法,但加密时出现这个错误的原因,是因为使用了私钥进行加密.
正常应该使用公钥进行加密,然后通过私钥进行解密.
代码:
KeyPair keypair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
String str = "hello world";
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.PUBLIC_KEY, keypair.getPublic());
byte[] buffer = cipher.doFinal(str.getBytes());
cipher.init(Cipher.PRIVATE_KEY, keypair.getPrivate());
System.out.println(new String(cipher.doFinal(buffer)));