RSA解密时报错 Data must not be longer than 128 bytes
最近RSA解密是遇到一个问题,就是报错 Data must not be longer than 128 bytes。
笔者是java代码,报错是在 cipher.doFinal(data) 这句产生的。
研究多个文档后发现最终解决办法,因为公钥私钥不是我生成的,所以无法更换,只能分块解密。
在网上看到如果时无填充,就用私钥的byte长度 / 8, 如果是有填充加密,则再 -11。这些方法我试了。都没有用。最后发现一个有用的,就是直接用128来分块。这个应该是跟加密方如何加密的有关系。
直接上代码
private final static int MAX_DECRYPT_BLOCK = 128;
private static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// 返回UTF-8编码的解密信息
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
String s = new String(decryptedData, "UTF-8");
System.out.println(s);
return null;
}
再放一段同类型加密
private static final int MAX_ENCRYPT_BLOCK = 127;
public static String encrypt(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.getBytes().length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int i = 0;
int offset = 0;
byte[] cache;
// 对数据分段加密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
return new String(Base64.encodeBase64String(encryptedData));
}
如果有用希望大家能点个赞!也欢迎评论区一起交流。