AES 加解密(包含JS、VUE、JAVA、MySQL)工具方法
以下是一个简化的AES加解密工具方法示例,包括JavaScript、Vue.js、Java和MySQL的实现。
JavaScript (使用CryptoJS库):
// 引入CryptoJS库
const CryptoJS = require("crypto-js");
function encryptAES(data, secretKey) {
return CryptoJS.AES.encrypt(JSON.stringify(data), secretKey).toString();
}
function decryptAES(ciphertext, secretKey) {
const bytes = CryptoJS.AES.decrypt(ciphertext, secretKey);
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
}
// 使用示例
const secretKey = "your-secret-key";
const data = { message: "Hello, World!" };
const encrypted = encryptAES(data, secretKey);
const decrypted = decryptAES(encrypted, secretKey);
Vue.js (使用axios和CryptoJS库):
// Vue方法部分
methods: {
encryptData(data, secretKey) {
return CryptoJS.AES.encrypt(JSON.stringify(data), secretKey).toString();
},
decryptData(ciphertext, secretKey) {
const bytes = CryptoJS.AES.decrypt(ciphertext, secretKey);
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
},
async sendData() {
const secretKey = "your-secret-key";
const data = { message: "Hello, World!" };
const encryptedData = this.encryptData(data, secretKey);
try {
const response = await axios.post('/api/data', { encryptedData });
// 处理响应
} catch (error) {
// 处理错误
}
}
}
Java (使用AES库,需要添加依赖):
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtil {
public static String encryptAES(String data, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES"));
byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decryptAES(String ciphertext, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES"));
评论已关闭