使用非对称加密时的IllegalBlockSize异常(公共私钥编码)

时间:2018-10-21 19:48:43

标签: java encryption rsa private-key encryption-asymmetric

我已经在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(字符串消息,PrivateKey密钥):

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");

非常感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

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