javax.crypto.BadPaddingException : Decryption error

标签 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格式 key ,由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: Decryption error 问题。数据的长度恰好是 256 字节,因此长度应该不是问题。

任何帮助都会很有帮助。

谢谢

最佳答案

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

关于javax.crypto.BadPaddingException : Decryption error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31397958/

相关文章:

android - 如何在 Cordova 项目中找到 SHA1

apache - 如何确保客户端能够使用强密码连接到 SSL 连接

mysql - MYSQL 中加密数据的数据类型

java - 如何创建透明的 JPanel

java - Android onTap Intent 数组

java - Spring JSR-303 bean 验证不起作用,绑定(bind)结果为空

c++ - Cryptoauthlib - 匿名 union 只能有非静态数据成员 - 段错误

带有 CSS 的 JavaFX TextArea 样式

android - connectedAndroidTest 和 release 构建类型

android - 在根项目 'android' React Native 中找不到“installDebug”