package com.ruoyi.common.signature; import com.ruoyi.common.constant.Constants; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AESUtils { private static final String key="Bd26jqDDJcdnBocn"; private static final String iv ="oVKRQCjElggSbd8D"; /** * @Description AES算法加密明文 * @param data 明文 * @param key 密钥,长度16 * @param iv 偏移量,长度16 * @return 密文 */ public static String encrypt(String data){ try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); int blockSize = cipher.getBlockSize(); byte[] dataBytes = data.getBytes(Constants.UTF8); int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) { plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); // CBC模式,需要一个向量iv,可增加加密算法的强度 cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); // BASE64做转码。 String aseEncode = Base64.getEncoder().encodeToString(encrypted); return aseEncode.trim(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } /** * @Description AES算法解密密文 * @param data 密文 * @param key 密钥,长度16 * @param iv 偏移量,长度16 * @return 明文 */ public static String decrypt(String data){ try { byte[] encryptCode = Base64.getDecoder().decode(data);//先用base64解密 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encryptCode); String originalString = new String(original); return originalString.trim(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } public static void main(String[] args) throws Exception { String key="Bd26jqDDJcdnBocn"; String iv ="oVKRQCjElggSbd8D"; /* System.out.println("****************************************"); String encode = AESUtils.encrypt("测试", key, iv); System.out.println(encode); System.out.println("****************************************"); String decode = AESUtils.decrypt(encode, key, iv); System.out.println(decode); System.out.println("****************************************");*/ } }