data must not be longer than 256 bytes

编程入门 行业动态 更新时间:2024-10-24 06:25:53

data must not be <a href=https://www.elefans.com/category/jswz/34/1734201.html style=longer than 256 bytes"/>

data must not be longer than 256 bytes

1、问题:

在进行 RSA 解密时候报错:data must not be longer than 256 bytes

2、分析:

RSA加解密算法通常有两种不同的方式:

① 是使用对称密钥(比如 AES/ DES等加解密方法)加密数据,然后使用非对称密钥(RSA加解密密钥)加密对称密钥;

② 是直接使用非对称密钥加密数据。

第一种方式安全性高,复杂度也高,不存在加密数据长度限制问题。

第二种方式安全性比起第一种要差一些,复杂度低,但是存在加密数据限制问题(即使用非对称密钥加密数据时,一次加密的数据长度是(密钥长度/8-11))。

此次报错即这里第二种的问题,长度限制。

3、解决方案

报错前使用的解密代码

   /*** 解密算法** @param cryptoGraph 密文*/public static String decrypt(String cryptoGraph, String privateKey) throws Exception {Key key = getPrivateKey(privateKey);// 得到Cipher对象对已用公钥加密的数据进行RSA解密Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);cipher.init(DECRYPT_MODE, key);// 执行解密操作return new String(cipher.doFinal(Base64Utils.decode(cryptoGraph.getBytes())));}

报错修改之后使用的解密算法

/*** 解密算法** @param cryptoGraph 密文*/public static String maxResultDecrypt(String cryptoGraph, String privateKey) throws Exception {Key key = getPrivateKey(privateKey);// 得到Cipher对象对已用公钥加密的数据进行RSA解密Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);cipher.init(DECRYPT_MODE, key);// 执行解密操作return new String(getMaxResultDecrypt(cryptoGraph, cipher));}//长度过长分割解密private static byte[] getMaxResultDecrypt(String str, Cipher cipher) throws IllegalBlockSizeException, BadPaddingException {byte[] inputArray = Base64Utils.decode(str.getBytes(StandardCharsets.UTF_8));int inputLength = inputArray.length;// 最大解密字节数,超出最大字节数需要分组加密int MAX_ENCRYPT_BLOCK = 256;// 标识int offSet = 0;byte[] resultBytes = {};byte[] cache = {};while (inputLength - offSet > 0) {if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);offSet += MAX_ENCRYPT_BLOCK;} else {cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);offSet = inputLength;}resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);}return resultBytes;}

对长度过长的解密做一下处理就完美解决了。

更多推荐

data must not be longer than 256 bytes

本文发布于:2024-02-12 01:58:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1685104.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:longer   data   bytes

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!