繁体   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