尝试解密时获取BadPaddingException-Java

我有这种加密方法:

private byte[] encrypt(byte[] data) throws NoSuchAlgorithmException,NoSuchPaddingException,InvalidKeyException,IllegalBlockSizeException,BadPaddingException {
    Cipher cipher = Cipher.getInstance("RSA/ECB/pkcs1Padding");
    cipher.init(Cipher.ENCRYPT_MODE,myPublicKey);
    ByteArrayInputStream input = new ByteArrayInputStream(data);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[64];
    int bytes;
    ByteArrayOutputStream aux;
    try {
        while ((bytes = input.read(buffer)) != -1) {
            aux = new ByteArrayOutputStream();
            aux.write(buffer,bytes);
            byte[] fragment = aux.toByteArray();
            byte[] encryptedFragment = cipher.doFinal(fragment);
            output.write(encryptedFragment);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    byte[] result = output.toByteArray();
    return result;
}

还有一个用于解密:

public static String decrypt(byte[] data) throws NoSuchPaddingException,NoSuchAlgorithmException,BadPaddingException,IOException {
    Cipher cipher = Cipher.getInstance("RSA/ECB/pkcs1Padding");
    cipher.init(Cipher.DECRYPT_MODE,myPrivateKey);
    int bitLenght = ((java.security.interfaces.RSAPrivateKey) privateKey).getmodulus().bitLength();
    int blockSize = bitLenght / 8;
    byte[] buffer = new byte[blockSize];
    int bytes;
    byte[] decrypted;
    ByteArrayOutputStream aux;
    ByteArrayInputStream input = new ByteArrayInputStream(data);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while ((bytes = input.read(buffer)) != -1) {
        aux = new ByteArrayOutputStream();
        aux.write(buffer,bytes);
        byte[] fragment = aux.toByteArray();

        byte[] decryptedFragment = cipher.doFinal(fragment);
        output.write(decryptedFragment);
    }
    decrypted = output.toByteArray();

    return new String(decrypted);
}

但是我遇到了这个异常:

  

javax.crypto.BadPaddingException:解密错误

正如我所看到的,我已将密码配置为具有相同的pkcs1Padding,所以我不知道为什么会收到该错误。

我已如下创建我的私钥:

openssl genrsa -out myPrivateKey.key 2048

和公众一个:

openssl rsa -in myPrivateKey.pem -pubout -out myPublicKey.key

据我所见,它们都是pkcs1,实际上我的私钥以-----BEGIN RSA PRIVATE KEY-----开头。

我想念什么?

注意:我也尝试过blockSize = 64,结果也一样。

xzsytc 回答:尝试解密时获取BadPaddingException-Java

加密流-正确地,您应该在循环中让cipher.update(..)并且在处理所有数据之后仅.doFinal(..)调用一次。

解密时,如果您对部分消息调用doFinal,则可能会遇到异常。无论这是您面临的问题,从代码中看不出来。 (假设您正确导入了密钥对)

实际上RSA仅用于短(117字节)消息。否则,您可以搜索“混合加密”

P。 S .:您对流和数组的处理过程一直在追求最佳化,因此也请看一下,但这是另一个问题

本文链接:https://www.f2er.com/2891297.html

大家都在问