-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathaes.js
More file actions
49 lines (35 loc) · 1.33 KB
/
aes.js
File metadata and controls
49 lines (35 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const crypto = require('crypto');
class AES {
static encrypt(plainText, key) {
// 创建密钥
const keyBytes = Buffer.from(key, 'utf8');
// 创建加密器
const cipher = crypto.createCipher('aes-128-ecb', keyBytes);
// 加密
let encrypted = cipher.update(plainText, 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
}
static decrypt(encryptedText, key) {
// 创建密钥
const keyBytes = Buffer.from(key, 'utf8');
// 创建解密器
const decipher = crypto.createDecipher('aes-128-ecb', keyBytes);
// 解密
let decrypted = decipher.update(encryptedText, 'base64', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
static main() {
const plainText = "Hello, World!";
const key = "1234567890123456"; // 16字节密钥
console.log("原文:", plainText);
const encrypted = AES.encrypt(plainText, key);
console.log("加密后:", encrypted);
const decrypted = AES.decrypt(encrypted, key);
console.log("解密后:", decrypted);
console.log("验证:", plainText === decrypted);
}
}
// 示例使用
AES.main();