簡體   English   中英

javax.crypto.BadPaddingException:解密錯誤

[英]javax.crypto.BadPaddingException : Decryption error

我正在嘗試在客戶端和服務器之間實施基於RSA的加密通信。 為此,我以以下方式使用openssl生成了RSA公鑰和私鑰:

 openssl genrsa -out private.pem 2048 openssl rsa -in private.pem -outform PEM -pubout -out public.pem --generate modulus and exponent openssl rsa -pubin -in public_key.pem -modulus -noout openssl rsa -pubin -in public_key.pem -text -noout 

使用上述文件,可以在Android端進行加密,如下所示:

   public static byte[] encrypt(BigInteger modulus, BigInteger exp, byte[] data) {
        try {
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exp);
            PublicKey publicKey = kf.generatePublic(keySpec);
            final Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        } catch (Exception e) {
            FileLog.e("module" , e);
        }
        return null;
    }

這可以正常工作,並且可以加密數據。 現在在服務器端,我使用以下代碼進行解密。 私鑰存儲為pkcs8格式密鑰,由java讀取。

public static byte[] decrypt(byte[] data) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
    String fileName = "location/of/private_key/file";
    File f = new File(fileName);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int)f.length()];
    dis.readFully(keyBytes);
    dis.close();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey rsaPrivate = kf.generatePrivate(spec);
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, rsaPrivate);
    return cipher.doFinal(data);
    }

在服務器上使用eclipse運行此命令時,出現BadPaddingException:解密錯誤問題。 數據的長度正好是256個字節,因此長度不應該成為問題。

任何幫助將是真正有幫助的。

謝謝

Android使用不同的填充算法。 您需要使用其他類似如下的算法:

Cipher CheckCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

那里有辭職人數。

你可以參考

Java中的RSA BadPaddingException-在Android中加密在JRE中解密

RSA加密:Java和Android之間的區別

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM