ph-utils 0.4.8 → 0.5.0
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/lib/crypto.d.ts +1 -1
- package/lib/crypto.js +47 -45
- package/lib/file.d.ts +6 -8
- package/lib/file.js +12 -44
- package/package.json +1 -1
package/lib/crypto.d.ts
CHANGED
@@ -14,7 +14,7 @@ export declare function bufferToHex(bf: ArrayBuffer | Uint8Array, upper?: boolea
|
|
14
14
|
*/
|
15
15
|
export declare function sha(message: string, upper?: boolean, algorithm?: string): Promise<string>;
|
16
16
|
/** 返回结果类似 */
|
17
|
-
type AlgorithmResType =
|
17
|
+
type AlgorithmResType = "hex" | "hexUpper" | "base64" | "raw";
|
18
18
|
/**
|
19
19
|
* AES 加密
|
20
20
|
* @param message 待加密的数据
|
package/lib/crypto.js
CHANGED
@@ -10,10 +10,10 @@ export function bufferToHex(bf, upper = false) {
|
|
10
10
|
const hashArray = Array.from(u8Array);
|
11
11
|
return hashArray
|
12
12
|
.map((b) => {
|
13
|
-
let hx = b.toString(16).padStart(2,
|
13
|
+
let hx = b.toString(16).padStart(2, "0");
|
14
14
|
return upper === true ? hx.toUpperCase() : hx;
|
15
15
|
})
|
16
|
-
.join(
|
16
|
+
.join("");
|
17
17
|
}
|
18
18
|
/**
|
19
19
|
* 将16进制的数据转换为 UInt8Array
|
@@ -38,7 +38,7 @@ function hexToBuffer(data) {
|
|
38
38
|
function bufferToBase64(bf) {
|
39
39
|
const u8Array = bf instanceof Uint8Array ? bf : new Uint8Array(bf);
|
40
40
|
const hashArray = Array.from(u8Array);
|
41
|
-
return
|
41
|
+
return globalThis.btoa(String.fromCharCode.apply(null, hashArray));
|
42
42
|
}
|
43
43
|
/**
|
44
44
|
* 将 Base64 转换为 UInt8Array 数据
|
@@ -46,9 +46,9 @@ function bufferToBase64(bf) {
|
|
46
46
|
* @returns
|
47
47
|
*/
|
48
48
|
function base64ToBuffer(data) {
|
49
|
-
return new Uint8Array(
|
49
|
+
return new Uint8Array(globalThis
|
50
50
|
.atob(data)
|
51
|
-
.split(
|
51
|
+
.split("")
|
52
52
|
.map((char) => char.charCodeAt(0)));
|
53
53
|
}
|
54
54
|
/**
|
@@ -58,14 +58,14 @@ function base64ToBuffer(data) {
|
|
58
58
|
* @param algorithm hash算法, 支持: SHA-1、SHA-256、SHA-384、SHA-512; 默认为: SHA-256
|
59
59
|
* @returns
|
60
60
|
*/
|
61
|
-
export async function sha(message, upper = false, algorithm =
|
61
|
+
export async function sha(message, upper = false, algorithm = "SHA-256") {
|
62
62
|
const msgUint8 = new TextEncoder().encode(message);
|
63
|
-
const hashBuffer = await
|
63
|
+
const hashBuffer = await globalThis.crypto.subtle.digest(algorithm || "SHA-256", msgUint8);
|
64
64
|
return bufferToHex(hashBuffer, upper);
|
65
65
|
}
|
66
66
|
function parseRsaKey(pem) {
|
67
|
-
const pemHeader =
|
68
|
-
const pemFooter =
|
67
|
+
const pemHeader = "-----BEGIN PUBLIC KEY-----";
|
68
|
+
const pemFooter = "-----END PUBLIC KEY-----";
|
69
69
|
if (pem.indexOf(pemHeader) !== -1 && pem.indexOf(pemFooter) !== -1) {
|
70
70
|
pem = pem.substring(pemHeader.length, pem.indexOf(pemFooter)).trim();
|
71
71
|
}
|
@@ -79,34 +79,34 @@ function parseRsaKey(pem) {
|
|
79
79
|
* @returns
|
80
80
|
*/
|
81
81
|
// eslint-disable-next-line no-undef
|
82
|
-
async function importKey(key, algorithmName, usages, encoding =
|
83
|
-
let name =
|
82
|
+
async function importKey(key, algorithmName, usages, encoding = "hex") {
|
83
|
+
let name = "AES-CBC";
|
84
84
|
if (algorithmName == null) {
|
85
|
-
name =
|
85
|
+
name = "AES-CBC";
|
86
86
|
}
|
87
87
|
else {
|
88
|
-
if (algorithmName.toUpperCase() ===
|
89
|
-
name =
|
88
|
+
if (algorithmName.toUpperCase() === "AES") {
|
89
|
+
name = "AES-CBC";
|
90
90
|
}
|
91
|
-
else if (algorithmName.toUpperCase() ===
|
92
|
-
name =
|
91
|
+
else if (algorithmName.toUpperCase() === "RSA") {
|
92
|
+
name = "RSA-OAEP";
|
93
93
|
}
|
94
94
|
}
|
95
95
|
name = name.toUpperCase();
|
96
96
|
if (usages == null || usages.length === 0) {
|
97
|
-
usages = [
|
97
|
+
usages = ["encrypt"];
|
98
98
|
}
|
99
|
-
let format =
|
99
|
+
let format = "raw";
|
100
100
|
let algorithm = { name };
|
101
|
-
if (name.includes(
|
102
|
-
format =
|
103
|
-
algorithm.hash = { name:
|
101
|
+
if (name.includes("RSA")) {
|
102
|
+
format = "spki";
|
103
|
+
algorithm.hash = { name: "SHA-256" };
|
104
104
|
key = parseRsaKey(key);
|
105
105
|
}
|
106
|
-
const keyBuf = encoding ===
|
106
|
+
const keyBuf = encoding === "base64" ? base64ToBuffer(key) : hexToBuffer(key);
|
107
107
|
// importKey时传 false 表明该密钥不能被导出
|
108
108
|
return Promise.all([
|
109
|
-
|
109
|
+
globalThis.crypto.subtle.importKey(format, keyBuf, algorithm, false, usages),
|
110
110
|
Promise.resolve({ name }),
|
111
111
|
]);
|
112
112
|
}
|
@@ -118,18 +118,18 @@ async function importKey(key, algorithmName, usages, encoding = 'hex') {
|
|
118
118
|
* @param encode 解密后返回数据格式
|
119
119
|
* @returns
|
120
120
|
*/
|
121
|
-
async function encrypt(algorithm, key, message, encode =
|
122
|
-
if (typeof message ===
|
121
|
+
async function encrypt(algorithm, key, message, encode = "hex") {
|
122
|
+
if (typeof message === "string") {
|
123
123
|
message = new TextEncoder().encode(message);
|
124
124
|
}
|
125
|
-
const encrypted = await
|
126
|
-
if (encode ===
|
125
|
+
const encrypted = await globalThis.crypto.subtle.encrypt(algorithm, key, message);
|
126
|
+
if (encode === "hex") {
|
127
127
|
return bufferToHex(encrypted);
|
128
128
|
}
|
129
|
-
else if (encode ===
|
129
|
+
else if (encode === "hexUpper") {
|
130
130
|
return bufferToHex(encrypted, true);
|
131
131
|
}
|
132
|
-
else if (encode ===
|
132
|
+
else if (encode === "base64") {
|
133
133
|
return bufferToBase64(encrypted);
|
134
134
|
}
|
135
135
|
else {
|
@@ -144,8 +144,8 @@ async function encrypt(algorithm, key, message, encode = 'hex') {
|
|
144
144
|
* @returns
|
145
145
|
*/
|
146
146
|
async function decrypt(algorithm, key, message) {
|
147
|
-
const decrypted = await
|
148
|
-
return new TextDecoder(
|
147
|
+
const decrypted = await globalThis.crypto.subtle.decrypt(algorithm, key, message);
|
148
|
+
return new TextDecoder("utf-8").decode(decrypted);
|
149
149
|
}
|
150
150
|
/**
|
151
151
|
* AES 加密
|
@@ -155,15 +155,15 @@ async function decrypt(algorithm, key, message) {
|
|
155
155
|
* @param iv 加解密向量
|
156
156
|
* @returns [加密数据,向量]
|
157
157
|
*/
|
158
|
-
export async function aesEncrypt(message, key, encode =
|
159
|
-
let ciphertext =
|
160
|
-
let resIv =
|
158
|
+
export async function aesEncrypt(message, key, encode = "hex", iv = null) {
|
159
|
+
let ciphertext = "";
|
160
|
+
let resIv = "";
|
161
161
|
// 导入密钥
|
162
|
-
const [cryptoKey, algorithm] = await importKey(key,
|
162
|
+
const [cryptoKey, algorithm] = await importKey(key, "aes", ["encrypt"]);
|
163
163
|
if (iv == null) {
|
164
|
-
iv =
|
164
|
+
iv = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
165
165
|
}
|
166
|
-
else if (typeof iv ===
|
166
|
+
else if (typeof iv === "string") {
|
167
167
|
iv = hexToBuffer(iv);
|
168
168
|
}
|
169
169
|
const encodeData = await encrypt({ ...algorithm, iv }, cryptoKey, message, encode);
|
@@ -179,8 +179,8 @@ export async function aesEncrypt(message, key, encode = 'hex', iv = null) {
|
|
179
179
|
*/
|
180
180
|
function parseEncryptData(message, type) {
|
181
181
|
let input;
|
182
|
-
if (typeof message ===
|
183
|
-
if (type ===
|
182
|
+
if (typeof message === "string") {
|
183
|
+
if (type === "hex" || type === "hexUpper") {
|
184
184
|
input = hexToBuffer(message);
|
185
185
|
}
|
186
186
|
else {
|
@@ -200,9 +200,9 @@ function parseEncryptData(message, type) {
|
|
200
200
|
* @param encode 加密后数据的形式: hex | base64
|
201
201
|
* @returns
|
202
202
|
*/
|
203
|
-
export async function aesDecrypt(message, key, iv, encode =
|
203
|
+
export async function aesDecrypt(message, key, iv, encode = "hex") {
|
204
204
|
// 导入密钥
|
205
|
-
const [cryptoKey, algorithm] = await importKey(key,
|
205
|
+
const [cryptoKey, algorithm] = await importKey(key, "aes", ["decrypt"]);
|
206
206
|
const input = parseEncryptData(message, encode);
|
207
207
|
return await decrypt({ ...algorithm, iv: hexToBuffer(iv) }, cryptoKey, input);
|
208
208
|
}
|
@@ -213,9 +213,9 @@ export async function aesDecrypt(message, key, iv, encode = 'hex') {
|
|
213
213
|
* @param encode 返回类型
|
214
214
|
* @returns
|
215
215
|
*/
|
216
|
-
export async function rsaEncrypt(message, publicKey, encode =
|
216
|
+
export async function rsaEncrypt(message, publicKey, encode = "hex") {
|
217
217
|
// 导入密钥
|
218
|
-
const [cryptoKey, algorithm] = await importKey(publicKey,
|
218
|
+
const [cryptoKey, algorithm] = await importKey(publicKey, "rsa", ["encrypt"], "base64");
|
219
219
|
return await encrypt(algorithm, cryptoKey, message, encode);
|
220
220
|
}
|
221
221
|
/**
|
@@ -225,8 +225,10 @@ export async function rsaEncrypt(message, publicKey, encode = 'hex') {
|
|
225
225
|
* @param encode 加密后的数据形式
|
226
226
|
* @returns
|
227
227
|
*/
|
228
|
-
export async function rsaDecrypt(privateKey, message, encode =
|
228
|
+
export async function rsaDecrypt(privateKey, message, encode = "hex") {
|
229
229
|
// 导入密钥
|
230
|
-
const [cryptoKey, algorithm] = await importKey(privateKey,
|
230
|
+
const [cryptoKey, algorithm] = await importKey(privateKey, "rsa", [
|
231
|
+
"decrypt",
|
232
|
+
]);
|
231
233
|
return await decrypt({ ...algorithm }, cryptoKey, parseEncryptData(message, encode));
|
232
234
|
}
|
package/lib/file.d.ts
CHANGED
@@ -1,9 +1,14 @@
|
|
1
1
|
/**
|
2
2
|
* 读取文件内容为JSON格式
|
3
3
|
* @param filepath 读取的文件路径
|
4
|
+
* @param errIsNull 读取失败时,是否返回 null,默认为 false[抛出异常]
|
5
|
+
*
|
6
|
+
* @example <caption>1. 文件不存在时, 返回null,而不是 catch</caption>
|
7
|
+
* await readJSON("./not-exists.json", true);
|
8
|
+
*
|
4
9
|
* @returns Promise<unknown>
|
5
10
|
*/
|
6
|
-
export declare function readJSON<T>(filepath: string): Promise<T>;
|
11
|
+
export declare function readJSON<T>(filepath: string, errIsNull?: boolean): Promise<T>;
|
7
12
|
/**
|
8
13
|
* 写入 JSON 格式的数据到文件
|
9
14
|
* @param file 待写入的文件
|
@@ -16,13 +21,6 @@ export declare function write(file: string, data: any, opts?: {
|
|
16
21
|
json: boolean;
|
17
22
|
format: boolean;
|
18
23
|
}): Promise<unknown>;
|
19
|
-
/**
|
20
|
-
* 遍历文件夹
|
21
|
-
* @param dir 待遍历的目录
|
22
|
-
* @param callback 遍历到文件后的回调
|
23
|
-
* @param done 遍历完成后的回调
|
24
|
-
*/
|
25
|
-
export declare function traverseDir(dir: string, callback?: (filename: string) => void, done?: () => void): void;
|
26
24
|
/**
|
27
25
|
* 根据文件的 stat 获取文件的 etag
|
28
26
|
* @param filePath 文件地址
|
package/lib/file.js
CHANGED
@@ -4,13 +4,23 @@ import fs from "node:fs";
|
|
4
4
|
/**
|
5
5
|
* 读取文件内容为JSON格式
|
6
6
|
* @param filepath 读取的文件路径
|
7
|
+
* @param errIsNull 读取失败时,是否返回 null,默认为 false[抛出异常]
|
8
|
+
*
|
9
|
+
* @example <caption>1. 文件不存在时, 返回null,而不是 catch</caption>
|
10
|
+
* await readJSON("./not-exists.json", true);
|
11
|
+
*
|
7
12
|
* @returns Promise<unknown>
|
8
13
|
*/
|
9
|
-
export function readJSON(filepath) {
|
14
|
+
export function readJSON(filepath, errIsNull = false) {
|
10
15
|
return new Promise((resolve, reject) => {
|
11
16
|
fs.readFile(path.resolve(filepath), "utf-8", (err, data) => {
|
12
17
|
if (err) {
|
13
|
-
|
18
|
+
if (errIsNull) {
|
19
|
+
resolve(null);
|
20
|
+
}
|
21
|
+
else {
|
22
|
+
reject(err);
|
23
|
+
}
|
14
24
|
}
|
15
25
|
else {
|
16
26
|
resolve(JSON.parse(data));
|
@@ -43,48 +53,6 @@ export function write(file, data, opts) {
|
|
43
53
|
});
|
44
54
|
});
|
45
55
|
}
|
46
|
-
/**
|
47
|
-
* 遍历文件夹
|
48
|
-
* @param dir 待遍历的目录
|
49
|
-
* @param callback 遍历到文件后的回调
|
50
|
-
* @param done 遍历完成后的回调
|
51
|
-
*/
|
52
|
-
export function traverseDir(dir, callback, done) {
|
53
|
-
let t = -1; // 定时任务,简单延迟作为遍历完成计算
|
54
|
-
function list(dr, cb, d) {
|
55
|
-
fs.readdir(path.resolve(dr), { withFileTypes: true }, (err, files) => {
|
56
|
-
if (err && err.errno === -4052) {
|
57
|
-
// 本身就是文件
|
58
|
-
if (typeof cb === "function")
|
59
|
-
cb(dr);
|
60
|
-
if (typeof d === "function")
|
61
|
-
d(); // 遍历完成
|
62
|
-
}
|
63
|
-
else {
|
64
|
-
for (let i = 0, len = files.length; i < len; i++) {
|
65
|
-
const file = files[i];
|
66
|
-
if (file.isFile()) {
|
67
|
-
if (typeof cb === "function")
|
68
|
-
cb(path.join(dr, file.name));
|
69
|
-
clearTimeout(t);
|
70
|
-
t = setTimeout(() => {
|
71
|
-
setImmediate(() => {
|
72
|
-
if (typeof done === "function") {
|
73
|
-
done();
|
74
|
-
}
|
75
|
-
});
|
76
|
-
}, 10);
|
77
|
-
}
|
78
|
-
else {
|
79
|
-
// 文件夹
|
80
|
-
list(path.join(dr, file.name), cb, d);
|
81
|
-
}
|
82
|
-
}
|
83
|
-
}
|
84
|
-
});
|
85
|
-
}
|
86
|
-
list(dir, callback, done);
|
87
|
-
}
|
88
56
|
/**
|
89
57
|
* 根据文件的 stat 获取文件的 etag
|
90
58
|
* @param filePath 文件地址
|