报错问题解决办法:Decryption error sun.security.rsa.RSAPadding.unpadV15

报错问题解决办法:Decryption error sun.security.rsa.RSAPadding.unpadV15

出现的问题

javax.crypto.BadPaddingException: Decryption error
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380) ~[na:1.8.0_131]
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291) ~[na:1.8.0_131]
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356) ~[sunjce_provider.jar:1.8.0_112]
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389) ~[sunjce_provider.jar:1.8.0_112]
    at javax.crypto.Cipher.doFinal(Cipher.java:2048) ~[na:1.8.0_121]

解决办法:
采用相同提供者组件
com.sun.crypto.provider.SunJCE

SunJCE provider=new com.sun.crypto.provider.SunJCE();
Security.addProvider(provider);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm(),provider);
//必须自己生成下面两个密钥
    private static final String PUBLIC_KEY = "自己生成公钥";
    private static final String PRIVATE_KEY="自己生成私钥";
    //

调用方法:

String pwd = RsaUtil.DecryptByPrivateKey(pwd_web);
String web=RsaUtil.encryptByPublicKey(pwd);
String pwd2 = RsaUtil.DecryptByPrivateKey(web);

执行的两个方法代码:

//加密-公 OK
    public static String encryptByPublicKey(String data)
    {
        String r="";
        try {
            byte[] itemResultBytes = encryptByPublicKey(data, PUBLIC_KEY);
            r= Base64.encode(itemResultBytes);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("encryptByPublicKey加密出错:" + e.getMessage() + ":" + "加密内容:" + data);
            throw new RuntimeException("rsa加密失败");
        }
        return r;
    }

    //解密-私    OK
    public static String DecryptByPrivateKey(String content)
    {
        return jsencryptDecryptByPrivateKeyLong(content,PRIVATE_KEY);
    }

你可能感兴趣的:(Java,java,开发语言)