died2369
fernando_fox
2019-01-14 19:50
采纳率: 57.1%
浏览 2.8k
已采纳

java使用Cipher 执行RSA解密报错

padding选取都是一样的,加密成功,解密失败,很奇怪。

#主要代码
public static byte[] rsa_encrypt(byte[] bArr, byte[] bArr2) {
try {
Key a = MyKey.getPublicKey(bArr2);
if(a == null)
System.out.println("get pub key error!");
Cipher instance = Cipher.getInstance("RSA/ECB/PKCS1Padding");
instance.init(Cipher.ENCRYPT_MODE, a);
return instance.doFinal(bArr);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

public static byte[] rsa_decrypt(byte[] bArr, byte[] bArr2) {
    try {
        Key a = MyKey.getPrivateKey(bArr2);
        if(a == null)
            System.out.println("get pri key error!");

        Cipher instance = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        instance.init(Cipher.DECRYPT_MODE, a);
        return instance.doFinal(bArr);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

#报错信息
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at qqpinyin.EncryptTool.rsa_decrypt(EncryptTool.java:134)
at qqpinyin.main.key_decrypt(main.java:80)
at qqpinyin.main.main(main.java:96)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • qq_31055671
    qq_31055671 2019-01-15 00:01
    已采纳

    bArr 多大?加密 buffer 至少要和 public key-11 一樣大(比方 117), 解密buffer 至少要和 public key 同大(比方 128)。

    点赞 评论
  • caozhy
    点赞 评论

相关推荐