@yoooloo42/beat 1.0.29 → 1.0.30

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.
@@ -1,69 +0,0 @@
1
- // v3签名:所有的v3请求都由这里向微信支付接口的后台发出
2
-
3
- import req from 'request'
4
- import random from '@yoooloo42/bean/unclassified/random'
5
- import RSA from '../crypto/RSA.js'
6
- const para_global = {
7
- nonce_str32: random.random(32, '0123456789abcdefghijklmnopqrstuvwxyz') // 32位的随机字符串
8
- }
9
-
10
- function v3sign(para){
11
- // para.host 接口域名
12
- // para.url 接口地址
13
- // para.method 请求方式
14
- // para.body 签名内容
15
- // para.mchid 商户号
16
- // para.serial_no 证书序列号
17
- // para.private_key 证书私钥
18
- // para.nonce_str 32位的随机字符串
19
- let method = para.method ? para.method : "POST"
20
-
21
- return new Promise(function (resolve, reject) {
22
- let nonce_str = para.nonce_str ? para.nonce_str : para_global.nonce_str32,
23
- timestamp_seconds = Math.floor(new Date().getTime() / 1000) // 秒级的时间戳
24
-
25
- let strBody = para.body ? JSON.stringify(para.body) : ""
26
-
27
- // '\n' === String.fromCharCode(0x0A)
28
- let text = method + String.fromCharCode(0x0A) +
29
- para.url + '\n' +
30
- timestamp_seconds + '\n' +
31
- nonce_str + '\n' +
32
- strBody + '\n'
33
-
34
- // RSA-SHA256签名
35
- let signature = RSA.rsaSign({text, privateKey: para.private_key})
36
- req({
37
- url: para.host + para.url,
38
- headers: {
39
- 'Accept': 'application/json',
40
- 'Content-Type': 'application/json',
41
- 'User-Agent': 'Chrome/17.0.963.56',
42
- 'Authorization': 'WECHATPAY2-SHA256-RSA2048' + ' ' +
43
- 'serial_no="' + para.serial_no + '",' +
44
- 'mchid="' + para.mchid + '",' +
45
- 'nonce_str="' + nonce_str + '",' +
46
- 'timestamp="' + timestamp_seconds + '",' +
47
- 'signature="' + signature + '"'
48
- },
49
- method,
50
- body: strBody
51
- }, function (err, res, body) {
52
- if(!body){
53
- return resolve({code: 1, message: "v3签名失败"})
54
- }
55
-
56
- let objV3Result = JSON.parse(body)
57
- resolve({code: 0, message: "v3签名完成",
58
- objV3Result
59
- })
60
- })
61
- })
62
- }
63
-
64
- export {
65
- v3sign
66
- }
67
- export default {
68
- v3sign
69
- }
@@ -1,174 +0,0 @@
1
- // 驿町管家智能门锁
2
- // http://www.yizoo.net/
3
-
4
- import Request from 'request'
5
-
6
- // 获取令牌
7
- function openSmartLogin(para){
8
- // para.url 接口请求地址
9
- // para.accountName 登录账号
10
- // para.password 密码
11
-
12
- return new Promise((resolve, reject) => {
13
- Request({
14
- url: para.url,
15
- method: 'POST',
16
- json: true,
17
- headers: {
18
- 'Content-Type': 'text/json;charset=utf-8',
19
- 'Content-Version': '1.0' // 接口版本,不填则默认获取1.0版本
20
- },
21
- body: {
22
- method: 'openSmartLogin', // 接口方法
23
- data: {
24
- accountName: para.accountName,
25
- password: para.password
26
- }
27
- }
28
- }, function (error, response, body) {
29
- if (error) throw error
30
-
31
- let msgId = body.msgId,
32
- resultCode = body.resultCode,
33
- reason = body.reason,
34
- method = body.method,
35
- data = body.data
36
-
37
- if (resultCode !== 0) {
38
- return resolve({code: 1, message: '获取 tokenid 失败:' + reason})
39
- }
40
-
41
- resolve({code: 0, message: '获取 tokenid 成功',
42
- data: {
43
- tokenId: data.tokenId, // 令牌
44
- expireTime: data.expireTime // 有效时长(单位:秒)
45
- }
46
- })
47
- })
48
- })
49
- }
50
-
51
- // 获取门锁信息
52
- function openSmartRoomList(para){
53
- // para.requestUrl 接口请求地址
54
- // para.tokenId 访问令牌
55
-
56
- return new Promise((resolve, reject) => {
57
- let startNum = 0, // 开始下标,默认:0
58
- pageSize = 10, // 分页大小,默认:10
59
- pageSizeMax = 50 // 分页大小,最大:50
60
-
61
- // 第一次请求
62
- Request({
63
- url: para.requestUrl,
64
- method: 'POST',
65
- json: true,
66
- headers: {
67
- 'Content-Type': 'text/json;charset=utf-8',
68
- 'Content-Version': '1.0' // 接口版本,不填则默认获取1.0版本
69
- },
70
- body: {
71
- method: 'openSmartRoomList', // 接口方法
72
- tokenId: para.tokenId,
73
- data: {
74
- startNum,
75
- pageSize: pageSizeMax
76
- }
77
- }
78
- }, function (error, response, body) {
79
- if (error) throw error
80
-
81
- let resultCode = body.resultCode,
82
- reason = body.reason,
83
- roomList = body.data.roomList, // 门锁信息
84
- listSum = body.listSum // 总记录数
85
-
86
- if (resultCode !== 0) {
87
- return resolve({code: 1, message: '获取门锁信息失败:' + reason})
88
- }
89
-
90
- let roomListAll = [], // 门锁信息转义、累加
91
- arrPromiseReq = []
92
-
93
- for (let i = 0; i < roomList.length; i++) {
94
- roomListAll.push({
95
- roomName: roomList [i].roomName, // 房号
96
- buildingCode: roomList [i].buildingCode, // 楼栋编码
97
- floorCode: roomList [i].floorCode, // 楼层
98
- roomCode: roomList [i].roomCode, // 房间编码
99
- lockCode: roomList [i].lockCode, // 门锁编码
100
- lockMac: roomList [i].lockMac, // 门锁Mac
101
- aesKey: roomList [i].aesKey // 门锁AES128密钥
102
- })
103
- }
104
-
105
- //剩余请求次数
106
- let reqCount = Math.floor(listSum / pageSizeMax)
107
- reqCount = listSum % pageSizeMax > 0 ? reqCount + 1 : reqCount
108
- reqCount = reqCount > 0 ? reqCount - 1 : 0
109
-
110
- //继续发送请求
111
- for (let iReq = 0; iReq < reqCount; iReq++) {
112
- arrPromiseReq.push(new Promise((resolve0, reject0) => {
113
- Request({
114
- url: para.requestUrl,
115
- method: 'POST',
116
- json: true,
117
- headers: {
118
- 'Content-Type': 'text/json;charset=utf-8',
119
- 'Content-Version': '1.0' // 接口版本,不填则默认获取1.0版本
120
- },
121
- body: {
122
- method: 'openSmartRoomList', // 接口方法
123
- tokenId: para.tokenId,
124
- data: {
125
- startNum: (iReq + 1) * pageSizeMax + 1,
126
- pageSize: pageSizeMax
127
- }
128
- }
129
- }, function (error, response, body) {
130
- if (error) throw error
131
-
132
- let resultCode = body.resultCode,
133
- reason = body.reason,
134
- roomList = body.data.roomList // 门锁信息
135
-
136
- if (resultCode !== 0) {
137
- return resolve({code: 1, message: '获取门锁信息失败:' + reason})
138
- }
139
-
140
- //门锁信息转义、累加
141
- for (let i = 0; i < roomList.length; i++) {
142
- roomListAll.push({
143
- roomName: roomList [i].roomName, // 房号
144
- buildingCode: roomList [i].buildingCode, // 楼栋编码
145
- floorCode: roomList [i].floorCode, // 楼层
146
- roomCode: roomList [i].roomCode, // 房间编码
147
- lockCode: roomList [i].lockCode, // 门锁编码
148
- lockMac: roomList [i].lockMac, // 门锁Mac
149
- aesKey: roomList [i].aesKey // 门锁AES128密钥
150
- })
151
- }
152
-
153
- resolve0()
154
- })
155
- }))
156
- }
157
-
158
- Promise.all(arrPromiseReq).then(() => {
159
- resolve({code: 0, message: '获取门锁信息成功',
160
- data: roomListAll
161
- })
162
- })
163
- })
164
- })
165
- }
166
-
167
- export {
168
- openSmartLogin,
169
- openSmartRoomList
170
- }
171
- export default {
172
- openSmartLogin,
173
- openSmartRoomList
174
- }
package/src/crypto/AES.js DELETED
@@ -1,141 +0,0 @@
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 {
131
- generateKeyAndIV,
132
- checkKeyAndIV,
133
- aesEncrypt,
134
- aesDecrypt
135
- };
136
- export default {
137
- generateKeyAndIV,
138
- checkKeyAndIV,
139
- aesEncrypt,
140
- aesDecrypt
141
- };
@@ -1,33 +0,0 @@
1
- import crypto from 'crypto'
2
-
3
- function md5(text){
4
- if(!text){
5
- return ''
6
- }
7
- return crypto.createHash('md5').update(text).digest('hex')
8
- }
9
-
10
- function sha1(text){
11
- if(!text){
12
- return ''
13
- }
14
- return crypto.createHash('sha1').update(text).digest('hex')
15
- }
16
-
17
- function sha256(text){
18
- if(!text){
19
- return ''
20
- }
21
- return crypto.createHash('sha256').update(text).digest('hex')
22
- }
23
-
24
- export {
25
- md5,
26
- sha1,
27
- sha256
28
- }
29
- export default {
30
- md5,
31
- sha1,
32
- sha256
33
- }
package/src/crypto/RSA.js DELETED
@@ -1,145 +0,0 @@
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 {
137
- generateRSAKeyPair,
138
- rsaSign,
139
- rsaVerify
140
- }
141
- export default {
142
- generateRSAKeyPair,
143
- rsaSign,
144
- rsaVerify
145
- }
@@ -1,14 +0,0 @@
1
- import AES from './AES.js'
2
- import Hash from './Hash.js'
3
- import RSA from './RSA.js'
4
-
5
- export {
6
- AES,
7
- Hash,
8
- RSA
9
- }
10
- export default {
11
- AES,
12
- Hash,
13
- RSA
14
- }
package/src/index.js DELETED
@@ -1,29 +0,0 @@
1
- import Ali from './Ali/index.js'
2
- import crypto from './crypto/index.js'
3
- import Email from './Email/index.js'
4
- import Feie from './Feie/index.js'
5
- import FileDB from './FileDB/index.js'
6
- import WeChat from './WeChat/index.js'
7
- import WeChat_Pay from './WeChat-Pay/index.js'
8
- import Yizoo from './Yizoo/index.js'
9
-
10
- export {
11
- Ali,
12
- crypto,
13
- Email,
14
- Feie,
15
- FileDB,
16
- WeChat,
17
- WeChat_Pay,
18
- Yizoo
19
- }
20
- export default {
21
- Ali,
22
- crypto,
23
- Email,
24
- Feie,
25
- FileDB,
26
- WeChat,
27
- WeChat_Pay,
28
- Yizoo
29
- }