简体   繁体   English

解密RSA数据时出错Java:javax.crypto.BadPaddingException:解密错误

[英]Error in decryption of RSA data Java: javax.crypto.BadPaddingException: Decryption error

I have problem with decryption (or maybe wrong encryption, too) of data with RSA in Java. 我在Java中使用RSA解密数据(或者也可能是错误的加密)也有问题。 I wanna encrypt public key with some more info in String and then decrypt this public key and encrypt with it something (I use 2048 RSA): 我想用String中的更多信息加密公钥,然后解密这个公钥并用它加密(我使用2048 RSA):

Encryption: 加密:

public void saveExportToFile(String fileName, BigInteger mod, BigInteger exp, String info, PublicKey puk) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(baos));
    try {
        oout.writeObject(mod);
        oout.writeObject(exp);
        oout.writeChars(info);
        oout.close();
        baos.close();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, puk);

        FileOutputStream fos = new FileOutputStream(new File(fileName));
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] data = baos.toByteArray();

        int i = 0;
        byte[] buffer = new byte[128];
        byte[] cipherData = null;
        while (i < data.length) {
            if (i+128 >= data.length) {
                buffer = new byte[data.length - i];
                System.arraycopy(data, i, buffer, 0, data.length - i);
                cipherData = cipher.doFinal(buffer);
                bos.write(cipherData);
            } else {
                System.arraycopy(data, i, buffer, 0, 128);
                cipherData = cipher.doFinal(buffer);
                bos.write(cipherData);
            }
            i += 128;
        }

        bos.close();
    } catch (Exception e) {
        throw new IOException("Unexpected error", e);
    }
}

Decryption: 解密:

public void getDataFromRSA(String sendname, PrivateKey privateKey) {
    try {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(sendname)));

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        int length = 0;
        int allLength = 0;
        byte[] buffer = new byte[128];
        byte[] bufferAC = null;
        byte[] outData = null;
        byte[] allData = null;
        byte[] tmpData = null;
        while ( (length = bis.read(buffer)) != -1) {
            if (length < 128) {
                bufferAC = new byte[length];
                System.arraycopy(buffer, 0, bufferAC, 0, length);
                outData = cipher.doFinal(bufferAC);
            } else {
                outData = cipher.doFinal(buffer); // HERE IS THE ERROR
            }
            allLength += outData.length;
            tmpData = allData;
            allData = new byte[allLength];
            System.arraycopy(tmpData, 0, allData, 0, tmpData.length);
            System.arraycopy(outData, 0, allData, tmpData.length, outData.length);
        }
    } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | ClassNotFoundException | InvalidKeySpecException e) {
        e.printStackTrace();
    }
}

EDIT OK, it seems I don't know about encryption as much as I thought. 编辑好吧,似乎我不像我想的那样知道加密。 I'd like to use only RSA (if it's possible) since I don't need to transfer info more than once (size of info vary). 我只想使用RSA(如果可能的话),因为我不需要多次传输信息(信息大小各不相同)。 I've edited encryption like this: 我编辑了这样的加密:

int i = 0;
byte[] buffer = new byte[245];
byte[] cipherData = null;
while (i < data.length) {
    if (i+245 >= data.length) {
        buffer = new byte[data.length - i];
        System.arraycopy(data, i, buffer, 0, data.length - i);
    } else {
        System.arraycopy(data, i, buffer, 0, 245);
    }
    cipherData = cipher.update(buffer);
    bos.write(cipherData);
    i += 245;
}
bos.write(cipher.doFinal()); // HERE IS THE ERROR
bos.close();

And now I get javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes (tried several lower values for buffer size). 现在我得到javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes (尝试缓冲区大小的几个较低值)。 Is it because data length is not multiple of blocksize? 是因为数据长度不是blocksize的倍数? Could this be fixed? 这可以解决吗? Thanks for answers. 谢谢你的回答。

First of all, you should be using hybrid encryption, ie first encrypt the data using a symmetric cipher and then encrypt the random secret with an RSA key - sending both to the receiver. 首先,您应该使用混合加密,即首先使用对称密码加密数据,然后使用RSA密钥加密随机密钥 - 将两者都发送到接收器。

Second, you should never have to perform doFinal in a loop for a single message. 其次,您不应该在循环中为单个消息执行doFinal Use update and a single doFinal instead. 使用update和单个doFinal代替。

And thirdly, 2048 bits is 256 bytes. 第三,2048位是256字节。 As long as you keep trying to decrypt 128 bytes instead of 256, you will get this exception. 只要您继续尝试解密128个字节而不是256个字节,您将获得此异常。 Usually I use 2048 / Byte.SIZE instead, it makes the code more readable and will avoid mistakes. 通常我使用2048 / Byte.SIZE ,它使代码更具可读性并避免错误。

This exception occurs when you try to encrypt data with private key and decrypt with public key, you need to reverse this or you have to use a single key to encrypt and decrypt your data. 当您尝试使用私钥加密数据并使用公钥解密时,会发生此异常,您需要撤消此操作,或者必须使用单个密钥来加密和解密数据。 This would solve this exception. 这将解决此异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RSA加密Android和Java中的解密:javax.crypto.BadPaddingException:解密错误 - RSA encryption Android and decryption in Java: javax.crypto.BadPaddingException: Decryption error RSA密钥块包装器:javax.crypto.BadPaddingException:解密错误 - RSA keyblock wrapper: javax.crypto.BadPaddingException: Decryption error javax.crypto.BadPaddingException:解密错误 - javax.crypto.BadPaddingException : Decryption error javax.crypto.BadPaddingException:解密错误 - javax.crypto.BadPaddingException: Decryption error 线程“main”中的异常 javax.crypto.BadPaddingException:Java 中的解密错误 - Exception in thread “main” javax.crypto.BadPaddingException: Decryption error in Java javax.crypto.BadPaddingException:使用Java RSA加密时出现解密错误 - javax.crypto.BadPaddingException: Decryption error when using Java RSA encryption RSAPrivateKeySpec javax.crypto.BadPaddingException中的Java RSA密钥:解密错误 - Java RSA key from RSAPrivateKeySpec javax.crypto.BadPaddingException: Decryption error RSA解密期间的javax.crypto.BadPaddingException - javax.crypto.BadPaddingException during RSA Decryption Java - 解密:javax.crypto.BadPaddingException - Java - Decryption : javax.crypto.BadPaddingException 线程“主”中的异常javax.crypto.BadPaddingException:解密错误 - Exception in thread “main” javax.crypto.BadPaddingException: Decryption error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM