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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
@Slf4j
public class RSAUtil {
/**
* BASE64 解码
*
* @param key 需要Base64解码的字符串
* @return 字节数组
*/
private static byte[] decryptBase64(String key) {
return Base64.decodeBase64(key);
}
/**
* BASE64 编码
*
* @param key 需要Base64编码的字节数组
* @return 字符串
*/
public static String encryptBase64(byte[] key) {
return new String(Base64.encodeBase64(key));
}
public static String encryptByPublicKey(String publicKey,String param){
RSA rsa = new RSA(null,publicKey);
byte[] encrypt = rsa.encrypt(param, KeyType.PublicKey);
return encryptBase64(encrypt);
}
public static String decryptByPrivate(String privateKey,String encryptParam){
log.info("开始解密");
byte[] bytes = RSAUtil.decryptBase64(encryptParam);
RSA rsa = new RSA(privateKey,null);
byte[] decrypt = rsa.decrypt(bytes, KeyType.PrivateKey);
String str = StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
log.info("结束解密");
return str;
}
}
RSA加解密
最新推荐文章于 2024-05-10 14:41:40 发布