@gjsify/crypto 0.3.16 → 0.3.17

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,371 +1 @@
1
- import { derToPem, encodePrivateKeyInfo, encodeRsaPrivateKeyPkcs1, encodeRsaPublicKeyPkcs1, encodeSubjectPublicKeyInfo, parsePemKey, rsaKeySize } from "./asn1.js";
2
- import { Buffer } from "node:buffer";
3
-
4
- //#region src/key-object.ts
5
- /** Convert BigInt to base64url-encoded string (no padding). */
6
- function bigintToBase64url(value) {
7
- if (value === 0n) return "AA";
8
- const hex = value.toString(16);
9
- const paddedHex = hex.length % 2 ? "0" + hex : hex;
10
- const bytes = [];
11
- for (let i = 0; i < paddedHex.length; i += 2) {
12
- bytes.push(parseInt(paddedHex.substring(i, i + 2), 16));
13
- }
14
- return Buffer.from(bytes).toString("base64url");
15
- }
16
- /** Convert base64url-encoded string to BigInt. */
17
- function base64urlToBigint(b64) {
18
- const buf = Buffer.from(b64, "base64url");
19
- let result = 0n;
20
- for (let i = 0; i < buf.length; i++) {
21
- result = result << 8n | BigInt(buf[i]);
22
- }
23
- return result;
24
- }
25
- var KeyObject = class KeyObject {
26
- type;
27
- /** @internal */
28
- _handle;
29
- constructor(type, handle) {
30
- if (type !== "secret" && type !== "public" && type !== "private") {
31
- throw new TypeError(`Invalid KeyObject type: ${type}`);
32
- }
33
- this.type = type;
34
- this._handle = handle;
35
- }
36
- get symmetricKeySize() {
37
- if (this.type !== "secret") return undefined;
38
- return this._handle.byteLength;
39
- }
40
- get asymmetricKeyType() {
41
- if (this.type === "secret") return undefined;
42
- const handle = this._handle;
43
- if (handle.parsed.type === "rsa-public" || handle.parsed.type === "rsa-private") {
44
- return "rsa";
45
- }
46
- return undefined;
47
- }
48
- get asymmetricKeySize() {
49
- if (this.type === "secret") return undefined;
50
- const handle = this._handle;
51
- if (handle.parsed.type === "rsa-public") {
52
- return rsaKeySize(handle.parsed.components.n) / 8;
53
- }
54
- if (handle.parsed.type === "rsa-private") {
55
- return rsaKeySize(handle.parsed.components.n) / 8;
56
- }
57
- return undefined;
58
- }
59
- equals(otherKeyObject) {
60
- if (!(otherKeyObject instanceof KeyObject)) return false;
61
- if (this.type !== otherKeyObject.type) return false;
62
- if (this.type === "secret") {
63
- const a = this._handle;
64
- const b = otherKeyObject._handle;
65
- if (a.byteLength !== b.byteLength) return false;
66
- for (let i = 0; i < a.byteLength; i++) {
67
- if (a[i] !== b[i]) return false;
68
- }
69
- return true;
70
- }
71
- const a = this._handle;
72
- const b = otherKeyObject._handle;
73
- return a.pem === b.pem;
74
- }
75
- export(options) {
76
- if (this.type === "secret") {
77
- const key = this._handle;
78
- if (options?.format === "jwk") {
79
- return {
80
- kty: "oct",
81
- k: Buffer.from(key).toString("base64url")
82
- };
83
- }
84
- return Buffer.from(key);
85
- }
86
- const handle = this._handle;
87
- const format = options?.format ?? "pem";
88
- const keyType = options?.type;
89
- if (format === "jwk") {
90
- return exportJwk(handle.parsed, this.type);
91
- }
92
- if (format === "pem") {
93
- if (handle.pem && !handle.pem.startsWith("[")) {
94
- return handle.pem;
95
- }
96
- return generatePem(handle.parsed, this.type, keyType);
97
- }
98
- if (format === "der") {
99
- if (handle.pem && !handle.pem.startsWith("[")) {
100
- const lines = handle.pem.trim().split(/\r?\n/);
101
- const headerIdx = lines.findIndex((l) => l.startsWith("-----BEGIN "));
102
- const footerIdx = lines.findIndex((l, i) => i > headerIdx && l.startsWith("-----END "));
103
- const base64Body = lines.slice(headerIdx + 1, footerIdx).join("");
104
- return Buffer.from(base64Body, "base64");
105
- }
106
- return generateDer(handle.parsed, this.type, keyType);
107
- }
108
- throw new TypeError(`Unsupported export format: ${format}`);
109
- }
110
- get [Symbol.toStringTag]() {
111
- return "KeyObject";
112
- }
113
- };
114
- function exportJwk(parsed, keyType) {
115
- if (parsed.type === "rsa-public") {
116
- return {
117
- kty: "RSA",
118
- n: bigintToBase64url(parsed.components.n),
119
- e: bigintToBase64url(parsed.components.e)
120
- };
121
- }
122
- if (parsed.type === "rsa-private") {
123
- if (keyType === "public") {
124
- return {
125
- kty: "RSA",
126
- n: bigintToBase64url(parsed.components.n),
127
- e: bigintToBase64url(parsed.components.e)
128
- };
129
- }
130
- const { n, e, d, p, q } = parsed.components;
131
- const dp = d % (p - 1n);
132
- const dq = d % (q - 1n);
133
- const qi = modInverse(q, p);
134
- return {
135
- kty: "RSA",
136
- n: bigintToBase64url(n),
137
- e: bigintToBase64url(e),
138
- d: bigintToBase64url(d),
139
- p: bigintToBase64url(p),
140
- q: bigintToBase64url(q),
141
- dp: bigintToBase64url(dp),
142
- dq: bigintToBase64url(dq),
143
- qi: bigintToBase64url(qi)
144
- };
145
- }
146
- throw new Error("Unsupported key type for JWK export");
147
- }
148
- function importJwkRsa(jwk) {
149
- if (jwk.d) {
150
- const components = {
151
- n: base64urlToBigint(jwk.n),
152
- e: base64urlToBigint(jwk.e),
153
- d: base64urlToBigint(jwk.d),
154
- p: base64urlToBigint(jwk.p),
155
- q: base64urlToBigint(jwk.q)
156
- };
157
- const parsed = {
158
- type: "rsa-private",
159
- components
160
- };
161
- const der = encodeRsaPrivateKeyPkcs1(components);
162
- const pem = derToPem(der, "RSA PRIVATE KEY");
163
- return {
164
- parsed,
165
- pem
166
- };
167
- }
168
- const components = {
169
- n: base64urlToBigint(jwk.n),
170
- e: base64urlToBigint(jwk.e)
171
- };
172
- const parsed = {
173
- type: "rsa-public",
174
- components
175
- };
176
- const der = encodeSubjectPublicKeyInfo(components);
177
- const pem = derToPem(der, "PUBLIC KEY");
178
- return {
179
- parsed,
180
- pem
181
- };
182
- }
183
- function generatePem(parsed, keyType, type) {
184
- if (parsed.type === "rsa-public") {
185
- if (type === "pkcs1") {
186
- const der = encodeRsaPublicKeyPkcs1(parsed.components);
187
- return derToPem(der, "RSA PUBLIC KEY");
188
- }
189
- const der = encodeSubjectPublicKeyInfo(parsed.components);
190
- return derToPem(der, "PUBLIC KEY");
191
- }
192
- if (parsed.type === "rsa-private" && keyType === "public") {
193
- const pubComponents = {
194
- n: parsed.components.n,
195
- e: parsed.components.e
196
- };
197
- if (type === "pkcs1") {
198
- const der = encodeRsaPublicKeyPkcs1(pubComponents);
199
- return derToPem(der, "RSA PUBLIC KEY");
200
- }
201
- const der = encodeSubjectPublicKeyInfo(pubComponents);
202
- return derToPem(der, "PUBLIC KEY");
203
- }
204
- if (parsed.type === "rsa-private") {
205
- if (type === "pkcs8") {
206
- const der = encodePrivateKeyInfo(parsed.components);
207
- return derToPem(der, "PRIVATE KEY");
208
- }
209
- const der = encodeRsaPrivateKeyPkcs1(parsed.components);
210
- return derToPem(der, "RSA PRIVATE KEY");
211
- }
212
- throw new Error("Cannot generate PEM for this key type");
213
- }
214
- function generateDer(parsed, keyType, type) {
215
- if (parsed.type === "rsa-public") {
216
- if (type === "pkcs1") {
217
- return Buffer.from(encodeRsaPublicKeyPkcs1(parsed.components));
218
- }
219
- return Buffer.from(encodeSubjectPublicKeyInfo(parsed.components));
220
- }
221
- if (parsed.type === "rsa-private" && keyType === "public") {
222
- const pubComponents = {
223
- n: parsed.components.n,
224
- e: parsed.components.e
225
- };
226
- if (type === "pkcs1") {
227
- return Buffer.from(encodeRsaPublicKeyPkcs1(pubComponents));
228
- }
229
- return Buffer.from(encodeSubjectPublicKeyInfo(pubComponents));
230
- }
231
- if (parsed.type === "rsa-private") {
232
- if (type === "pkcs8") {
233
- return Buffer.from(encodePrivateKeyInfo(parsed.components));
234
- }
235
- return Buffer.from(encodeRsaPrivateKeyPkcs1(parsed.components));
236
- }
237
- throw new Error("Cannot generate DER for this key type");
238
- }
239
- function modInverse(a, m) {
240
- let [old_r, r] = [a % m, m];
241
- let [old_s, s] = [1n, 0n];
242
- while (r !== 0n) {
243
- const q = old_r / r;
244
- [old_r, r] = [r, old_r - q * r];
245
- [old_s, s] = [s, old_s - q * s];
246
- }
247
- return (old_s % m + m) % m;
248
- }
249
- /**
250
- * Create a secret key from raw bytes.
251
- */
252
- function createSecretKey(key, encoding) {
253
- let keyBuf;
254
- if (typeof key === "string") {
255
- keyBuf = Buffer.from(key, encoding ?? "utf8");
256
- } else {
257
- keyBuf = new Uint8Array(key);
258
- }
259
- return new KeyObject("secret", keyBuf);
260
- }
261
- /**
262
- * Create a public key from PEM, DER, JWK, or another KeyObject.
263
- */
264
- function createPublicKey(key) {
265
- if (key instanceof KeyObject) {
266
- if (key.type === "public") return key;
267
- if (key.type === "private") {
268
- const handle = key._handle;
269
- if (handle.parsed.type === "rsa-private") {
270
- const pubComponents = {
271
- n: handle.parsed.components.n,
272
- e: handle.parsed.components.e
273
- };
274
- const pubParsed = {
275
- type: "rsa-public",
276
- components: pubComponents
277
- };
278
- const der = encodeSubjectPublicKeyInfo(pubComponents);
279
- const pem = derToPem(der, "PUBLIC KEY");
280
- return new KeyObject("public", {
281
- parsed: pubParsed,
282
- pem
283
- });
284
- }
285
- }
286
- throw new TypeError("Cannot create public key from secret key");
287
- }
288
- if (typeof key === "object" && !Buffer.isBuffer(key) && "key" in key) {
289
- const input = key;
290
- if (input.format === "jwk") {
291
- const jwk = input.key;
292
- if (jwk.kty === "RSA") {
293
- const { parsed, pem } = importJwkRsa({
294
- n: jwk.n,
295
- e: jwk.e
296
- });
297
- return new KeyObject("public", {
298
- parsed,
299
- pem
300
- });
301
- }
302
- throw new Error(`Unsupported JWK key type: ${jwk.kty}`);
303
- }
304
- }
305
- const pem = normalizePem(key);
306
- const parsed = parsePemKey(pem);
307
- if (parsed.type === "rsa-private") {
308
- const pubComponents = {
309
- n: parsed.components.n,
310
- e: parsed.components.e
311
- };
312
- const pubParsed = {
313
- type: "rsa-public",
314
- components: pubComponents
315
- };
316
- const der = encodeSubjectPublicKeyInfo(pubComponents);
317
- const pubPem = derToPem(der, "PUBLIC KEY");
318
- return new KeyObject("public", {
319
- parsed: pubParsed,
320
- pem: pubPem
321
- });
322
- }
323
- return new KeyObject("public", {
324
- parsed,
325
- pem
326
- });
327
- }
328
- /**
329
- * Create a private key from PEM, DER, JWK, or KeyInput.
330
- */
331
- function createPrivateKey(key) {
332
- if (typeof key === "object" && !Buffer.isBuffer(key) && "key" in key) {
333
- const input = key;
334
- if (input.format === "jwk") {
335
- const jwk = input.key;
336
- if (jwk.kty === "RSA" && jwk.d) {
337
- const { parsed, pem } = importJwkRsa(jwk);
338
- return new KeyObject("private", {
339
- parsed,
340
- pem
341
- });
342
- }
343
- throw new Error("JWK does not contain a private key");
344
- }
345
- }
346
- const pem = normalizePem(key);
347
- const parsed = parsePemKey(pem);
348
- if (parsed.type !== "rsa-private") {
349
- throw new TypeError("Key is not a private key");
350
- }
351
- return new KeyObject("private", {
352
- parsed,
353
- pem
354
- });
355
- }
356
- function normalizePem(key) {
357
- if (typeof key === "string") return key;
358
- if (Buffer.isBuffer(key)) return key.toString("utf8");
359
- if (key && typeof key === "object" && "key" in key) {
360
- const input = key;
361
- if (typeof input.key === "string") return input.key;
362
- if (Buffer.isBuffer(input.key)) return input.key.toString(input.encoding ?? "utf8");
363
- if (input.key instanceof KeyObject) {
364
- return input.key.export({ format: "pem" });
365
- }
366
- }
367
- throw new TypeError("Invalid key input");
368
- }
369
-
370
- //#endregion
371
- export { KeyObject, createPrivateKey, createPublicKey, createSecretKey };
1
+ import{derToPem as e,encodePrivateKeyInfo as t,encodeRsaPrivateKeyPkcs1 as n,encodeRsaPublicKeyPkcs1 as r,encodeSubjectPublicKeyInfo as i,parsePemKey as a,rsaKeySize as o}from"./asn1.js";import{Buffer as s}from"node:buffer";function c(e){if(e===0n)return`AA`;let t=e.toString(16),n=t.length%2?`0`+t:t,r=[];for(let e=0;e<n.length;e+=2)r.push(parseInt(n.substring(e,e+2),16));return s.from(r).toString(`base64url`)}function l(e){let t=s.from(e,`base64url`),n=0n;for(let e=0;e<t.length;e++)n=n<<8n|BigInt(t[e]);return n}var u=class e{type;_handle;constructor(e,t){if(e!==`secret`&&e!==`public`&&e!==`private`)throw TypeError(`Invalid KeyObject type: ${e}`);this.type=e,this._handle=t}get symmetricKeySize(){if(this.type===`secret`)return this._handle.byteLength}get asymmetricKeyType(){if(this.type===`secret`)return;let e=this._handle;if(e.parsed.type===`rsa-public`||e.parsed.type===`rsa-private`)return`rsa`}get asymmetricKeySize(){if(this.type===`secret`)return;let e=this._handle;if(e.parsed.type===`rsa-public`||e.parsed.type===`rsa-private`)return o(e.parsed.components.n)/8}equals(t){if(!(t instanceof e)||this.type!==t.type)return!1;if(this.type===`secret`){let e=this._handle,n=t._handle;if(e.byteLength!==n.byteLength)return!1;for(let t=0;t<e.byteLength;t++)if(e[t]!==n[t])return!1;return!0}let n=this._handle,r=t._handle;return n.pem===r.pem}export(e){if(this.type===`secret`){let t=this._handle;return e?.format===`jwk`?{kty:`oct`,k:s.from(t).toString(`base64url`)}:s.from(t)}let t=this._handle,n=e?.format??`pem`,r=e?.type;if(n===`jwk`)return d(t.parsed,this.type);if(n===`pem`)return t.pem&&!t.pem.startsWith(`[`)?t.pem:p(t.parsed,this.type,r);if(n===`der`){if(t.pem&&!t.pem.startsWith(`[`)){let e=t.pem.trim().split(/\r?\n/),n=e.findIndex(e=>e.startsWith(`-----BEGIN `)),r=e.findIndex((e,t)=>t>n&&e.startsWith(`-----END `)),i=e.slice(n+1,r).join(``);return s.from(i,`base64`)}return m(t.parsed,this.type,r)}throw TypeError(`Unsupported export format: ${n}`)}get[Symbol.toStringTag](){return`KeyObject`}};function d(e,t){if(e.type===`rsa-public`)return{kty:`RSA`,n:c(e.components.n),e:c(e.components.e)};if(e.type===`rsa-private`){if(t===`public`)return{kty:`RSA`,n:c(e.components.n),e:c(e.components.e)};let{n,e:r,d:i,p:a,q:o}=e.components,s=i%(a-1n),l=i%(o-1n),u=h(o,a);return{kty:`RSA`,n:c(n),e:c(r),d:c(i),p:c(a),q:c(o),dp:c(s),dq:c(l),qi:c(u)}}throw Error(`Unsupported key type for JWK export`)}function f(t){if(t.d){let r={n:l(t.n),e:l(t.e),d:l(t.d),p:l(t.p),q:l(t.q)};return{parsed:{type:`rsa-private`,components:r},pem:e(n(r),`RSA PRIVATE KEY`)}}let r={n:l(t.n),e:l(t.e)};return{parsed:{type:`rsa-public`,components:r},pem:e(i(r),`PUBLIC KEY`)}}function p(a,o,s){if(a.type===`rsa-public`)return s===`pkcs1`?e(r(a.components),`RSA PUBLIC KEY`):e(i(a.components),`PUBLIC KEY`);if(a.type===`rsa-private`&&o===`public`){let t={n:a.components.n,e:a.components.e};return s===`pkcs1`?e(r(t),`RSA PUBLIC KEY`):e(i(t),`PUBLIC KEY`)}if(a.type===`rsa-private`)return s===`pkcs8`?e(t(a.components),`PRIVATE KEY`):e(n(a.components),`RSA PRIVATE KEY`);throw Error(`Cannot generate PEM for this key type`)}function m(e,a,o){if(e.type===`rsa-public`)return o===`pkcs1`?s.from(r(e.components)):s.from(i(e.components));if(e.type===`rsa-private`&&a===`public`){let t={n:e.components.n,e:e.components.e};return o===`pkcs1`?s.from(r(t)):s.from(i(t))}if(e.type===`rsa-private`)return o===`pkcs8`?s.from(t(e.components)):s.from(n(e.components));throw Error(`Cannot generate DER for this key type`)}function h(e,t){let[n,r]=[e%t,t],[i,a]=[1n,0n];for(;r!==0n;){let e=n/r;[n,r]=[r,n-e*r],[i,a]=[a,i-e*a]}return(i%t+t)%t}function g(e,t){let n;return n=typeof e==`string`?s.from(e,t??`utf8`):new Uint8Array(e),new u(`secret`,n)}function _(t){if(t instanceof u){if(t.type===`public`)return t;if(t.type===`private`){let n=t._handle;if(n.parsed.type===`rsa-private`){let t={n:n.parsed.components.n,e:n.parsed.components.e};return new u(`public`,{parsed:{type:`rsa-public`,components:t},pem:e(i(t),`PUBLIC KEY`)})}}throw TypeError(`Cannot create public key from secret key`)}if(typeof t==`object`&&!s.isBuffer(t)&&`key`in t){let e=t;if(e.format===`jwk`){let t=e.key;if(t.kty===`RSA`){let{parsed:e,pem:n}=f({n:t.n,e:t.e});return new u(`public`,{parsed:e,pem:n})}throw Error(`Unsupported JWK key type: ${t.kty}`)}}let n=y(t),r=a(n);if(r.type===`rsa-private`){let t={n:r.components.n,e:r.components.e};return new u(`public`,{parsed:{type:`rsa-public`,components:t},pem:e(i(t),`PUBLIC KEY`)})}return new u(`public`,{parsed:r,pem:n})}function v(e){if(typeof e==`object`&&!s.isBuffer(e)&&`key`in e){let t=e;if(t.format===`jwk`){let e=t.key;if(e.kty===`RSA`&&e.d){let{parsed:t,pem:n}=f(e);return new u(`private`,{parsed:t,pem:n})}throw Error(`JWK does not contain a private key`)}}let t=y(e),n=a(t);if(n.type!==`rsa-private`)throw TypeError(`Key is not a private key`);return new u(`private`,{parsed:n,pem:t})}function y(e){if(typeof e==`string`)return e;if(s.isBuffer(e))return e.toString(`utf8`);if(e&&typeof e==`object`&&`key`in e){let t=e;if(typeof t.key==`string`)return t.key;if(s.isBuffer(t.key))return t.key.toString(t.encoding??`utf8`);if(t.key instanceof u)return t.key.export({format:`pem`})}throw TypeError(`Invalid key input`)}export{u as KeyObject,v as createPrivateKey,_ as createPublicKey,g as createSecretKey};
package/lib/esm/mgf1.js CHANGED
@@ -1,33 +1 @@
1
- import { hashSize } from "./crypto-utils.js";
2
- import { Hash } from "./hash.js";
3
-
4
- //#region src/mgf1.ts
5
- /**
6
- * MGF1 mask generation function.
7
- * Produces a mask of `length` bytes from `seed` using `hashAlgo`.
8
- */
9
- function mgf1(hashAlgo, seed, length) {
10
- const hashLen = hashSize(hashAlgo);
11
- const mask = new Uint8Array(length);
12
- let offset = 0;
13
- let counter = 0;
14
- while (offset < length) {
15
- const C = new Uint8Array(4);
16
- C[0] = counter >>> 24 & 255;
17
- C[1] = counter >>> 16 & 255;
18
- C[2] = counter >>> 8 & 255;
19
- C[3] = counter & 255;
20
- const hash = new Hash(hashAlgo);
21
- hash.update(seed);
22
- hash.update(C);
23
- const digest = new Uint8Array(hash.digest());
24
- const toCopy = Math.min(digest.length, length - offset);
25
- mask.set(digest.slice(0, toCopy), offset);
26
- offset += toCopy;
27
- counter++;
28
- }
29
- return mask;
30
- }
31
-
32
- //#endregion
33
- export { mgf1 };
1
+ import{hashSize as e}from"./crypto-utils.js";import{Hash as t}from"./hash.js";function n(n,r,i){e(n);let a=new Uint8Array(i),o=0,s=0;for(;o<i;){let e=new Uint8Array(4);e[0]=s>>>24&255,e[1]=s>>>16&255,e[2]=s>>>8&255,e[3]=s&255;let c=new t(n);c.update(r),c.update(e);let l=new Uint8Array(c.digest()),u=Math.min(l.length,i-o);a.set(l.slice(0,u),o),o+=u,s++}return a}export{n as mgf1};
package/lib/esm/pbkdf2.js CHANGED
@@ -1,75 +1 @@
1
- import { DIGEST_SIZES, SUPPORTED_ALGORITHMS, normalizeAlgorithm, toBuffer } from "./crypto-utils.js";
2
- import { Hmac } from "./hmac.js";
3
- import { Buffer } from "node:buffer";
4
-
5
- //#region src/pbkdf2.ts
6
- function hmacDigest(algo, key, data) {
7
- const hmac = new Hmac(algo, key);
8
- hmac.update(data);
9
- return hmac.digest();
10
- }
11
- function validateParameters(iterations, keylen) {
12
- if (typeof iterations !== "number" || iterations < 0 || !Number.isFinite(iterations)) {
13
- throw new TypeError("iterations must be a positive number");
14
- }
15
- if (iterations === 0) {
16
- throw new TypeError("iterations must be a positive number");
17
- }
18
- if (typeof keylen !== "number" || keylen < 0 || !Number.isFinite(keylen) || keylen > 2147483647) {
19
- throw new TypeError("keylen must be a positive number");
20
- }
21
- }
22
- /**
23
- * Synchronous PBKDF2 key derivation.
24
- */
25
- function pbkdf2Sync(password, salt, iterations, keylen, digest) {
26
- validateParameters(iterations, keylen);
27
- const passwordBuf = toBuffer(password);
28
- const saltBuf = toBuffer(salt);
29
- const algo = normalizeAlgorithm(digest || "sha1");
30
- const hashLen = DIGEST_SIZES[algo];
31
- if (!SUPPORTED_ALGORITHMS.has(algo) || hashLen === undefined) {
32
- throw new TypeError(`Unknown message digest: ${digest || "sha1"}`);
33
- }
34
- if (keylen === 0) {
35
- return Buffer.alloc(0);
36
- }
37
- const numBlocks = Math.ceil(keylen / hashLen);
38
- const dk = Buffer.allocUnsafe(numBlocks * hashLen);
39
- for (let blockIndex = 1; blockIndex <= numBlocks; blockIndex++) {
40
- const block = Buffer.allocUnsafe(saltBuf.length + 4);
41
- saltBuf.copy(block, 0);
42
- block.writeUInt32BE(blockIndex, saltBuf.length);
43
- let u = hmacDigest(algo, passwordBuf, block);
44
- let t = Buffer.from(u);
45
- for (let iter = 1; iter < iterations; iter++) {
46
- u = hmacDigest(algo, passwordBuf, u);
47
- for (let k = 0; k < hashLen; k++) {
48
- t[k] ^= u[k];
49
- }
50
- }
51
- t.copy(dk, (blockIndex - 1) * hashLen);
52
- }
53
- return Buffer.from(dk.buffer, dk.byteOffset, keylen);
54
- }
55
- /**
56
- * Asynchronous PBKDF2 key derivation.
57
- */
58
- function pbkdf2(password, salt, iterations, keylen, digest, callback) {
59
- try {
60
- validateParameters(iterations, keylen);
61
- } catch (err) {
62
- throw err;
63
- }
64
- setTimeout(() => {
65
- try {
66
- const result = pbkdf2Sync(password, salt, iterations, keylen, digest);
67
- callback(null, result);
68
- } catch (err) {
69
- callback(err instanceof Error ? err : new Error(String(err)));
70
- }
71
- }, 0);
72
- }
73
-
74
- //#endregion
75
- export { pbkdf2, pbkdf2Sync };
1
+ import{DIGEST_SIZES as e,SUPPORTED_ALGORITHMS as t,normalizeAlgorithm as n,toBuffer as r}from"./crypto-utils.js";import{Hmac as i}from"./hmac.js";import{Buffer as a}from"node:buffer";function o(e,t,n){let r=new i(e,t);return r.update(n),r.digest()}function s(e,t){if(typeof e!=`number`||e<0||!Number.isFinite(e)||e===0)throw TypeError(`iterations must be a positive number`);if(typeof t!=`number`||t<0||!Number.isFinite(t)||t>2147483647)throw TypeError(`keylen must be a positive number`)}function c(i,c,l,u,d){s(l,u);let f=r(i),p=r(c),m=n(d||`sha1`),h=e[m];if(!t.has(m)||h===void 0)throw TypeError(`Unknown message digest: ${d||`sha1`}`);if(u===0)return a.alloc(0);let g=Math.ceil(u/h),_=a.allocUnsafe(g*h);for(let e=1;e<=g;e++){let t=a.allocUnsafe(p.length+4);p.copy(t,0),t.writeUInt32BE(e,p.length);let n=o(m,f,t),r=a.from(n);for(let e=1;e<l;e++){n=o(m,f,n);for(let e=0;e<h;e++)r[e]^=n[e]}r.copy(_,(e-1)*h)}return a.from(_.buffer,_.byteOffset,u)}function l(e,t,n,r,i,a){try{s(n,r)}catch(e){throw e}setTimeout(()=>{try{a(null,c(e,t,n,r,i))}catch(e){a(e instanceof Error?e:Error(String(e)))}},0)}export{l as pbkdf2,c as pbkdf2Sync};