RSA加密算法是一种非对称加密算法,公钥加密私钥解密。RSA是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA就是他们三人姓氏开头字母拼在一起组成的。(百度百科) 问题场景: Cipher提供加解密API,其中RSA非对称加密解密内容长度是有限制的,加密长度不超过117Byte,解密长度不超过128Byte,报错如下:javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes。 解决方案: 对加密、解密内容分段处理,然后再累加 加密示例:
public static String rsaEncrypt(String input, String rsaPublicKey) {
String result = "";
try {
// 将Base64编码后的公钥转换成PublicKey对象
byte[] buffer = Base64.decode(rsaPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
// 加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);ubli
byte[] inputArray = input.getBytes();
int inputLength = inputArray.length;
System.out.println("加密字节数:" + inputLength);
// 最大加密字节数,超出最大字节数需要分组加密
int MAX_ENCRYPT_BLOCK = 117;
// 标识
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);
}
result = Base64.encodeToString(resultBytes);
} catch (Exception e) {
System.out.println("rsaEncrypt error:" + e.getMessage());
}
System.out.println("加密的结果:" + result);
return result;
}