目录
使用依赖:
<!--http包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
<version>5.7.22</version>
</dependency>
<!--加密包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
<version>5.8.4</version>
</dependency>
一、AES加密解密工具类
场景:
对一个字段进行简单的加密解密时使用,工具类如下
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.shuyun.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
/**
* @author hanyang
* @date 2022-07-13
*/
@Slf4j
@Component
public class AESUtils {
private static AES aes;
private static String aesKey;
@Value("${aes.key}")
public void setAesKey(String aesKey) {
AESUtils.aesKey = aesKey;
}
public static String getAesKey() {
return aesKey;
}
/**
* 使用aes加密内容
*
* @param content 内容
* @return 密文
*/
public static String encryptAes(String content) {
String aesKey = getAesKey();
byte[] keyByte = Base64.decode(aesKey);
// 构建
aes = SecureUtil.aes(keyByte);
return aes.encryptHex(content);
}
/**
* 使用aes解密密文
*
* @param content 内容
* @return 明文
*/
public static String decryptAes(String content) {
String aesKey = getAesKey();
byte[] keyByte = Base64.decode(aesKey);
// 构建
aes = SecureUtil.aes(keyByte);
return aes.decryptStr(content, CharsetUtil.CHARSET_UTF_8);
}
}
AES属于对称加密,加密解密使用同一个密钥,因此不能每次都生成一个密钥,而是将固定密钥配置在配置文件或使用其他存储方法,生成密钥代码如下。
/**
* hutool随机生成一个密钥
*/
@Test
public void test1() {
// 随机生成密钥
byte[] key =
SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
// Base64编码
String encode = Base64.encode(key);
System.out.println("key-> " + encode);
}
运行结果下入:
二、构造http请求工具
场景:
在某些业务控制器中,我们需要向第三方接口发送调用请求,以获得一些业务需要的信息,比方获取第三方用户信息,需要调用第三方用户的接口。这时就要在控制器中构造http请求。
String validRes = HttpUtil.createPost(tokenUrl)
//添加请求头
.addHeaders(personHeaderToken)
//添加表单参数
.form(validResMap)
//设置contentType
.contentType("application/x-www-form-urlencoded")
//执行请求并返回响应体
.execute().body();
以Post请求为例,可以在构造请求的时候设置一些请求头信息,表单、请求体等多种参数构造方式,注意参数基本都是Map类型
对于获取的结果,可以采用FastJson等json处理工具类进行转换,转换成map后取值。