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

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

问题描述

我正在使用 rsa 密钥加密一个长字符串,我将发送到我的服务器(将使用服务器的公钥和我的私钥对其进行加密)但它抛出一个异常,如 javax.crypto.IllegalBlockSizeException: Data must不超过 256 字节我觉得到目前为止我还没有正确理解 rsa 的工作(使用内置库是导致此问题的原因).
请有人解释一下为什么会抛出此异常.发送加密的长字符串完全不可能吗?

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?

推荐答案

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

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.

所以基本上你将密钥长度除以 8 -11(如果你有填充).例如,如果您有一个 2048 位的密钥,您可以加密 2048/8 = 256 个字节(如果有填充,则为 - 11 个字节).因此,要么使用更大的密钥,要么使用对称密钥加密数据,然后使用 rsa 加密该密钥(这是推荐的方法).

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).

这将要求您:

  1. 生成对称密钥
  2. 使用对称密钥加密数据
  3. 使用 rsa 加密对称密钥
  4. 发送加密密钥和数据
  5. 使用 rsa 解密加密的对称密钥
  6. 使用对称密钥解密数据
  7. 完成:)

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

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