javax.crypto.BadPaddingException:解密错误

时间:2015-07-14 04:57:38

标签: java android encryption

我正在尝试在客户端和服务器之间实现基于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字节,因此长度不应成为问题。

任何帮助都会有所帮助。

由于

1 个答案:

答案 0 :(得分:2)

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

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

那里有很多帖子。

您可以参考

RSA BadPaddingException in Java - encrypt in Android decrypt in JRE

RSA Encryption: Difference between Java and Android