RSA解密時BadPaddingException Decryption error

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 {
            System.out.println("ciphertext"+ciphertext);
            inputByte = Base64.decodeBase64(ciphertext.getBytes("UTF-8"));
            decoded = Base64.decodeBase64(privateKey);
            pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decoded);
            priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec);
            cipher = Cipher.getInstance("RSA");// RSA解密   改成"RSA/ECB/PKCS1Padding"
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            plaintext = new String(cipher.doFinal(inputByte));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return plaintext;
    }

 

  windows 系統校驗沒問題到了ubuntu 系統就報錯

  BadPaddingException  Decryption error 

 

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

搞定

 

還遇到過get傳的加密數據沒有urldecode,導致+全變成 空格,導致解密失敗

解決方式:對url進行轉義,java可使用URLEncoder.encode(url)  ,javaScript 裏使用encodeURIComponent(url)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章