首页 > 解决方案 > 使用非对称加密(公钥加密)时出现 IllegalBlockSize 异常

问题描述

我在Java中设置了公钥和私钥加密,并分发了两个用户的公钥(通信是两个用户之间)。我现在希望用户交换对称密钥。我应该做什么:

  1. 用户 A 生成密钥。
  2. 用户 A 用他的私钥加密密钥,然后用 B 的公钥加密它。
  3. 用户 A 发送加密密钥。
  4. 用户 B 收到加密密钥。
  5. 用户 B 用他的私钥解密密钥,然后用 A 的公钥解密。

我的用户 A 生成密钥的代码:

1. KeyGenerator keyGenerator = KeyGenerator.getInstance(ENCMETHOD);
2. SecureRandom secureRandom = new SecureRandom();
3. int keyBitSize = 128;
4. keyGenerator.init(keyBitSize, secureRandom);
5. secretKey = keyGenerator.generateKey();
6. encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());

// encrypt with public key of B and then my private key
7. String encryptedMessage = encodedKey;
8. encryptedMessage = ac.encryptText
               (
                        ac.encryptText(encryptedMessage, otherUserPublickey),
                        privateKey
                );

第 8 行抛出以下错误:

javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:344)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at driver.AsymmetricCryptography.encryptText(AsymmetricCryptography.java:73) // please refer to the code section below for this method
    at driver.ClientOne.main(ClientOne.java:158) // this is line 8 in the above code

AsymmetricCryptography.encryptText(String message, PrivateKey key)方法:

public String encryptText(String msg, PrivateKey key)
        throws
        UnsupportedEncodingException, IllegalBlockSizeException,
        BadPaddingException, InvalidKeyException {
        this.cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64.encodeBase64String(cipher.doFinal(msg.getBytes("UTF-8")));
}

// this.cipher = Cipher.getInstance("RSA");

任何帮助深表感谢。谢谢。

标签: javaencryptionrsaprivate-keyencryption-asymmetric

解决方案


看起来您超过了可以使用 RSA 加密的数据量(请参阅此处https://security.stackexchange.com/questions/44702/whats-the-limit-on-the-size-of-the-data-that -public-key-cryptos-can-handle ) 本质上是模数大小,可能是由于 Base 64 编码。


推荐阅读