工具类
import cn.hutool.core.util.HexUtil; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Arrays; @Slf4j public class AESTool { //秘钥设置16位 private static final String SECRET_KEY = "Snch9xeabPPurxE0"; //加密方式 private static final String AES_TYPE = "AES"; //秘钥最大长度16位 private static final int BYTE_LENGTH = 16; /** * 加密AES * * @param value 字符串 * @param key 秘钥 * @return String */ private static String encryptAES(String key, String value) { try { byte[] keyBytes = Arrays.copyOf(key.getBytes(StandardCharsets.US_ASCII), BYTE_LENGTH); SecretKey keyStr = new SecretKeySpec(keyBytes, AES_TYPE); Cipher cipher = Cipher.getInstance(AES_TYPE); cipher.init(Cipher.ENCRYPT_MODE, keyStr); byte[] cleartext = value.getBytes(StandardCharsets.UTF_8); byte[] ciphertextBytes = cipher.doFinal(cleartext); return new String(HexUtil.encodeHex(ciphertextBytes)).toUpperCase(); } catch (Exception ex) { ex.printStackTrace(); } return null; } public static String encrypt( String value) { return encryptAES(SECRET_KEY,value); } /** * 解密AES * * @param encrypted 字符串 * @param key 秘钥 * @return String */ public static String decryptAES(String key, String encrypted) { try { byte[] keyBytes = Arrays.copyOf(key.getBytes(StandardCharsets.US_ASCII), BYTE_LENGTH); SecretKey keyStr = new SecretKeySpec(keyBytes, AES_TYPE); Cipher cipher = Cipher.getInstance(AES_TYPE); cipher.init(Cipher.DECRYPT_MODE, keyStr); byte[] content = HexUtil.decodeHex(encrypted.toCharArray()); byte[] ciphertextBytes = cipher.doFinal(content); return new String(ciphertextBytes); } catch (Exception ex) { ex.printStackTrace(); } return null; } public static String decrypt(String encrypted) { return decryptAES(SECRET_KEY,encrypted); } /** * 加密 * * @param value 字符串 * @param pwd 秘钥 * @return String */ public static String encryptValue(String value, String pwd) { return StrUtil.isEmpty(value) ? null : encryptAES(pwd, value.trim()); } /** * 解密 * * @param value 字符串 * @param pwd 秘钥 * @return String */ public static String decryptValue(String value, String pwd) { if (StrUtil.isNotEmpty(value)) { String value2 = decryptAES(pwd, value.toLowerCase()); value = StrUtil.isEmpty(value2) ? value : value2; } return value; } public static void main(String[] args) { System.out.println(decrypt("58F2743E93CBFE5D73B3DA911858D1DC")); } }
测试
abv131313123