0
点赞
收藏
分享

微信扫一扫

如何使用hutool进行AES加密和解密?

如何使用hutool进行AES加密和解密?

下面直接贴出工具类,有需要的小伙伴可以直接拿去用。

import cn.hutool.crypto.asymmetric.AsymmetricCrypto;
import cn.hutool.crypto.asymmetric.KeyType;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
* @Author: 夏威夷8080
* @Date: 2011/3/22 15:36
*/
@Slf4j
public class SystemRSAUtil {

private final static String DEFAULT_ALGORITHM = "RSA";
private final static String ALGORITHM = "RSA/ECB/PKCS1Padding";

/**
* @desc: 将字符串转换成RSAPublicKey类型
* @param
* @return
*/
public static RSAPublicKey getRSAPublicKeyByBase64(String base64s) throws Exception {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec((new BASE64Decoder()).decodeBuffer(base64s));
RSAPublicKey publicKey = null;
KeyFactory keyFactory = KeyFactory.getInstance(DEFAULT_ALGORITHM);
try {
publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
} catch (InvalidKeySpecException var4) {

}
return publicKey;
}

/**
* @desc: 将字符串转换成RSAPrivateKey类型
* @param
* @return
*/
public static RSAPrivateKey getRSAPrivateKeyByBase64(String base64s) throws Exception{
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec((new BASE64Decoder()).decodeBuffer(base64s));
RSAPrivateKey privateKey = null;
KeyFactory keyFactory = KeyFactory.getInstance(DEFAULT_ALGORITHM);
try {
privateKey = (RSAPrivateKey)keyFactory.generatePrivate(keySpec);
} catch (InvalidKeySpecException var4) {
}
return privateKey;
}

/**
* 加密
* @param data
* @return
*/
public static String encryptBase64(String data, String publicKey){
AsymmetricCrypto asymmetricCrypto = null;
try {
asymmetricCrypto = new AsymmetricCrypto(DEFAULT_ALGORITHM, null,
getRSAPublicKeyByBase64(publicKey));
} catch (Exception e) {
log.error("构建asymmetricCrypto出错:{}", Throwables.getStackTraceAsString(e));
}
return asymmetricCrypto.encryptBase64(data, KeyType.PublicKey);
}

/**
* 解密
* @param data
* @return
*/
public static String decryptStr(String data, String privateKey){
AsymmetricCrypto asymmetricCrypto = null;
try {
asymmetricCrypto = new AsymmetricCrypto(DEFAULT_ALGORITHM, getRSAPrivateKeyByBase64(privateKey),
null);
} catch (Exception e) {
log.error("构建asymmetricCrypto出错:{}", Throwables.getStackTraceAsString(e));
}
return asymmetricCrypto.decryptStr(data, KeyType.PrivateKey);
}


public static void main(String[] args) {
// 公钥
String publicKey = "用工具生成";
// 私钥
String privateKey = "用工具生成";
// 公钥和私钥可以通过在线工具生成,记住一个原则,公钥加密,私钥解密
String a = encryptBase64("55555555555", publicKey);
System.out.println("加密后的数据:");
System.out.println(a);
String b = decryptStr(a, privateKey);
System.out.println("解密后的数据:");
System.out.println(b);

}
}

如何使用hutool进行AES加密和解密?希望本文对你有帮助。



举报

相关推荐

0 条评论