解决Java RSA加密报错:Data must not be longer than 117 bytes

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;
}

 

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值