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;
}
对长度过长的解密做一下处理就完美解决了。