还记得上次面试时面试官问我相关的问题,当时回答的一团糟。正好最近新找了一家公司,前后端传输是经过加密的,具体操作很简单,前端传输过来的数据使用了AES加一串字符串进行加密,后端公司自己写了request和response,然后在过滤器中进行解密。
大概代码如下:
package com.poplar.utils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.util.DigestUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
/**
* by poplar created on 2020/1/26
*/
public class AesHelper {
private static final String KEY = DigestUtils.md5DigestAsHex("HGDD657525KKJGHFGCDFSFGRTYUYERXDAWEGFGFYT".getBytes(StandardCharsets.UTF_8));
private static final String ARITHMETIC = "AES/ECB/PKCS5Padding";
public static String encrypt(String content,String key) {
try {
//1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator kgen = KeyGenerator.getInstance("AES");
//2.根据ecnodeRules规则初始化密钥生成器
//生成一个128位的随机源,根据传入的字节数组
kgen.init(128);
Cipher cipher = Cipher.getInstance(ARITHMETIC);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
byte[]