@yoooloo42/beat 1.0.18 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yoooloo42/beat",
3
- "version": "1.0.18",
3
+ "version": "1.0.20",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -0,0 +1,135 @@
1
+ import crypto from 'crypto';
2
+
3
+ // --- 安全常量定义 ---
4
+ const ALGORITHM = 'aes-128-cbc'; // 算法:AES-128-CBC
5
+ const IV_LENGTH = 16; // IV 长度:16 字节 (128 位)
6
+ const KEY_LENGTH = 16; // 密钥长度:16 字节 (128 位)
7
+ const PLAINTEXT_ENCODING = 'utf8'; // 明文输入编码
8
+ const CIPHER_OUTPUT_FORMAT = 'base64';// 密文输出格式 (Base64)
9
+ const KEY_IV_FORMAT = 'base64'; // 密钥和 IV 的传输/存储格式 (Base64)
10
+
11
+ /**
12
+ * 🔑 生成安全随机的 AES 密钥和 IV。
13
+ * @returns {Object} 包含 Base64 格式密钥和 IV 的对象
14
+ */
15
+ function generateKeyAndIV() {
16
+ // 使用 KEY_IV_FORMAT (Base64) 输出,以便于存储和传输
17
+ const key = crypto.randomBytes(KEY_LENGTH).toString(KEY_IV_FORMAT);
18
+ const iv = crypto.randomBytes(IV_LENGTH).toString(KEY_IV_FORMAT);
19
+
20
+ return {
21
+ key: key, // Base64 格式的 16 字节密钥(长度为 24 的字符串)
22
+ iv: iv // Base64 格式的 16 字节 IV(长度为 24 的字符串)
23
+ };
24
+ }
25
+
26
+ /**
27
+ * 检查密钥和初始化向量的长度是否符合 AES-128-CBC 规范。
28
+ * 注意:这里的 Buffer 长度必须是 KEY_LENGTH/IV_LENGTH (16 字节)
29
+ * @param {Buffer} keyBuffer 密钥 Buffer
30
+ * @param {Buffer} ivBuffer 初始化向量 Buffer
31
+ */
32
+ function checkKeyAndIV(keyBuffer, ivBuffer) {
33
+ if (keyBuffer.length !== KEY_LENGTH) {
34
+ throw new Error(`Invalid Key Length. Key must be ${KEY_LENGTH} bytes for ${ALGORITHM}. Current buffer size: ${keyBuffer.length}`);
35
+ }
36
+ if (ivBuffer.length !== IV_LENGTH) {
37
+ throw new Error(`Invalid IV Length. IV must be ${IV_LENGTH} bytes for ${ALGORITHM}. Current buffer size: ${ivBuffer.length}`);
38
+ }
39
+ }
40
+
41
+ /**
42
+ * 🔐 AES-128-CBC 加密
43
+ * @param {Object} params
44
+ * @param {string} params.text - 明文
45
+ * @param {string} params.key - Base64 格式的密钥字符串
46
+ * @param {string} params.iv - Base64 格式的初始化向量字符串
47
+ * @returns {string} Base64 格式的密文
48
+ */
49
+ function aesEncrypt({ text, key, iv }) {
50
+ try {
51
+ // 关键修复:使用 KEY_IV_FORMAT (Base64) 来解析输入的 Key 和 IV 字符串
52
+ const keyBuffer = Buffer.from(key, KEY_IV_FORMAT);
53
+ const ivBuffer = Buffer.from(iv, KEY_IV_FORMAT);
54
+
55
+ checkKeyAndIV(keyBuffer, ivBuffer);
56
+
57
+ const cipher = crypto.createCipheriv(ALGORITHM, keyBuffer, ivBuffer);
58
+
59
+ // 加密主体:输入是明文 (PLAINTEXT_ENCODING),输出为 Hex
60
+ let encrypted = cipher.update(text, PLAINTEXT_ENCODING, 'hex');
61
+
62
+ // 完成加密,并应用最终补位
63
+ encrypted += cipher.final('hex');
64
+
65
+ // 将 Hex 转换为 Base64 输出
66
+ return Buffer.from(encrypted, 'hex').toString(CIPHER_OUTPUT_FORMAT);
67
+
68
+ } catch (error) {
69
+ console.error("AES Encryption Error:", error.message);
70
+ throw new Error("Encryption failed.");
71
+ }
72
+ }
73
+
74
+ /**
75
+ * 🔓 AES-128-CBC 解密
76
+ * @param {Object} params
77
+ * @param {string} params.text - Base64 格式的密文
78
+ * @param {string} params.key - Base64 格式的密钥字符串
79
+ * @param {string} params.iv - Base64 格式的初始化向量字符串
80
+ * @returns {string} 明文
81
+ */
82
+ function aesDecrypt({ text, key, iv }) {
83
+ try {
84
+ // 关键修复:使用 KEY_IV_FORMAT (Base64) 来解析输入的 Key 和 IV 字符串
85
+ const keyBuffer = Buffer.from(key, KEY_IV_FORMAT);
86
+ const ivBuffer = Buffer.from(iv, KEY_IV_FORMAT);
87
+
88
+ checkKeyAndIV(keyBuffer, ivBuffer);
89
+
90
+ // 1. 将 Base64 密文转为 Buffer
91
+ const encryptedBuffer = Buffer.from(text, CIPHER_OUTPUT_FORMAT);
92
+
93
+ // 2. 创建解密器
94
+ const decipher = crypto.createDecipheriv(ALGORITHM, keyBuffer, ivBuffer);
95
+
96
+ // 3. 解密主体:输入是 Buffer,输出为明文编码
97
+ let decrypted = decipher.update(encryptedBuffer, 'buffer', PLAINTEXT_ENCODING);
98
+
99
+ // 4. 完成解密,并移除补位
100
+ decrypted += decipher.final(PLAINTEXT_ENCODING);
101
+
102
+ return decrypted;
103
+ } catch (error) {
104
+ // 在解密失败(如密文被篡改)时,decipher.final() 会抛出错误
105
+ console.error("AES Decryption Error:", error.message);
106
+ throw new Error("Decryption failed. Ciphertext may be invalid or tampered with.");
107
+ }
108
+ }
109
+
110
+ // --- 测试和导出 ---
111
+
112
+ // 测试代码部分(请在文件外部执行时使用,或在 Node.js 环境中移除 export default 后测试)
113
+ /*
114
+ const { key, iv } = generateKeyAndIV()
115
+ console.log("Key:", key);
116
+ console.log(key.length); // 应该是 Base64 字符串长度 24
117
+ console.log("IV:", iv);
118
+ console.log(iv.length); // 应该是 Base64 字符串长度 24
119
+ const text = 'Hello Gemini'
120
+ try {
121
+ const ciphertext = aesEncrypt({text: text, key, iv})
122
+ console.log('加密测试:', ciphertext)
123
+ const decryptedText = aesDecrypt({text: ciphertext, key, iv})
124
+ console.log('解密测试:', decryptedText)
125
+ } catch (e) {
126
+ console.error('测试失败:', e.message)
127
+ }
128
+ */
129
+
130
+ export default {
131
+ generateKeyAndIV,
132
+ checkKeyAndIV,
133
+ aesEncrypt,
134
+ aesDecrypt
135
+ };
@@ -0,0 +1,140 @@
1
+ import crypto from 'crypto';
2
+
3
+ // --- 常量定义 ---
4
+ const ALGORITHM = 'RSA-SHA256';
5
+ const INPUT_ENCODING = 'utf8';
6
+ const SIGNATURE_FORMAT = 'base64';
7
+
8
+ /**
9
+ * 🔑 生成 RSA 密钥对 (公钥和私钥)。
10
+ *
11
+ * @returns {Object} 包含公钥和私钥的对象 (PEM 格式)
12
+ */
13
+ function generateRSAKeyPair() {
14
+ // 使用 generateKeyPairSync 同步生成 RSA 密钥对
15
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
16
+ modulusLength: 2048, // 密钥长度,2048 位是目前推荐的最小安全长度
17
+ publicKeyEncoding: {
18
+ type: 'spki', // SubjectPublicKeyInfo 格式
19
+ format: 'pem' // PEM 格式
20
+ },
21
+ privateKeyEncoding: {
22
+ type: 'pkcs8', // PKCS#8 格式
23
+ format: 'pem' // PEM 格式
24
+ // 生产环境建议添加 cipher: 'aes-256-cbc' 和 passphrase 来加密私钥
25
+ }
26
+ });
27
+
28
+ return { publicKey, privateKey };
29
+ }
30
+
31
+ /**
32
+ * 🔐 RSA 签名
33
+ * 使用 'RSA-SHA256' 算法,将输入文本进行签名。
34
+ *
35
+ * @param {Object} params
36
+ * @param {string} params.text - 要签名的明文数据。
37
+ * @param {string} params.privateKey - PEM 格式的私钥。
38
+ * @returns {string} Base64 格式的签名结果。
39
+ * @throws {Error} 如果签名失败(如密钥无效或参数缺失)。
40
+ */
41
+ function rsaSign({ text, privateKey }) {
42
+ if (!text || !privateKey) {
43
+ throw new Error("Missing required parameters for signing: text or privateKey.");
44
+ }
45
+
46
+ try {
47
+ const signer = crypto.createSign(ALGORITHM);
48
+ signer.update(text, INPUT_ENCODING);
49
+
50
+ // 签名
51
+ const signature = signer.sign(privateKey, SIGNATURE_FORMAT);
52
+
53
+ return signature;
54
+
55
+ } catch (error) {
56
+ console.error(`RSA Signing Error (${ALGORITHM}):`, error.message);
57
+ throw new Error("RSA signing failed. Check private key format and validity.");
58
+ }
59
+ }
60
+
61
+ /**
62
+ * 🔓 RSA 验证签名
63
+ * 使用 'RSA-SHA256' 算法验证签名是否有效。
64
+ *
65
+ * @param {Object} params
66
+ * @param {string} params.text - 用于签名的原始明文数据。
67
+ * @param {string} params.signature - Base64 格式的签名结果。
68
+ * @param {string} params.publicKey - PEM 格式的公钥。
69
+ * @returns {boolean} 签名是否有效。
70
+ * @throws {Error} 如果验证过程发生致命错误。
71
+ */
72
+ function rsaVerify({ text, signature, publicKey }) {
73
+ if (!text || !signature || !publicKey) {
74
+ console.warn("Missing required parameters for verification.");
75
+ return false;
76
+ }
77
+
78
+ try {
79
+ const verifier = crypto.createVerify(ALGORITHM);
80
+ verifier.update(text, INPUT_ENCODING);
81
+
82
+ // 验证签名
83
+ return verifier.verify(
84
+ publicKey,
85
+ signature,
86
+ SIGNATURE_FORMAT // 指定签名的输入格式
87
+ );
88
+
89
+ } catch (error) {
90
+ console.error(`RSA Verification Error (${ALGORITHM}):`, error.message);
91
+ throw new Error("RSA verification failed due to internal error. Check public key format and validity.");
92
+ }
93
+ }
94
+
95
+ /* --- 测试代码 ---
96
+ try {
97
+ const dataToSign = "这是一段需要使用数字签名的重要数据。";
98
+
99
+ // 1. 生成密钥对
100
+ console.log("--- 1. 生成 RSA 密钥对 ---");
101
+ const { publicKey, privateKey } = generateRSAKeyPair();
102
+ // console.log("私钥 (PEM):", privateKey);
103
+ // console.log("公钥 (PEM):", publicKey);
104
+
105
+ // 2. 使用私钥签名
106
+ console.log("\n--- 2. 进行签名 ---");
107
+ const signature = rsaSign({ text: dataToSign, privateKey: privateKey });
108
+ console.log("原始数据:", dataToSign);
109
+ console.log("签名结果 (Base64):", signature);
110
+
111
+ // 3. 使用公钥验证
112
+ console.log("\n--- 3. 验证签名 ---");
113
+ const isValid = rsaVerify({
114
+ text: dataToSign,
115
+ signature: signature,
116
+ publicKey: publicKey
117
+ });
118
+ console.log("验证结果 (正确签名):", isValid ? "✅ 验证通过" : "❌ 验证失败");
119
+
120
+ // 4. 验证失败场景 (数据篡改)
121
+ console.log("\n--- 4. 验证失败测试 (数据篡改) ---");
122
+ const tamperedData = "这是一段被篡改后的数据!";
123
+ const isInvalid = rsaVerify({
124
+ text: tamperedData, // 使用篡改后的数据
125
+ signature: signature,
126
+ publicKey: publicKey
127
+ });
128
+ console.log("验证结果 (篡改数据):", isInvalid ? "❌ 验证通过 (错误)" : "✅ 验证失败 (正确)");
129
+
130
+ } catch (error) {
131
+ console.error("\n--- RSA 测试发生错误 ---");
132
+ console.error(error.message);
133
+ }
134
+ */
135
+
136
+ export default {
137
+ generateRSAKeyPair,
138
+ rsaSign,
139
+ rsaVerify
140
+ }