package com.ltkj.web.controller.api.utils; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class CryptoUtil { private static final String KEY = "f$9Lz#Q@1vT!eW2%"; // AES密钥(16位) private static final String ALGORITHM = "AES"; // 加密 public static String encrypt(String plainText) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] encrypted = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encrypted); } // 解密 public static String decrypt(String cipherText) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, keySpec); byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText)); return new String(decrypted); } public static void main(String[] args) throws Exception { String encrypt = encrypt("{\"card\": \"622722197210102079\",\"name\":\"焦拉民\"}"); System.out.println("encrypt = " + encrypt); String decrypt = decrypt(encrypt); System.out.println("decrypt = " + decrypt); } }