1.注意点 要保持 前后端偏移量、密钥key 一致
2.解密数据需要确保是base64 编码数据
3.前端解密时需要针对空格和换行需要进行处理
代码 Java
package com.longji.mob.util; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; public class AESEUtil { // 偏移量 private final static String IV = "1234567890123456";//需要前端与后端配置一致 // key private final static String KEY = "1234567890123456"; /** * 加密算法,使用默认的IV、KEY * @param content 加密的明文 * @return 加密后的字符串 */ public static String encrypt(String content){ return encrypt(content,KEY,IV); } /** * 解密算法,使用默认的IV、KEY * @param content 解密的密文 * @return 解密后的字符串 */ public static String decrypt(String content){ return decrypt(content,KEY,IV); } /** * 加密方法 * @param content 加密的明文 * @param key key * @param iv 偏移量 * @return 加密后的字符串 */ public static String encrypt(String content, String key, String iv){ try{ // "算法/模式/补码方式"NoPadding PkcsPadding Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); int blockSize = cipher.getBlockSize(); byte[] dataBytes = content.getBytes(); 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(StandardCharsets.UTF_8), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return new Base64().encodeToString(encrypted); }catch (Exception e) { throw new RuntimeException("加密算法异常 CryptoUtil encrypt()加密方法,异常信息:" + e.getMessage()); } } /** * 解密方法 * @param content 解密的密文 * @param key key * @param iv 偏移量 * @return 解密后的字符串 */ public static String decrypt(String content, String key, String iv){ try { byte[] encrypted1 = new Base64().decode(content); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); byte[] original = cipher.doFinal(encrypted1); return new String(original).trim(); } catch (Exception e) { throw new RuntimeException("加密算法异常 CryptoUtil decrypt()解密方法,异常信息:" + e.getMessage()); } } }
vue 前端代码
//解密方法
// 解密算法
function decryptKey(word) {
let idKey = word.replaceAll(/\s/g, '+')
const SECRET_KEY = CryptoJS.enc.Latin1.parse('1234567890123456');
const SECRET_IV = CryptoJS.enc.Latin1.parse('1234567890123456');
const base64 = CryptoJS.enc.Base64.parse(idKey)
const srcs = CryptoJS.enc.Base64.stringify(base64)
const decrypt = CryptoJS.AES.decrypt(srcs, SECRET_KEY, {
iv: SECRET_IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
})
return decrypt.toString(CryptoJS.enc.Utf8)
}