rsa加密
项目中用到了rsa加密,
对接时发现最大加密字节数117,超出最大字节数需要分组加密
1.正常加密
package com.plan.License;
import com.alibaba.fastjson.JSON;
import java.text.SimpleDateFormat;
import java.util.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson.JSONObject;
/**
* 非分组加密
* 使用hutool工具类中的rsa工具*/
public class RSAUsing {
private static final String PRIVATE_KEY="aaa";
private static final String PUBLIC_KEY="bbb";
/**
* 获取公钥私钥密钥对
* */
public static String getKeyPair(RSA rsa){
StringBuilder rtnStb=new StringBuilder();
//获得私钥
//System.out.println(rsa.getPrivateKey());
rtnStb.append("privateKey: ");
rtnStb.append(rsa.getPrivateKeyBase64());
rtnStb.append("\n");
//获得公钥
//System.out.println(rsa.getPublicKey());
rtnStb.append("publicKey: ");
rtnStb.append(rsa.getPublicKeyBase64());
return rtnStb.toString();
}
//加密
public static String getEncryptString(String str, RSA rsa){
byte[] encrypt = rsa.encrypt(StrUtil.bytes(str, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
return Base64.getEncoder().encodeToString(encrypt);
}
//解密
public static String getDecryptString(String str, RSA rsa){
byte[] aByte = Base64.getDecoder().decode(str);
byte[] decrypt = rsa.decrypt(aByte, KeyType.PrivateKey);
return new String(decrypt, CharsetUtil.CHARSET_UTF_8);
}
/**
* 封装生成license
* @param license
* @return
*/
public static String generateLicense123(LicenseVo license) {
//1.Java对象->Json字符串
String licenseString = JSONObject.toJSONString(license);
System.out.println("licenseString"+licenseString);
//将生成的license加密
RSA rsa = new RSA();
String encryptTxt=RSAUsing.getEncryptString(JSON.toJSONString(licenseString), rsa);
System.out.println("密文"+encryptTxt);
String decryptTxt=RSAUsing.getDecryptString(encryptTxt, rsa);
System.out.println("解密"+decryptTxt);
return encryptTxt;
}
public static void main(String[] args) {
String priKey="aaa";
String pubKey="bbb";
RSA rsa = new RSA(priKey, pubKey);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String plainTxt="123456789";
String encryptTxt=getEncryptString(JSON.toJSONString(plainTxt), rsa);
System.out.println("加密密文:"+encryptTxt);
String decryptTxt=getDecryptString(encryptTxt, rsa);
System.out.println("解密后:"+decryptTxt);
}
}
2.分组加密
package com.plan.License;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.plan.business.domain.vo.PResourceVo;
import com.plan.business.domain.vo.PSoftwareVo;
import net.sf.json.JSONArray;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
/**
* 分组加密
*/
public class RSAUtils2 {
private static final String PRIVATE_KEY="aaa";
private static final String PUBLIC_KEY="bbb";
/**
* RSA公钥加密
*
* @param str
* 加密字符串
* @param publicKey
* 公钥
* @return 密文
* @throws Exception
* 加密过程中的异常信息
*/
public static String encrypt( String str, String publicKey ) throws Exception{
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
// String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
String outStr = null;
byte[] inputArray = str.getBytes("UTF-8");
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);
}
outStr = Base64.encodeBase64String(resultBytes);
return outStr;
}
/**
* 封装生成license
* @param license
* @return
*/
public static String generateLicense(LicenseVo license) throws Exception {
//1.Java对象->Json字符串
String licenseString = JSONObject.toJSONString(license);
System.out.println("licenseString"+licenseString);
//将生成的license加密
String encryptTxt=RSAUtils2.encrypt(JSON.toJSONString(licenseString),PUBLIC_KEY);
System.out.println("密文"+encryptTxt);
return encryptTxt;
}
/**
* 封装生成已下载的json
* @param
* @return
*/
public static String generateDownload(List<PResourceVo> resourceVoList,List<PSoftwareVo> softwareVoList) throws Exception {
//1.Java集合->Json字符串
JSONArray jsonArray =null;
String encryptTxt="";
if(resourceVoList!=null&&resourceVoList.size()>0){
jsonArray = JSONArray.fromObject(resourceVoList);
}else{
jsonArray = JSONArray.fromObject(softwareVoList);
}
encryptTxt=encryptTxt.concat(RSAUtils2.encrypt(jsonArray.toString(),PUBLIC_KEY));
System.out.println("downloadString"+jsonArray);
System.out.println("密文"+encryptTxt);
return encryptTxt;
}
public static void main(String[] args) throws Exception {
String priKey="aaa";
String pubKey="bbb";
// RSA rsa = new RSA(priKey, pubKey);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String plainTxt="{\"code\":\"123456789\",\"customerId\":1,\"customerName\":\"客户名称\",\"endTime\":\"2022-10-1\",\"license\":\"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4oZSlP9KlXr8vMN/Yvu/7Rvnu\",\"remarks\":\"备注\",\"startTime\":\"2021-10-1\"}";
int i = plainTxt.length();
byte[] buff = plainTxt.getBytes();
System.out.println("明文长度:"+buff.length);
String encryptTxt=encrypt(plainTxt, pubKey);
System.out.println("加密密文:"+encryptTxt);
}
}