package com.nokia.financeapi.utils; import cn.hutool.core.codec.Base64; import com.google.gson.Gson; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; /** * aes加密解密 */ public class AESUtil { static final String KEY = "2na$$PdV9AW8b#CS"; // 固定替换 private static final String ADD = "/add/"; // 加密 public static String encrypt(String str, String key) throws Exception { // 加密 if (str == null || key == null) { // 加密 return null; } // 加密 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // 加密 cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES")); // 加密 byte[] bytes = cipher.doFinal(str.getBytes("utf-8")); // 加密 String result = Base64.encode(bytes); // String result = new BASE64Encoder().encode(bytes); // 加密 result = result.replaceAll("\r\n", ""); // 加密 result = result.replaceAll("\\+", ADD); // 加密 return result; } // 解密 public static String decrypt(String str, String key) throws Exception { // 解密 if (str == null || key == null) { // 解密 return null; } // 解密 str = str.replaceAll("\\\\n", ""); // 解密 str = str.replaceAll(ADD, "+"); // 解密 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // 解密 cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES")); // 解密 byte[] bytes = Base64.decode(str); // byte[] bytes = new BASE64Decoder().decodeBuffer(str); // 解密 bytes = cipher.doFinal(bytes); // 解密 return new String(bytes); } public static String decrypt(String str) throws Exception { return decrypt(str, KEY); } public static void main(String[] args) throws Exception { // 参数 HashMap map = new HashMap<>(); // 财务系统id, 固定值 map.put("APP_ID", "FINANCE"); // 时间戳 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); map.put("TIME_STAMP", sdf.format(new Date())); // 当前登录账号 map.put("LOGIN_ID", "loginId"); //请求的地址 map.put("REQUEST_URL","https://ip:port/aaa"); // 加密串 String encrypt = AESUtil.encrypt(new Gson().toJson(map), "2na$$PdV9AW8b#CS"); // 返回 System.out.println(encrypt); //解密 System.out.println(AESUtil.decrypt(encrypt,"2na$$PdV9AW8b#CS")); System.out.println(AESUtil.decrypt("zoQtYlmhk/add/mBUBZD5mFJB1IXEwaLRS97Uf9z9Hlqdh8eF/add/c2gDUmD3pwGPfA8FQKBNTCB8LPlCPF/vHcU/2tL7Ps/add/6rn6w5rDS98R4GJueGgU01n12YZVS/FNx6pSI/add/BuEy1XyrSg8QBfx7igSozPxmdZ6a235/add/fqZPPSjoQReI","2na$$PdV9AW8b#CS")); } }