RSA解密时BadPaddingException Decryption error

时间:2025-03-27 18:41:39

public static String decryptRSA(String ciphertext, String privateKey) {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = null;
        RSAPrivateKey priKey = null;
        byte[] inputByte = null;// 64位解码加密后的字符串
        byte[] decoded = null;// base64编码的私钥
        Cipher cipher = null;
        String plaintext = "";
        try {
            ("ciphertext"+ciphertext);
            inputByte = Base64.decodeBase64(("UTF-8"));
            decoded = Base64.decodeBase64(privateKey);
            pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decoded);
            priKey = (RSAPrivateKey) ("RSA").generatePrivate(pkcs8EncodedKeySpec);
            cipher = ("RSA");// RSA解密   改成"RSA/ECB/PKCS1Padding"
            (Cipher.DECRYPT_MODE, priKey);
            plaintext = new String((inputByte));
        } catch (UnsupportedEncodingException e) {
            ();
        } catch (InvalidKeySpecException e) {
            ();
        } catch (NoSuchAlgorithmException e) {
            ();
        } catch (NoSuchPaddingException e) {
            ();
        } catch (InvalidKeyException e) {
            ();
        } catch (IllegalBlockSizeException e) {
            ();
        } catch (BadPaddingException e) {
            ();
        }
        return plaintext;
    }

 

  windows 系统校验没问题到了ubuntu 系统就报错

  BadPaddingException  Decryption error 

 

 cipher = ("RSA");// RSA解密   改成"RSA/ECB/PKCS1Padding"

搞定

 

还遇到过get传的加密数据没有urldecode,导致+全变成 空格,导致解密失败

解决方式:对url进行转义,java可使用(url)  ,javaScript 里使用encodeURIComponent(url)