获取IllegalBlockSizeException:使用rsa时,数据不能超过256个字节 [英] getting a IllegalBlockSizeException: Data must not be longer than 256 bytes when using rsa

查看:6621
本文介绍了获取IllegalBlockSizeException:使用rsa时,数据不能超过256个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用rsa密钥加密一个我将发送到我的服务器的长字符串(将使用服务器的公钥和我的私钥进行加密)但是它会抛出一个异常,如 javax.crypto.IllegalBlockSizeException :数据不能超过256字节
我觉得到目前为止我还没有明白rsa的正常工作(使用内建的库是造成这种情况的原因)。
可以有一些请解释为什么这个异常被抛出。发送长字符串加密是不是可能?

解决方案


RSA算法只能加密具有RSA密钥长度的最大字节长度
的数据除以8减去11个填充
字节,即最大字节数=密钥长度(以位/ 8-11为单位)。


所以基本上你将键长度与8 -11(如果你有填充)分开。例如,如果您有一个2048位密钥,您可以加密2048/8 = 256字节(如果您有填充,则为11个字节)。所以,要么使用较大的密钥,要么使用对称密钥加密数据,并使用rsa(这是推荐的方法)加密该密钥。



这将需要你到:


  1. 生成对称密钥

  2. 使用对称密钥加密数据

  3. 使用rsa

  4. 加密对称密钥发送加密密钥和数据

  5. 使用rsa解密加密对称密钥

  6. 用对称密钥解密数据

  7. done:)


I am using rsa key to encrypt a long string which I will send to my server(will encrypt it with server's public key and my private key) But it throws an exception like javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes I feel that I have not understood the working of rsa properly till now(using the inbuilt libraries are the cause for this).
Can some one please explain why this exception is being thrown. Is it not at all possible to send long string encrypted?

解决方案

The RSA algorithm can only encrypt data that has a maximum byte length of the RSA key length in bits divided with eight minus eleven padding bytes, i.e. number of maximum bytes = key length in bits / 8 - 11.

So basicly you divide the key length with 8 -11(if you have padding). For example if you have a 2048bit key you can encrypt 2048/8 = 256 bytes (- 11 bytes if you have padding). So, either use a larger key or you encrypt the data with a symmetric key, and encrypt that key with rsa (which is the recommended approach).

That will require you to:

  1. generate a symmetric key
  2. Encrypt the data with the symmetric key
  3. Encrypt the symmetric key with rsa
  4. send the encrypted key and the data
  5. Decrypt the encrypted symmetric key with rsa
  6. decrypt the data with the symmetric key
  7. done :)

这篇关于获取IllegalBlockSizeException:使用rsa时,数据不能超过256个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆