请写出一个java的aes加密解密工具类并写出对应的vue的aes加密解密工具类
由于AES加密解密涉及到安全性,建议使用官方提供的Java Cryptography Extension (JCE)库进行操作。以下是一个基于JCE库实现的Java AES加密解密工具类:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
/**
* AES加密
* @param plainText 明文
* @param key 密钥
* @return 密文
* @throws Exception 异常
*/
public static String encrypt(String plainText, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
/**
* AES解密
* @param cipherText 密文
* @param key 密钥
* @return 明文
* @throws Exception 异常
*/
public static String decrypt(String cipherText, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
以下是一个基于JavaScript的Vue AES加密解密工具类:
import CryptoJS from 'crypto-js';
const key = CryptoJS.enc.Utf8.parse("1234567890123456"); // 密钥长度必须为16、24或32位
export default {
/**
* AES加密
* @param plainText 明文
* @returns 密文
*/
encrypt: function (plainText) {
const encrypted = CryptoJS.AES.encrypt(plainText, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
},
/**
* AES解密
* @param cipherText 密文
* @returns 明文
*/
decrypt: function (cipherText) {
const decrypted = CryptoJS.AES.decrypt(cipherText, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
}
原文地址: http://www.cveoy.top/t/topic/brMK 著作权归作者所有。请勿转载和采集!