本文介绍了如何在不运行“ javax.crypto.IllegalBlockSizeException:数据不得超过117个字节”的情况下使用RSA加密AES密钥的方法。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为项目构建一个简单的授权服务器。服务器必须分发AES密钥,以允许其客户端彼此通信。

I have to build a simple authorization server for a project. The server has to distribute AES keys to allow its clients to communicate with each other.

使用RSA加密AES密钥时,我遇到此错误: javax.crypto .IllegalBlockSizeException:数据不得超过117个字节。
这很奇怪,因为我的AES密钥的长度是128位= 16个字节。

When encrypting the AES key using RSA, I run into this error: "javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes".Which is weird, since the lenght of my AES key is 128 bits = 16 bytes.

这是生成错误的代码:

private void createAndSendAES() throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, IOException, InvalidKeyException, BadPaddingException {
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    this.AESBlackboardKey = keyGen.generateKey(); // My AES key

     byte[] raw = AESBlackboardKey.getEncoded();
     System.out.println(raw.length); // Prints 16

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, this.clientPubKey);


    SealedObject encryptedAESBlackboardKey = new SealedObject(this.AESBlackboardKey, cipher); // ERROR HERE

    ObjectOutputStream outO = new ObjectOutputStream(this.clientSocket.getOutputStream());
    outO.writeObject(encryptedAESBlackboardKey); //Transmitting the key over socket link
    outO.flush();

    System.out.println("AS: Blackboard AES key sent.");

}

有人知道如何加密16字节长的AES键让我碰到这种错误以及如何避免它?

Does someone know how the encryption of a 16 bytes long AES key makes me run into this kind of error and how to avoid it ?

预先感谢!

推荐答案

出现错误的原因是保存了整个对象,而不仅仅是组成键的16个字节。所以你会

The reason why you are getting the error is that the whole object is saved, not just the 16 bytes that make up the key. So you will e.g. have the full class name in there, the serial number of the class etcetera.

如果您想继续使用 SealedObject

If you want to keep using SealedObject then I would suggest encryption with a new random AES key and "AES/CBC/PKCS5Padding". You can then encrypt that key using the RSA algorithm (be sure to specify it fully, e.g. "RSA/NONE/OAEPPadding" or "RSA/NONE/PKCS1Padding") simply by using Cipher.doFinal().

您可以

另一种方法是简单地增加RSA密钥的大小。 RSA密钥大小1024受到越来越多的威胁,请尝试最小使用2048密钥大小(允许256-11 = 245字节存储空间)。

Another method is to simply increase the RSA key size; the RSA key size of 1024 is increasingly under threat, try to use a key size of 2048 at the bare minimum (allowing 256 - 11 = 245 bytes of storage).

请注意,您可以使用 key.getEncoded()从先前创建的AES密钥中检索16个字节。

Note that you can retrieve the 16 bytes from a previously created AES key by using key.getEncoded().

这篇关于如何在不运行“ javax.crypto.IllegalBlockSizeException:数据不得超过117个字节”的情况下使用RSA加密AES密钥的方法。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 06:29