Java 和 Vue AES 加密解密工具类实现
Java AES 加密解密工具类
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AESUtil {
private static final String ALGORITHM = 'AES';
private static final String TRANSFORMATION = 'AES/ECB/PKCS5Padding';
/**
* 加密
* @param key 密钥
* @param plainText 明文
* @return 密文
*/
public static String encrypt(String key, String plainText) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes('UTF-8'), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes('UTF-8'));
return Base64.encodeBase64String(encryptedBytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 解密
* @param key 密钥
* @param cipherText 密文
* @return 明文
*/
public static String decrypt(String key, String cipherText) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes('UTF-8'), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] cipherBytes = Base64.decodeBase64(cipherText);
byte[] decryptedBytes = cipher.doFinal(cipherBytes);
return new String(decryptedBytes, 'UTF-8');
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Vue AES 加密解密工具类
import CryptoJS from 'crypto-js';
const ALGORITHM = 'AES';
const TRANSFORMATION = 'AES/ECB/PKCS5Padding';
/**
* 加密
* @param {String} key 密钥
* @param {String} plainText 明文
* @return {String} 密文
*/
export function encrypt(key, plainText) {
const secretKey = CryptoJS.enc.Utf8.parse(key);
const encryptedBytes = CryptoJS.AES.encrypt(plainText, secretKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encryptedBytes.toString();
}
/**
* 解密
* @param {String} key 密钥
* @param {String} cipherText 密文
* @return {String} 明文
*/
export function decrypt(key, cipherText) {
const secretKey = CryptoJS.enc.Utf8.parse(key);
const decryptedBytes = CryptoJS.AES.decrypt(cipherText, secretKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return decryptedBytes.toString(CryptoJS.enc.Utf8);
}
使用说明:
- 确保您已在项目中安装了
crypto-js库。 - 将密钥 (key) 和明文 (plainText) 传递给
encrypt函数进行加密。 - 将密钥 (key) 和密文 (cipherText) 传递给
decrypt函数进行解密。
示例:
import { encrypt, decrypt } from './aes'; // 导入工具函数
const key = 'your_secret_key'; // 密钥
const plainText = 'hello world'; // 明文
// 加密
const cipherText = encrypt(key, plainText);
console.log('密文:', cipherText);
// 解密
const decryptedText = decrypt(key, cipherText);
console.log('明文:', decryptedText);
原文地址: https://www.cveoy.top/t/topic/mU4q 著作权归作者所有。请勿转载和采集!