有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

尝试解密Java时加密获取BadPaddingException

我有以下加密方法:

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, 0, 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, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, 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, 0, bytes);
        byte[] fragment = aux.toByteArray();

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

    return new String(decrypted);
}

但我有一个例外:

javax.crypto.BadPaddingException: Decryption error

正如我所看到的,我已经将密码配置为具有相同的PKCS1Padding,所以我猜不出为什么会出现这种错误

我已按如下方式创建了私钥:

openssl genrsa -out myPrivateKey.key 2048

而公众方面:

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

就我所见,在这个命令中,它们都是PKCS1,实际上我的私钥以-----BEGIN RSA PRIVATE KEY-----开头

我错过了什么

注意:我还尝试了blockSize = 64,结果相同


共 (1) 个答案

  1. # 1 楼答案

    加密流——正确地说,您应该在循环中有cipher.update(..),并且在处理所有数据后只调用.doFinal(..)

    解密时,如果对部分消息调用doFinal,可能会出现异常。不管你的代码中是否存在这样的问题。(假设正确导入了密钥对)

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

    附言:你处理流和数组的方式迫切需要优化,所以也来看看吧,但这是另一个问题