Java之RSA非对称加密解密
` 提示:RSA非对称加密
前言
`提示:基于hutool实现RSA非对称加密。
一、程序启动时将RSA对象注册到容器中
package org.tpsoft.RSA;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.RSA;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.base.entity.TpAuthClient;
import org.jeecg.modules.base.service.ITpAuthClientService;
import org.openxmlformats.schemas.drawingml.x2006.diagram.STAlgorithmType;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.tpsoft.common.CommonConstant;
import javax.annotation.Resource;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
/***
* @description RSA非对称加密配置类-将RSA对象注册到容器中
* @author macro
* @date 2023/4/18 13:14
*/
@Configuration
public class RSAConfig {
/**
* 授权信息接口
*/
@Resource
private ITpAuthClientService tpAuthClientService;
/**
* @return {@link RSA} RSA对象
* @description 唯一的秘钥对注册到容器中
* @author macro
* @date 2023/4/18 13:58
*/
@Bean(name = "rsa")
public RSA init() {
/*1.查询一体化平台授权信息*/
TpAuthClient clientItem = tpAuthClientService.getTpAuthClientByAppId(CommonConstant.YTH_AUTH_APP_ID);
if (null == clientItem) {
throw new JeecgBootException("未查询到应用授权信息!");
}
//2.判断授权信息有无秘钥对
if (StringUtils.isNotEmpty(clientItem.getPubilcKeyStr()) && StringUtils.isNotEmpty(clientItem.getPrivateKeyStr())) {
//2.1有,则返回rsa对象至容器
return new RSA(clientItem.getPrivateKeyStr(), clientItem.getPubilcKeyStr());
} else {
/*2.2没有,生成并返回*/
/*生成秘钥对*/
KeyPair pair = SecureUtil.generateKeyPair(CommonConstant.ALGORITHM_TYPE_RSA);
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();
// 将公钥对象转为字符串,并使用Base64编码
String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
// 将私钥对象转为字符串,并使用Base64编码
String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());
RSA rsa = new RSA(privateKeyStr, publicKeyStr);
/*秘钥对保存至数据库*/
clientItem.setPrivateKeyStr(privateKeyStr);
clientItem.setPubilcKeyStr(publicKeyStr);
tpAuthClientService.updateById(clientItem);
//返回到spring器
return rsa;
}
}
}
二、使用公钥加密
公钥可以提供给要加密的一方,进行加密。
三、使用私钥解密
public static void decryption(TreeMap<String,Object> map) {
try {
/*1.取出密文*/
String ciphertext = map.get(SIGN_KEY).toString();
if (null == ciphertext) {
throw new JeecgBootException("请按格式传递数据,没有参数[sign]!");
}
log.info("解密前的明文:" + ciphertext);
/*2.使用私钥解密成明文*/
byte[] decrypt = rsa.decrypt(ciphertext, KeyType.PrivateKey);
String plaintext = new String(decrypt, StandardCharsets.UTF_8);
log.info("解密后的明文:" + plaintext);
} catch (JeecgBootException e) {
log.error("签名错误:" + map.toString());
throw new JeecgBootException("签名错误");
}
}