java - 使用非对称加密(公共(public)私钥 Enc)时出现 IllegalBlockSize 异常

标签 java encryption rsa private-key encryption-asymmetric

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

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

我为用户 A 生成 key 的代码:

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

方法 AmetryCryptography.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");

非常感谢任何帮助。谢谢。

最佳答案

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

关于java - 使用非对称加密(公共(public)私钥 Enc)时出现 IllegalBlockSize 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52919233/

相关文章:

java - 如何在多线程JAVA环境中保护对象而不损失性能?

sql - 使用 SQL 加密更新生产数据库 - 批量更新快捷方式?

openssl - 为什么OpenSSL RSA_sign函数需要int类型参数?

java - ProcessBuilder 找不到 perl

java - 将 SQL-INSERT 拆分为 Map 列名称 > 值

c++ - 如何在 C++ 中递增字母?

c - OpenSSL RSA 签名验证 : hash and padding?

encryption - 在PKCS#1 OAEP加密/解密中交换公钥/私钥

java - GridBagLayout 中未显示的元素

encryption - 使用 RSA 加密,我应该使用相同的证书来签署和加密消息吗?