@twin.org/crypto 0.0.1-next.1

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.
Files changed (57) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +31 -0
  3. package/dist/cjs/index.cjs +1572 -0
  4. package/dist/esm/index.mjs +1528 -0
  5. package/dist/types/address/bech32.d.ts +28 -0
  6. package/dist/types/address/bip44.d.ts +53 -0
  7. package/dist/types/ciphers/chaCha20Poly1305.d.ts +24 -0
  8. package/dist/types/curves/ed25519.d.ts +37 -0
  9. package/dist/types/curves/secp256k1.d.ts +37 -0
  10. package/dist/types/curves/x25519.d.ts +18 -0
  11. package/dist/types/curves/zip215.d.ts +15 -0
  12. package/dist/types/hashes/blake2b.d.ts +55 -0
  13. package/dist/types/hashes/hmacSha1.d.ts +28 -0
  14. package/dist/types/hashes/hmacSha256.d.ts +44 -0
  15. package/dist/types/hashes/hmacSha512.d.ts +66 -0
  16. package/dist/types/hashes/pbkdf2.d.ts +23 -0
  17. package/dist/types/hashes/sha1.d.ts +26 -0
  18. package/dist/types/hashes/sha256.d.ts +41 -0
  19. package/dist/types/hashes/sha512.d.ts +61 -0
  20. package/dist/types/index.d.ts +23 -0
  21. package/dist/types/keys/bip32Path.d.ts +40 -0
  22. package/dist/types/keys/bip39.d.ts +36 -0
  23. package/dist/types/keys/slip0010.d.ts +38 -0
  24. package/dist/types/models/keyType.d.ts +17 -0
  25. package/dist/types/otp/hotp.d.ts +14 -0
  26. package/dist/types/otp/totp.d.ts +46 -0
  27. package/dist/types/passwords/passwordGenerator.d.ts +11 -0
  28. package/dist/types/passwords/passwordValidator.d.ts +22 -0
  29. package/docs/changelog.md +5 -0
  30. package/docs/examples.md +1 -0
  31. package/docs/reference/classes/Bech32.md +89 -0
  32. package/docs/reference/classes/Bip32Path.md +117 -0
  33. package/docs/reference/classes/Bip39.md +121 -0
  34. package/docs/reference/classes/Bip44.md +173 -0
  35. package/docs/reference/classes/Blake2b.md +155 -0
  36. package/docs/reference/classes/ChaCha20Poly1305.md +69 -0
  37. package/docs/reference/classes/Ed25519.md +113 -0
  38. package/docs/reference/classes/HmacSha1.md +79 -0
  39. package/docs/reference/classes/HmacSha256.md +123 -0
  40. package/docs/reference/classes/HmacSha512.md +187 -0
  41. package/docs/reference/classes/Hotp.md +39 -0
  42. package/docs/reference/classes/PasswordGenerator.md +33 -0
  43. package/docs/reference/classes/PasswordValidator.md +56 -0
  44. package/docs/reference/classes/Pbkdf2.md +77 -0
  45. package/docs/reference/classes/Secp256k1.md +113 -0
  46. package/docs/reference/classes/Sha1.md +69 -0
  47. package/docs/reference/classes/Sha256.md +111 -0
  48. package/docs/reference/classes/Sha512.md +167 -0
  49. package/docs/reference/classes/Slip0010.md +114 -0
  50. package/docs/reference/classes/Totp.md +148 -0
  51. package/docs/reference/classes/X25519.md +57 -0
  52. package/docs/reference/classes/Zip215.md +43 -0
  53. package/docs/reference/index.md +34 -0
  54. package/docs/reference/type-aliases/KeyType.md +5 -0
  55. package/docs/reference/variables/KeyType.md +19 -0
  56. package/locales/en.json +71 -0
  57. package/package.json +71 -0
@@ -0,0 +1,1572 @@
1
+ 'use strict';
2
+
3
+ var core = require('@twin.org/core');
4
+ var base = require('@scure/base');
5
+ var ed25519 = require('@noble/curves/ed25519');
6
+ var secp256k1 = require('@noble/curves/secp256k1');
7
+ var blake2b = require('@noble/hashes/blake2b');
8
+ var bip32 = require('@scure/bip32');
9
+ var slip10_js = require('micro-key-producer/slip10.js');
10
+ var chacha = require('@noble/ciphers/chacha');
11
+ var hmac = require('@noble/hashes/hmac');
12
+ var sha1 = require('@noble/hashes/sha1');
13
+ var sha256 = require('@noble/hashes/sha256');
14
+ var sha512 = require('@noble/hashes/sha512');
15
+ var pbkdf2 = require('@noble/hashes/pbkdf2');
16
+ var bip39 = require('@scure/bip39');
17
+ var english = require('@scure/bip39/wordlists/english');
18
+ var otp = require('micro-key-producer/otp.js');
19
+
20
+ function _interopNamespaceDefault(e) {
21
+ var n = Object.create(null);
22
+ if (e) {
23
+ Object.keys(e).forEach(function (k) {
24
+ if (k !== 'default') {
25
+ var d = Object.getOwnPropertyDescriptor(e, k);
26
+ Object.defineProperty(n, k, d.get ? d : {
27
+ enumerable: true,
28
+ get: function () { return e[k]; }
29
+ });
30
+ }
31
+ });
32
+ }
33
+ n.default = e;
34
+ return Object.freeze(n);
35
+ }
36
+
37
+ var bip39__namespace = /*#__PURE__*/_interopNamespaceDefault(bip39);
38
+ var otp__namespace = /*#__PURE__*/_interopNamespaceDefault(otp);
39
+
40
+ // Copyright 2024 IOTA Stiftung.
41
+ // SPDX-License-Identifier: Apache-2.0.
42
+ /**
43
+ * Bech32 encoding and decoding.
44
+ */
45
+ class Bech32 {
46
+ /**
47
+ * Runtime name for the class.
48
+ * @internal
49
+ */
50
+ static _CLASS_NAME = "Bech32";
51
+ /**
52
+ * Encode the buffer.
53
+ * @param humanReadablePart The header.
54
+ * @param data The data to encode.
55
+ * @returns The encoded data.
56
+ */
57
+ static encode(humanReadablePart, data) {
58
+ core.Guards.stringValue(Bech32._CLASS_NAME, "humanReadablePart", humanReadablePart);
59
+ core.Guards.uint8Array(Bech32._CLASS_NAME, "data", data);
60
+ return base.bech32.encode(humanReadablePart, base.bech32.toWords(data));
61
+ }
62
+ /**
63
+ * Decode a bech32 string.
64
+ * @param bech The text to decode.
65
+ * @returns The decoded data or undefined if it could not be decoded.
66
+ * @throws An error if the decoding fails.
67
+ */
68
+ static decode(bech) {
69
+ core.Guards.stringValue(Bech32._CLASS_NAME, "bech", bech);
70
+ try {
71
+ const result = base.bech32.decodeToBytes(bech);
72
+ return {
73
+ humanReadablePart: result.prefix,
74
+ data: result.bytes
75
+ };
76
+ }
77
+ catch (err) {
78
+ if (core.BaseError.isErrorMessage(err, /checksum/)) {
79
+ throw new core.GeneralError(Bech32._CLASS_NAME, "invalidChecksum", { bech: base.bech32 });
80
+ }
81
+ else if (core.BaseError.isErrorMessage(err, /between prefix and data only/i)) {
82
+ throw new core.GeneralError(Bech32._CLASS_NAME, "separatorMisused", { bech: base.bech32 });
83
+ }
84
+ else if (core.BaseError.isErrorMessage(err, /lowercase or uppercase/i)) {
85
+ throw new core.GeneralError(Bech32._CLASS_NAME, "lowerUpper", { bech: base.bech32 });
86
+ }
87
+ else if (core.BaseError.isErrorMessage(err, /must be at least/i) ||
88
+ core.BaseError.isErrorMessage(err, /wrong string length/i)) {
89
+ throw new core.GeneralError(Bech32._CLASS_NAME, "dataTooShort", { bech: base.bech32 });
90
+ }
91
+ throw new core.GeneralError(Bech32._CLASS_NAME, "decodeFailed", { bech: base.bech32 }, err);
92
+ }
93
+ }
94
+ /**
95
+ * Is the input a bech 32 address.
96
+ * @param bech The value to test.
97
+ * @returns True if this is potentially a match.
98
+ */
99
+ static isBech32(bech) {
100
+ try {
101
+ if (core.Is.stringValue(bech)) {
102
+ const result = base.bech32.decodeToBytes(bech);
103
+ return (core.Is.stringValue(result.prefix) && core.Is.uint8Array(result.bytes) && result.bytes.length > 0);
104
+ }
105
+ }
106
+ catch { }
107
+ return false;
108
+ }
109
+ }
110
+
111
+ // Copyright 2024 IOTA Stiftung.
112
+ // SPDX-License-Identifier: Apache-2.0.
113
+ /**
114
+ * Implementation of Ed25519.
115
+ */
116
+ class Ed25519 {
117
+ /**
118
+ * Private Key Size is the size, in bytes, of private keys as used in this package.
119
+ */
120
+ static PRIVATE_KEY_SIZE = 32;
121
+ /**
122
+ * Public Key Size is the size, in bytes, of public keys as used in this package.
123
+ */
124
+ static PUBLIC_KEY_SIZE = 32;
125
+ /**
126
+ * Runtime name for the class.
127
+ * @internal
128
+ */
129
+ static _CLASS_NAME = "Ed25519";
130
+ /**
131
+ * Public returns the PublicKey corresponding to private.
132
+ * @param privateKey The private key to get the corresponding public key.
133
+ * @returns The public key.
134
+ * @throws Error if the private key is not the correct length.
135
+ */
136
+ static publicKeyFromPrivateKey(privateKey) {
137
+ core.Guards.uint8Array(Ed25519._CLASS_NAME, "privateKey", privateKey);
138
+ if (privateKey.length !== Ed25519.PRIVATE_KEY_SIZE) {
139
+ throw new core.GeneralError(Ed25519._CLASS_NAME, "privateKeyLength", {
140
+ requiredSize: Ed25519.PRIVATE_KEY_SIZE,
141
+ actualSize: privateKey.length
142
+ });
143
+ }
144
+ return ed25519.ed25519.getPublicKey(privateKey);
145
+ }
146
+ /**
147
+ * Sign the block with privateKey and returns a signature.
148
+ * @param privateKey The private key.
149
+ * @param block The block to sign.
150
+ * @returns The signature.
151
+ * @throws Error if the private key is not the correct length.
152
+ */
153
+ static sign(privateKey, block) {
154
+ core.Guards.uint8Array(Ed25519._CLASS_NAME, "privateKey", privateKey);
155
+ core.Guards.uint8Array(Ed25519._CLASS_NAME, "block", block);
156
+ if (privateKey.length !== Ed25519.PRIVATE_KEY_SIZE) {
157
+ throw new core.GeneralError(Ed25519._CLASS_NAME, "privateKeyLength", {
158
+ requiredSize: Ed25519.PRIVATE_KEY_SIZE,
159
+ actualSize: privateKey ? privateKey.length : 0
160
+ });
161
+ }
162
+ return ed25519.ed25519.sign(block, privateKey);
163
+ }
164
+ /**
165
+ * Verify reports whether sig is a valid signature of block by publicKey.
166
+ * @param publicKey The public key to verify the signature.
167
+ * @param block The block for the signature.
168
+ * @param signature The signature.
169
+ * @returns True if the signature matches.
170
+ * @throws Error if the public key is not the correct length.
171
+ */
172
+ static verify(publicKey, block, signature) {
173
+ core.Guards.uint8Array(Ed25519._CLASS_NAME, "publicKey", publicKey);
174
+ core.Guards.uint8Array(Ed25519._CLASS_NAME, "block", block);
175
+ core.Guards.uint8Array(Ed25519._CLASS_NAME, "signature", signature);
176
+ if (publicKey.length !== Ed25519.PUBLIC_KEY_SIZE) {
177
+ throw new core.GeneralError(Ed25519._CLASS_NAME, "publicKeyLength", {
178
+ requiredSize: Ed25519.PUBLIC_KEY_SIZE,
179
+ actualSize: publicKey ? publicKey.length : 0
180
+ });
181
+ }
182
+ try {
183
+ return ed25519.ed25519.verify(signature, block, publicKey);
184
+ }
185
+ catch {
186
+ return false;
187
+ }
188
+ }
189
+ }
190
+
191
+ // Copyright 2024 IOTA Stiftung.
192
+ // SPDX-License-Identifier: Apache-2.0.
193
+ /**
194
+ * Implementation of secp256k1.
195
+ */
196
+ class Secp256k1 {
197
+ /**
198
+ * Private Key Size is the size, in bytes, of private keys as used in this package.
199
+ */
200
+ static PRIVATE_KEY_SIZE = 32;
201
+ /**
202
+ * Public Key Size is the size, in bytes, of public keys as used in this package.
203
+ */
204
+ static PUBLIC_KEY_SIZE = 33;
205
+ /**
206
+ * Runtime name for the class.
207
+ * @internal
208
+ */
209
+ static _CLASS_NAME = "Secp256k1";
210
+ /**
211
+ * Public returns the PublicKey corresponding to private.
212
+ * @param privateKey The private key to get the corresponding public key.
213
+ * @returns The public key.
214
+ * @throws Error if the private key is not the correct length.
215
+ */
216
+ static publicKeyFromPrivateKey(privateKey) {
217
+ core.Guards.uint8Array(Secp256k1._CLASS_NAME, "privateKey", privateKey);
218
+ if (privateKey.length !== Secp256k1.PRIVATE_KEY_SIZE) {
219
+ throw new core.GeneralError(Secp256k1._CLASS_NAME, "privateKeyLength", {
220
+ requiredSize: Secp256k1.PRIVATE_KEY_SIZE,
221
+ actualSize: privateKey.length
222
+ });
223
+ }
224
+ return secp256k1.secp256k1.getPublicKey(privateKey);
225
+ }
226
+ /**
227
+ * Sign the block with privateKey and returns a signature.
228
+ * @param privateKey The private key.
229
+ * @param block The block to sign.
230
+ * @returns The signature.
231
+ * @throws Error if the private key is not the correct length.
232
+ */
233
+ static sign(privateKey, block) {
234
+ core.Guards.uint8Array(Secp256k1._CLASS_NAME, "privateKey", privateKey);
235
+ core.Guards.uint8Array(Secp256k1._CLASS_NAME, "block", block);
236
+ if (privateKey.length !== Secp256k1.PRIVATE_KEY_SIZE) {
237
+ throw new core.GeneralError(Secp256k1._CLASS_NAME, "privateKeyLength", {
238
+ requiredSize: Secp256k1.PRIVATE_KEY_SIZE,
239
+ actualSize: privateKey ? privateKey.length : 0
240
+ });
241
+ }
242
+ const res = secp256k1.secp256k1.sign(block, privateKey);
243
+ return res.toCompactRawBytes();
244
+ }
245
+ /**
246
+ * Verify reports whether sig is a valid signature of block by publicKey.
247
+ * @param publicKey The public key to verify the signature.
248
+ * @param block The block for the signature.
249
+ * @param signature The signature.
250
+ * @returns True if the signature matches.
251
+ * @throws Error if the public key is not the correct length.
252
+ */
253
+ static verify(publicKey, block, signature) {
254
+ core.Guards.uint8Array(Secp256k1._CLASS_NAME, "publicKey", publicKey);
255
+ core.Guards.uint8Array(Secp256k1._CLASS_NAME, "block", block);
256
+ core.Guards.uint8Array(Secp256k1._CLASS_NAME, "signature", signature);
257
+ if (publicKey.length !== Secp256k1.PUBLIC_KEY_SIZE) {
258
+ throw new core.GeneralError(Secp256k1._CLASS_NAME, "publicKeyLength", {
259
+ requiredSize: Secp256k1.PUBLIC_KEY_SIZE,
260
+ actualSize: publicKey ? publicKey.length : 0
261
+ });
262
+ }
263
+ try {
264
+ return secp256k1.secp256k1.verify(signature, block, publicKey);
265
+ }
266
+ catch {
267
+ return false;
268
+ }
269
+ }
270
+ }
271
+
272
+ // Copyright 2024 IOTA Stiftung.
273
+ // SPDX-License-Identifier: Apache-2.0.
274
+ /**
275
+ * Class to help with Blake2B Signature scheme.
276
+ */
277
+ class Blake2b {
278
+ /**
279
+ * Blake2b 160.
280
+ */
281
+ static SIZE_160 = 20;
282
+ /**
283
+ * Blake2b 256.
284
+ */
285
+ static SIZE_256 = 32;
286
+ /**
287
+ * Blake2b 512.
288
+ */
289
+ static SIZE_512 = 64;
290
+ /**
291
+ * Runtime name for the class.
292
+ * @internal
293
+ */
294
+ static _CLASS_NAME = "Blake2b";
295
+ /**
296
+ * The instance of the hash.
297
+ * @internal
298
+ */
299
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
300
+ _instance;
301
+ /**
302
+ * Create a new instance of Blake2b.
303
+ * @param outputLength The output length.
304
+ * @param key Optional key for the hash.
305
+ */
306
+ constructor(outputLength, key) {
307
+ this._instance = blake2b.blake2b.create({
308
+ dkLen: outputLength,
309
+ key
310
+ });
311
+ }
312
+ /**
313
+ * Perform Sum 160 on the block.
314
+ * @param block The block to operate on.
315
+ * @param key Optional key for the hash.
316
+ * @returns The sum 160 of the block.
317
+ */
318
+ static sum160(block, key) {
319
+ core.Guards.uint8Array(Blake2b._CLASS_NAME, "block", block);
320
+ return new Blake2b(Blake2b.SIZE_160, key).update(block).digest();
321
+ }
322
+ /**
323
+ * Perform Sum 256 on the block.
324
+ * @param block The block to operate on.
325
+ * @param key Optional key for the hash.
326
+ * @returns The sum 256 of the block.
327
+ */
328
+ static sum256(block, key) {
329
+ core.Guards.uint8Array(Blake2b._CLASS_NAME, "block", block);
330
+ return new Blake2b(Blake2b.SIZE_256, key).update(block).digest();
331
+ }
332
+ /**
333
+ * Perform Sum 512 on the block.
334
+ * @param block The block to operate on.
335
+ * @param key Optional key for the hash.
336
+ * @returns The sum 512 of the block.
337
+ */
338
+ static sum512(block, key) {
339
+ core.Guards.uint8Array(Blake2b._CLASS_NAME, "block", block);
340
+ return new Blake2b(Blake2b.SIZE_512, key).update(block).digest();
341
+ }
342
+ /**
343
+ * Update the hash with the block.
344
+ * @param block The block to update the hash with.
345
+ * @returns The instance for chaining.
346
+ */
347
+ update(block) {
348
+ core.Guards.uint8Array(Blake2b._CLASS_NAME, "block", block);
349
+ this._instance.update(block);
350
+ return this;
351
+ }
352
+ /**
353
+ * Get the digest for the hash.
354
+ * @returns The instance for chaining.
355
+ */
356
+ digest() {
357
+ return this._instance.digest();
358
+ }
359
+ }
360
+
361
+ // Copyright 2024 IOTA Stiftung.
362
+ // SPDX-License-Identifier: Apache-2.0.
363
+ /**
364
+ * Class to help with bip32 paths.
365
+ */
366
+ class Bip32Path {
367
+ /**
368
+ * The path.
369
+ * @internal
370
+ */
371
+ _path;
372
+ /**
373
+ * Create a new instance of Bip32Path.
374
+ * @param initialPath Initial path to create.
375
+ */
376
+ constructor(initialPath) {
377
+ if (initialPath) {
378
+ this._path = initialPath.split("/");
379
+ if (this._path[0] === "m") {
380
+ this._path.shift();
381
+ }
382
+ }
383
+ else {
384
+ this._path = [];
385
+ }
386
+ }
387
+ /**
388
+ * Construct a new path by cloning an existing one.
389
+ * @param bip32Path The path to clone.
390
+ * @returns A new instance of Bip32Path.
391
+ */
392
+ static fromPath(bip32Path) {
393
+ const p = new Bip32Path();
394
+ p._path = bip32Path._path.slice();
395
+ return p;
396
+ }
397
+ /**
398
+ * Converts the path to a string.
399
+ * @returns The path as a string.
400
+ */
401
+ toString() {
402
+ return this._path.length > 0 ? `m/${this._path.join("/")}` : "m";
403
+ }
404
+ /**
405
+ * Push a new index on to the path.
406
+ * @param index The index to add to the path.
407
+ */
408
+ push(index) {
409
+ this._path.push(`${index}`);
410
+ }
411
+ /**
412
+ * Push a new hardened index on to the path.
413
+ * @param index The index to add to the path.
414
+ */
415
+ pushHardened(index) {
416
+ this._path.push(`${index}'`);
417
+ }
418
+ /**
419
+ * Pop an index from the path.
420
+ */
421
+ pop() {
422
+ this._path.pop();
423
+ }
424
+ /**
425
+ * Get the segments.
426
+ * @returns The segments as numbers.
427
+ */
428
+ numberSegments() {
429
+ return this._path.map(p => Number.parseInt(p, 10));
430
+ }
431
+ }
432
+
433
+ // Copyright 2024 IOTA Stiftung.
434
+ // SPDX-License-Identifier: Apache-2.0.
435
+ /**
436
+ * The names of the key types.
437
+ */
438
+ // eslint-disable-next-line @typescript-eslint/naming-convention
439
+ const KeyType = {
440
+ /**
441
+ * Ed25519.
442
+ */
443
+ Ed25519: 0,
444
+ /**
445
+ * Secp256k1.
446
+ */
447
+ Secp256k1: 1
448
+ };
449
+
450
+ // Copyright 2024 IOTA Stiftung.
451
+ // SPDX-License-Identifier: Apache-2.0.
452
+ /* eslint-disable no-bitwise */
453
+ /**
454
+ * Class to help with slip0010 key derivation
455
+ * https://github.com/satoshilabs/slips/blob/master/slip-0010.md.
456
+ */
457
+ class Slip0010 {
458
+ /**
459
+ * Runtime name for the class.
460
+ * @internal
461
+ */
462
+ static _CLASS_NAME = "Slip0010";
463
+ /**
464
+ * Get the master key from the seed.
465
+ * @param seed The seed to generate the master key from.
466
+ * @param keyType The key type.
467
+ * @returns The key and chain code.
468
+ * @throws If the seed is invalid.
469
+ */
470
+ static getMasterKeyFromSeed(seed, keyType = KeyType.Ed25519) {
471
+ try {
472
+ const masterKey = keyType === KeyType.Ed25519
473
+ ? slip10_js.HDKey.fromMasterSeed(seed)
474
+ : bip32.HDKey.fromMasterSeed(seed);
475
+ return {
476
+ privateKey: masterKey.privateKey ?? new Uint8Array(),
477
+ chainCode: masterKey.chainCode ?? new Uint8Array()
478
+ };
479
+ }
480
+ catch (error) {
481
+ throw new core.GeneralError(Slip0010._CLASS_NAME, "invalidSeed", { seed: core.Converter.bytesToUtf8(seed) }, error);
482
+ }
483
+ }
484
+ /**
485
+ * Derive a key from the path.
486
+ * @param seed The seed.
487
+ * @param path The path.
488
+ * @param keyType The key type.
489
+ * @returns The key and chain code.
490
+ */
491
+ static derivePath(seed, path, keyType = KeyType.Ed25519) {
492
+ const keyOpts = Slip0010.getMasterKeyFromSeed(seed, keyType);
493
+ if (keyType === KeyType.Ed25519) {
494
+ const hdKey = new slip10_js.HDKey(keyOpts);
495
+ const derivedKey = hdKey.derive(path.toString());
496
+ return {
497
+ privateKey: derivedKey.privateKey,
498
+ chainCode: derivedKey.chainCode
499
+ };
500
+ }
501
+ const hdKey = new bip32.HDKey(keyOpts);
502
+ const derivedKey = hdKey.derive(path.toString());
503
+ return {
504
+ privateKey: derivedKey.privateKey ?? new Uint8Array(),
505
+ chainCode: derivedKey.chainCode ?? new Uint8Array()
506
+ };
507
+ }
508
+ /**
509
+ * Get the public key from the private key.
510
+ * @param privateKey The private key.
511
+ * @param keyType The key type.
512
+ * @param withZeroByte Include a zero bute prefix.
513
+ * @returns The public key.
514
+ */
515
+ static getPublicKey(privateKey, keyType = KeyType.Ed25519, withZeroByte = true) {
516
+ const signPk = keyType === KeyType.Ed25519
517
+ ? Ed25519.publicKeyFromPrivateKey(privateKey)
518
+ : Secp256k1.publicKeyFromPrivateKey(privateKey);
519
+ if (withZeroByte) {
520
+ const arr = new Uint8Array(1 + signPk.length);
521
+ arr[0] = 0;
522
+ arr.set(signPk, 1);
523
+ return arr;
524
+ }
525
+ return signPk;
526
+ }
527
+ }
528
+
529
+ // Copyright 2024 IOTA Stiftung.
530
+ // SPDX-License-Identifier: Apache-2.0.
531
+ /**
532
+ * Implementation of Bip44 for address generation.
533
+ */
534
+ class Bip44 {
535
+ /**
536
+ * Runtime name for the class.
537
+ * @internal
538
+ */
539
+ static _CLASS_NAME = "Bip44";
540
+ /**
541
+ * Generate a bip44 key pair from the seed and parts.
542
+ * @param seed The account seed.
543
+ * @param keyType The key type.
544
+ * @param coinType The coin type.
545
+ * @param accountIndex The account index.
546
+ * @param isInternal Is this an internal address.
547
+ * @param addressIndex The address index.
548
+ * @returns The key pair.
549
+ * @throws Error if the address type is not supported.
550
+ */
551
+ static keyPair(seed, keyType, coinType, accountIndex, isInternal, addressIndex) {
552
+ const bip44Path = Bip44.path(coinType, accountIndex, isInternal, addressIndex);
553
+ const keys = Slip0010.derivePath(seed, bip44Path);
554
+ if (keyType === KeyType.Ed25519) {
555
+ const publicKey = Ed25519.publicKeyFromPrivateKey(keys.privateKey);
556
+ return {
557
+ privateKey: keys.privateKey,
558
+ publicKey
559
+ };
560
+ }
561
+ else if (keyType === KeyType.Secp256k1) {
562
+ const publicKey = Secp256k1.publicKeyFromPrivateKey(keys.privateKey);
563
+ return {
564
+ privateKey: keys.privateKey,
565
+ publicKey
566
+ };
567
+ }
568
+ throw new core.GeneralError(Bip44._CLASS_NAME, "unsupportedKeyType", { keyType });
569
+ }
570
+ /**
571
+ * Generate a bip44 path based on all its parts.
572
+ * @param coinType The coin type.
573
+ * @param accountIndex The account index.
574
+ * @param isInternal Is this an internal address.
575
+ * @param addressIndex The address index.
576
+ * @returns The generated path.
577
+ */
578
+ static path(coinType, accountIndex, isInternal, addressIndex) {
579
+ const bip32Path = new Bip32Path(Bip44.basePath(coinType));
580
+ bip32Path.pushHardened(accountIndex);
581
+ bip32Path.pushHardened(isInternal ? 1 : 0);
582
+ bip32Path.pushHardened(addressIndex);
583
+ return bip32Path;
584
+ }
585
+ /**
586
+ * Create a bip44 base path for the provided coin type.
587
+ * @param coinType The coin type.
588
+ * @returns The bip44 address base path.
589
+ */
590
+ static basePath(coinType) {
591
+ return `m/44'/${coinType}'`;
592
+ }
593
+ /**
594
+ * Generate a bech32 address from the seed and parts.
595
+ * @param seed The account seed.
596
+ * @param keyType The key type.
597
+ * @param hrp The human readable part of the address.
598
+ * @param coinType The coin type.
599
+ * @param accountIndex The account index.
600
+ * @param isInternal Is this an internal address.
601
+ * @param addressIndex The address index.
602
+ * @returns The generated path and the associated keypair.
603
+ */
604
+ static addressBech32(seed, keyType, hrp, coinType, accountIndex, isInternal, addressIndex) {
605
+ const keyPair = Bip44.keyPair(seed, keyType, coinType, accountIndex, isInternal, addressIndex);
606
+ const addressData = Blake2b.sum256(keyPair.publicKey);
607
+ const bech32Data = new Uint8Array(1 + addressData.length);
608
+ bech32Data[0] = keyType;
609
+ bech32Data.set(addressData, 1);
610
+ return {
611
+ address: Bech32.encode(hrp, bech32Data),
612
+ ...keyPair
613
+ };
614
+ }
615
+ }
616
+
617
+ // Copyright 2024 IOTA Stiftung.
618
+ // SPDX-License-Identifier: Apache-2.0.
619
+ /**
620
+ * Implementation of the ChaCha20Poly1305 cipher.
621
+ */
622
+ class ChaCha20Poly1305 {
623
+ /**
624
+ * Runtime name for the class.
625
+ * @internal
626
+ */
627
+ static _CLASS_NAME = "ChaCha20Poly1305";
628
+ /**
629
+ * The cipher instance.
630
+ * @internal
631
+ */
632
+ _instance;
633
+ /**
634
+ * Create a new instance of ChaCha20Poly1305.
635
+ * @param key The key.
636
+ * @param nonce The nonce.
637
+ * @param aad The additional authenticated data.
638
+ */
639
+ constructor(key, nonce, aad) {
640
+ core.Guards.uint8Array(ChaCha20Poly1305._CLASS_NAME, "key", key);
641
+ core.Guards.uint8Array(ChaCha20Poly1305._CLASS_NAME, "nonce", nonce);
642
+ this._instance = chacha.chacha20poly1305(key, nonce, aad);
643
+ }
644
+ /**
645
+ * Encrypt the block.
646
+ * @param block The block to encrypt.
647
+ * @returns The block encrypted.
648
+ */
649
+ encrypt(block) {
650
+ core.Guards.uint8Array(ChaCha20Poly1305._CLASS_NAME, "block", block);
651
+ return this._instance.encrypt(block);
652
+ }
653
+ /**
654
+ * Decrypt the block.
655
+ * @param block The block to decrypt.
656
+ * @returns The block decrypted.
657
+ */
658
+ decrypt(block) {
659
+ core.Guards.uint8Array(ChaCha20Poly1305._CLASS_NAME, "block", block);
660
+ return this._instance.decrypt(block);
661
+ }
662
+ }
663
+
664
+ // Copyright 2024 IOTA Stiftung.
665
+ // SPDX-License-Identifier: Apache-2.0.
666
+ /**
667
+ * This is a TypeScript port of https://github.com/katzenpost/core/blob/master/crypto/extra25519/extra25519.go.
668
+ */
669
+ /**
670
+ * Implementation of X25519.
671
+ */
672
+ class X25519 {
673
+ /**
674
+ * Runtime name for the class.
675
+ * @internal
676
+ */
677
+ static _CLASS_NAME = "X25519";
678
+ /**
679
+ * Convert Ed25519 private key to X25519 private key.
680
+ * @param ed25519PrivateKey The ed25519 private key to convert.
681
+ * @returns The x25519 private key.
682
+ */
683
+ static convertPrivateKeyToX25519(ed25519PrivateKey) {
684
+ core.Guards.uint8Array(X25519._CLASS_NAME, "ed25519PrivateKey", ed25519PrivateKey);
685
+ return ed25519.edwardsToMontgomeryPriv(ed25519PrivateKey);
686
+ }
687
+ /**
688
+ * Convert Ed25519 public key to X25519 public key.
689
+ * @param ed25519PublicKey The ed25519 public key to convert.
690
+ * @returns The x25519 public key.
691
+ * @throws GeneralError On invalid public key.
692
+ */
693
+ static convertPublicKeyToX25519(ed25519PublicKey) {
694
+ core.Guards.uint8Array(X25519._CLASS_NAME, "ed25519PublicKey", ed25519PublicKey);
695
+ return ed25519.edwardsToMontgomeryPub(ed25519PublicKey);
696
+ }
697
+ }
698
+
699
+ // Copyright 2024 IOTA Stiftung.
700
+ // SPDX-License-Identifier: Apache-2.0.
701
+ /**
702
+ * Implementation of Zip215.
703
+ */
704
+ class Zip215 {
705
+ /**
706
+ * Runtime name for the class.
707
+ * @internal
708
+ */
709
+ static _CLASS_NAME = "Zip215";
710
+ /**
711
+ * Verify reports whether sig is a valid signature of block by
712
+ * publicKey, using precisely-specified validation criteria (ZIP 215) suitable
713
+ * for use in consensus-critical contexts.
714
+ * @param publicKey The public key for the block.
715
+ * @param block The block content to validate.
716
+ * @param sig The signature to verify.
717
+ * @returns True if the signature is valid.
718
+ */
719
+ static verify(publicKey, block, sig) {
720
+ core.Guards.uint8Array(Zip215._CLASS_NAME, "publicKey", publicKey);
721
+ core.Guards.uint8Array(Zip215._CLASS_NAME, "block", block);
722
+ core.Guards.uint8Array(Zip215._CLASS_NAME, "sig", sig);
723
+ if (publicKey.length !== Ed25519.PUBLIC_KEY_SIZE) {
724
+ return false;
725
+ }
726
+ return ed25519.ed25519.verify(sig, block, publicKey, { zip215: true });
727
+ }
728
+ }
729
+
730
+ // Copyright 2024 IOTA Stiftung.
731
+ // SPDX-License-Identifier: Apache-2.0.
732
+ /**
733
+ * Class to help with HmacSha1 scheme.
734
+ */
735
+ class HmacSha1 {
736
+ /**
737
+ * Runtime name for the class.
738
+ * @internal
739
+ */
740
+ static _CLASS_NAME = "HmacSha1";
741
+ /**
742
+ * The instance of the hash.
743
+ * @internal
744
+ */
745
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
746
+ _instance;
747
+ /**
748
+ * Create a new instance of HmacSha1.
749
+ * @param key The key for the hmac.
750
+ */
751
+ constructor(key) {
752
+ this._instance = hmac.hmac.create(sha1.sha1, key);
753
+ }
754
+ /**
755
+ * Perform Sum on the block.
756
+ * @param key The key for the hmac.
757
+ * @param block The block to operate on.
758
+ * @returns The sum of the block.
759
+ */
760
+ static sum(key, block) {
761
+ core.Guards.uint8Array(HmacSha1._CLASS_NAME, "key", key);
762
+ core.Guards.uint8Array(HmacSha1._CLASS_NAME, "block", block);
763
+ return new HmacSha1(key).update(block).digest();
764
+ }
765
+ /**
766
+ * Update the hash with the block.
767
+ * @param block The block to update the hash with.
768
+ * @returns The instance for chaining.
769
+ */
770
+ update(block) {
771
+ core.Guards.uint8Array(HmacSha1._CLASS_NAME, "block", block);
772
+ this._instance.update(block);
773
+ return this;
774
+ }
775
+ /**
776
+ * Get the digest for the hash.
777
+ * @returns The instance for chaining.
778
+ */
779
+ digest() {
780
+ return this._instance.digest();
781
+ }
782
+ }
783
+
784
+ // Copyright 2024 IOTA Stiftung.
785
+ // SPDX-License-Identifier: Apache-2.0.
786
+ /**
787
+ * Class to help with HmacSha256 scheme.
788
+ */
789
+ class HmacSha256 {
790
+ /**
791
+ * Sha256 256.
792
+ */
793
+ static SIZE_256 = 256;
794
+ /**
795
+ * Sha256 224.
796
+ */
797
+ static SIZE_224 = 224;
798
+ /**
799
+ * Runtime name for the class.
800
+ * @internal
801
+ */
802
+ static _CLASS_NAME = "HmacSha256";
803
+ /**
804
+ * The instance of the hash.
805
+ * @internal
806
+ */
807
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
808
+ _instance;
809
+ /**
810
+ * Create a new instance of HmacSha256.
811
+ * @param key The key for the hmac.
812
+ * @param bits The number of bits.
813
+ */
814
+ constructor(key, bits = HmacSha256.SIZE_256) {
815
+ if (bits !== HmacSha256.SIZE_224 && bits !== HmacSha256.SIZE_256) {
816
+ throw new core.GeneralError(HmacSha256._CLASS_NAME, "bitSize", { bitSize: bits });
817
+ }
818
+ this._instance = hmac.hmac.create(bits === HmacSha256.SIZE_256 ? sha256.sha256 : sha256.sha224, key);
819
+ }
820
+ /**
821
+ * Perform Sum 224 on the block.
822
+ * @param key The key for the hmac.
823
+ * @param block The block to operate on.
824
+ * @returns The sum 224 of the block.
825
+ */
826
+ static sum224(key, block) {
827
+ core.Guards.uint8Array(HmacSha256._CLASS_NAME, "key", key);
828
+ core.Guards.uint8Array(HmacSha256._CLASS_NAME, "block", block);
829
+ const instance = new HmacSha256(key, HmacSha256.SIZE_224);
830
+ instance.update(block);
831
+ return instance.digest();
832
+ }
833
+ /**
834
+ * Perform Sum 256 on the block.
835
+ * @param key The key for the hmac.
836
+ * @param block The block to operate on.
837
+ * @returns The sum 256 of the block.
838
+ */
839
+ static sum256(key, block) {
840
+ core.Guards.uint8Array(HmacSha256._CLASS_NAME, "key", key);
841
+ core.Guards.uint8Array(HmacSha256._CLASS_NAME, "block", block);
842
+ const instance = new HmacSha256(key, HmacSha256.SIZE_256);
843
+ instance.update(block);
844
+ return instance.digest();
845
+ }
846
+ /**
847
+ * Update the hash with the block.
848
+ * @param block The block to update the hash with.
849
+ * @returns The instance for chaining.
850
+ */
851
+ update(block) {
852
+ core.Guards.uint8Array(HmacSha256._CLASS_NAME, "block", block);
853
+ this._instance.update(block);
854
+ return this;
855
+ }
856
+ /**
857
+ * Get the digest for the hash.
858
+ * @returns The instance for chaining.
859
+ */
860
+ digest() {
861
+ return this._instance.digest();
862
+ }
863
+ }
864
+
865
+ // Copyright 2024 IOTA Stiftung.
866
+ // SPDX-License-Identifier: Apache-2.0.
867
+ /* eslint-disable camelcase */
868
+ /**
869
+ * Class to help with HmacSha512 scheme.
870
+ */
871
+ class HmacSha512 {
872
+ /**
873
+ * Sha512 224.
874
+ */
875
+ static SIZE_224 = 224;
876
+ /**
877
+ * Sha512 256.
878
+ */
879
+ static SIZE_256 = 256;
880
+ /**
881
+ * Sha512 384.
882
+ */
883
+ static SIZE_384 = 384;
884
+ /**
885
+ * Sha512 512.
886
+ */
887
+ static SIZE_512 = 512;
888
+ /**
889
+ * Runtime name for the class.
890
+ * @internal
891
+ */
892
+ static _CLASS_NAME = "HmacSha512";
893
+ /**
894
+ * The instance of the hash.
895
+ * @internal
896
+ */
897
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
898
+ _instance;
899
+ /**
900
+ * Create a new instance of HmacSha512.
901
+ * @param key The key for the hmac.
902
+ * @param bits The number of bits.
903
+ */
904
+ constructor(key, bits = HmacSha512.SIZE_512) {
905
+ if (bits !== HmacSha512.SIZE_224 &&
906
+ bits !== HmacSha512.SIZE_256 &&
907
+ bits !== HmacSha512.SIZE_384 &&
908
+ bits !== HmacSha512.SIZE_512) {
909
+ throw new core.GeneralError(HmacSha512._CLASS_NAME, "bitSize", { bitSize: bits });
910
+ }
911
+ if (bits === HmacSha512.SIZE_224) {
912
+ this._instance = hmac.hmac.create(sha512.sha512_224, key);
913
+ }
914
+ else if (bits === HmacSha512.SIZE_256) {
915
+ this._instance = hmac.hmac.create(sha512.sha512_256, key);
916
+ }
917
+ else if (bits === HmacSha512.SIZE_384) {
918
+ this._instance = hmac.hmac.create(sha512.sha384, key);
919
+ }
920
+ else {
921
+ this._instance = hmac.hmac.create(sha512.sha512, key);
922
+ }
923
+ }
924
+ /**
925
+ * Perform Sum 512 on the block.
926
+ * @param key The key for the hmac.
927
+ * @param block The block to operate on.
928
+ * @returns The sum 512 of the block.
929
+ */
930
+ static sum512(key, block) {
931
+ core.Guards.uint8Array(HmacSha512._CLASS_NAME, "key", key);
932
+ core.Guards.uint8Array(HmacSha512._CLASS_NAME, "block", block);
933
+ const instance = new HmacSha512(key, HmacSha512.SIZE_512);
934
+ instance.update(block);
935
+ return instance.digest();
936
+ }
937
+ /**
938
+ * Perform Sum 384 on the block.
939
+ * @param key The key for the hmac.
940
+ * @param block The block to operate on.
941
+ * @returns The sum 384 of the block.
942
+ */
943
+ static sum384(key, block) {
944
+ core.Guards.uint8Array(HmacSha512._CLASS_NAME, "key", key);
945
+ core.Guards.uint8Array(HmacSha512._CLASS_NAME, "block", block);
946
+ const instance = new HmacSha512(key, HmacSha512.SIZE_384);
947
+ instance.update(block);
948
+ return instance.digest();
949
+ }
950
+ /**
951
+ * Perform Sum 256 on the block.
952
+ * @param key The key for the hmac.
953
+ * @param block The block to operate on.
954
+ * @returns The sum 256 of the block.
955
+ */
956
+ static sum256(key, block) {
957
+ core.Guards.uint8Array(HmacSha512._CLASS_NAME, "key", key);
958
+ core.Guards.uint8Array(HmacSha512._CLASS_NAME, "block", block);
959
+ const instance = new HmacSha512(key, HmacSha512.SIZE_256);
960
+ instance.update(block);
961
+ return instance.digest();
962
+ }
963
+ /**
964
+ * Perform Sum 224 on the block.
965
+ * @param key The key for the hmac.
966
+ * @param block The block to operate on.
967
+ * @returns The sum 224 of the block.
968
+ */
969
+ static sum224(key, block) {
970
+ core.Guards.uint8Array(HmacSha512._CLASS_NAME, "key", key);
971
+ core.Guards.uint8Array(HmacSha512._CLASS_NAME, "block", block);
972
+ const instance = new HmacSha512(key, HmacSha512.SIZE_224);
973
+ instance.update(block);
974
+ return instance.digest();
975
+ }
976
+ /**
977
+ * Update the hash with the block.
978
+ * @param block The block to update the hash with.
979
+ * @returns The instance for chaining.
980
+ */
981
+ update(block) {
982
+ core.Guards.uint8Array(HmacSha512._CLASS_NAME, "block", block);
983
+ this._instance.update(block);
984
+ return this;
985
+ }
986
+ /**
987
+ * Get the digest for the hash.
988
+ * @returns The instance for chaining.
989
+ */
990
+ digest() {
991
+ return this._instance.digest();
992
+ }
993
+ }
994
+
995
+ // Copyright 2024 IOTA Stiftung.
996
+ // SPDX-License-Identifier: Apache-2.0.
997
+ /**
998
+ * Implementation of the password based key derivation function 2.
999
+ */
1000
+ class Pbkdf2 {
1001
+ /**
1002
+ * Runtime name for the class.
1003
+ * @internal
1004
+ */
1005
+ static _CLASS_NAME = "Pbkdf2";
1006
+ /**
1007
+ * Derive a key from the parameters using Sha256.
1008
+ * @param password The password to derive the key from.
1009
+ * @param salt The salt for the derivation.
1010
+ * @param iterations Number of iterations to perform.
1011
+ * @param keyLength The length of the key to derive.
1012
+ * @returns The derived key.
1013
+ */
1014
+ static sha256(password, salt, iterations, keyLength) {
1015
+ core.Guards.uint8Array(Pbkdf2._CLASS_NAME, "password", password);
1016
+ core.Guards.uint8Array(Pbkdf2._CLASS_NAME, "salt", salt);
1017
+ core.Guards.number(Pbkdf2._CLASS_NAME, "iterations", iterations);
1018
+ core.Guards.number(Pbkdf2._CLASS_NAME, "keyLength", keyLength);
1019
+ return pbkdf2.pbkdf2(sha256.sha256, password, salt, { c: iterations, dkLen: keyLength });
1020
+ }
1021
+ /**
1022
+ * Derive a key from the parameters using Sha512.
1023
+ * @param password The password to derive the key from.
1024
+ * @param salt The salt for the derivation.
1025
+ * @param iterations Number of iterations to perform.
1026
+ * @param keyLength The length of the key to derive.
1027
+ * @returns The derived key.
1028
+ */
1029
+ static sha512(password, salt, iterations, keyLength) {
1030
+ core.Guards.uint8Array(Pbkdf2._CLASS_NAME, "password", password);
1031
+ core.Guards.uint8Array(Pbkdf2._CLASS_NAME, "salt", salt);
1032
+ core.Guards.number(Pbkdf2._CLASS_NAME, "iterations", iterations);
1033
+ core.Guards.number(Pbkdf2._CLASS_NAME, "keyLength", keyLength);
1034
+ return pbkdf2.pbkdf2(sha512.sha512, password, salt, { c: iterations, dkLen: keyLength });
1035
+ }
1036
+ }
1037
+
1038
+ // Copyright 2024 IOTA Stiftung.
1039
+ // SPDX-License-Identifier: Apache-2.0.
1040
+ /**
1041
+ * Perform a SHA-1 hash on the block.
1042
+ */
1043
+ class Sha1 {
1044
+ /**
1045
+ * Runtime name for the class.
1046
+ * @internal
1047
+ */
1048
+ static _CLASS_NAME = "Sha1";
1049
+ /**
1050
+ * The instance of the hash.
1051
+ * @internal
1052
+ */
1053
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1054
+ _instance;
1055
+ /**
1056
+ * Create a new instance of Sha1.
1057
+ */
1058
+ constructor() {
1059
+ this._instance = sha1.sha1.create();
1060
+ }
1061
+ /**
1062
+ * Perform Sum on the block.
1063
+ * @param block The block to operate on.
1064
+ * @returns The sum of the block.
1065
+ */
1066
+ static sum(block) {
1067
+ core.Guards.uint8Array(Sha1._CLASS_NAME, "block", block);
1068
+ return new Sha1().update(block).digest();
1069
+ }
1070
+ /**
1071
+ * Update the hash with the block.
1072
+ * @param block The block to update the hash with.
1073
+ * @returns The instance for chaining.
1074
+ */
1075
+ update(block) {
1076
+ core.Guards.uint8Array(Sha1._CLASS_NAME, "block", block);
1077
+ this._instance.update(block);
1078
+ return this;
1079
+ }
1080
+ /**
1081
+ * Get the digest for the hash.
1082
+ * @returns The instance for chaining.
1083
+ */
1084
+ digest() {
1085
+ return this._instance.digest();
1086
+ }
1087
+ }
1088
+
1089
+ // Copyright 2024 IOTA Stiftung.
1090
+ // SPDX-License-Identifier: Apache-2.0.
1091
+ /**
1092
+ * Perform a SHA-256 hash on the block.
1093
+ */
1094
+ class Sha256 {
1095
+ /**
1096
+ * Sha256 256.
1097
+ */
1098
+ static SIZE_256 = 256;
1099
+ /**
1100
+ * Sha256 224.
1101
+ */
1102
+ static SIZE_224 = 224;
1103
+ /**
1104
+ * Runtime name for the class.
1105
+ * @internal
1106
+ */
1107
+ static _CLASS_NAME = "Sha256";
1108
+ /**
1109
+ * The instance of the hash.
1110
+ * @internal
1111
+ */
1112
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1113
+ _instance;
1114
+ /**
1115
+ * Create a new instance of Sha256.
1116
+ * @param bits The number of bits.
1117
+ */
1118
+ constructor(bits = Sha256.SIZE_256) {
1119
+ if (bits !== Sha256.SIZE_224 && bits !== Sha256.SIZE_256) {
1120
+ throw new core.GeneralError(Sha256._CLASS_NAME, "bitSize", { bitSize: bits });
1121
+ }
1122
+ this._instance = bits === Sha256.SIZE_256 ? sha256.sha256.create() : sha256.sha224.create();
1123
+ }
1124
+ /**
1125
+ * Perform Sum 256 on the block.
1126
+ * @param block The block to operate on.
1127
+ * @returns The sum 256 of the block.
1128
+ */
1129
+ static sum256(block) {
1130
+ const b2b = new Sha256(Sha256.SIZE_256);
1131
+ b2b.update(block);
1132
+ return b2b.digest();
1133
+ }
1134
+ /**
1135
+ * Perform Sum 224 on the block.
1136
+ * @param block The block to operate on.
1137
+ * @returns The sum 224 of the block.
1138
+ */
1139
+ static sum224(block) {
1140
+ const b2b = new Sha256(Sha256.SIZE_224);
1141
+ b2b.update(block);
1142
+ return b2b.digest();
1143
+ }
1144
+ /**
1145
+ * Update the hash with the block.
1146
+ * @param block The block to update the hash with.
1147
+ * @returns The instance for chaining.
1148
+ */
1149
+ update(block) {
1150
+ core.Guards.uint8Array(Sha256._CLASS_NAME, "block", block);
1151
+ this._instance.update(block);
1152
+ return this;
1153
+ }
1154
+ /**
1155
+ * Get the digest for the hash.
1156
+ * @returns The instance for chaining.
1157
+ */
1158
+ digest() {
1159
+ return this._instance.digest();
1160
+ }
1161
+ }
1162
+
1163
+ // Copyright 2024 IOTA Stiftung.
1164
+ // SPDX-License-Identifier: Apache-2.0.
1165
+ /* eslint-disable camelcase */
1166
+ /**
1167
+ * Perform a SHA-512 hash on the block.
1168
+ */
1169
+ class Sha512 {
1170
+ /**
1171
+ * Sha512 224.
1172
+ */
1173
+ static SIZE_224 = 224;
1174
+ /**
1175
+ * Sha512 256.
1176
+ */
1177
+ static SIZE_256 = 256;
1178
+ /**
1179
+ * Sha512 384.
1180
+ */
1181
+ static SIZE_384 = 384;
1182
+ /**
1183
+ * Sha512 512.
1184
+ */
1185
+ static SIZE_512 = 512;
1186
+ /**
1187
+ * Runtime name for the class.
1188
+ * @internal
1189
+ */
1190
+ static _CLASS_NAME = "Sha512";
1191
+ /**
1192
+ * The instance of the hash.
1193
+ * @internal
1194
+ */
1195
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1196
+ _instance;
1197
+ /**
1198
+ * Create a new instance of Sha512.
1199
+ * @param bits The number of bits.
1200
+ */
1201
+ constructor(bits = Sha512.SIZE_512) {
1202
+ if (bits !== Sha512.SIZE_224 &&
1203
+ bits !== Sha512.SIZE_256 &&
1204
+ bits !== Sha512.SIZE_384 &&
1205
+ bits !== Sha512.SIZE_512) {
1206
+ throw new core.GeneralError(Sha512._CLASS_NAME, "bitSize", { bitSize: bits });
1207
+ }
1208
+ if (bits === Sha512.SIZE_224) {
1209
+ this._instance = sha512.sha512_224.create();
1210
+ }
1211
+ else if (bits === Sha512.SIZE_256) {
1212
+ this._instance = sha512.sha512_256.create();
1213
+ }
1214
+ else if (bits === Sha512.SIZE_384) {
1215
+ this._instance = sha512.sha384.create();
1216
+ }
1217
+ else {
1218
+ this._instance = sha512.sha512.create();
1219
+ }
1220
+ }
1221
+ /**
1222
+ * Perform Sum 512 on the block.
1223
+ * @param block The block to operate on.
1224
+ * @returns The sum 512 of the block.
1225
+ */
1226
+ static sum512(block) {
1227
+ const b2b = new Sha512(Sha512.SIZE_512);
1228
+ b2b.update(block);
1229
+ return b2b.digest();
1230
+ }
1231
+ /**
1232
+ * Perform Sum 384 on the block.
1233
+ * @param block The block to operate on.
1234
+ * @returns The sum 384 of the block.
1235
+ */
1236
+ static sum384(block) {
1237
+ const b2b = new Sha512(Sha512.SIZE_384);
1238
+ b2b.update(block);
1239
+ return b2b.digest();
1240
+ }
1241
+ /**
1242
+ * Perform Sum 256 on the block.
1243
+ * @param block The block to operate on.
1244
+ * @returns The sum 256 of the block.
1245
+ */
1246
+ static sum256(block) {
1247
+ const b2b = new Sha512(Sha512.SIZE_256);
1248
+ b2b.update(block);
1249
+ return b2b.digest();
1250
+ }
1251
+ /**
1252
+ * Perform Sum 224 on the block.
1253
+ * @param block The block to operate on.
1254
+ * @returns The sum 224 of the block.
1255
+ */
1256
+ static sum224(block) {
1257
+ const b2b = new Sha512(Sha512.SIZE_224);
1258
+ b2b.update(block);
1259
+ return b2b.digest();
1260
+ }
1261
+ /**
1262
+ * Update the hash with the block.
1263
+ * @param block The block to update the hash with.
1264
+ * @returns The instance for chaining.
1265
+ */
1266
+ update(block) {
1267
+ core.Guards.uint8Array(Sha512._CLASS_NAME, "block", block);
1268
+ this._instance.update(block);
1269
+ return this;
1270
+ }
1271
+ /**
1272
+ * Get the digest for the hash.
1273
+ * @returns The instance for chaining.
1274
+ */
1275
+ digest() {
1276
+ return this._instance.digest();
1277
+ }
1278
+ }
1279
+
1280
+ // Copyright 2024 IOTA Stiftung.
1281
+ // SPDX-License-Identifier: Apache-2.0.
1282
+ /**
1283
+ * Implementation of Bip39 for mnemonic generation.
1284
+ */
1285
+ class Bip39 {
1286
+ /**
1287
+ * Runtime name for the class.
1288
+ * @internal
1289
+ */
1290
+ static _CLASS_NAME = "Bip39";
1291
+ /**
1292
+ * Generate a random mnemonic.
1293
+ * @param strength The strength of the mnemonic to generate, defaults to 256.
1294
+ * @param words The wordlist to use, defaults to the English wordlist.
1295
+ * @returns The random mnemonic.
1296
+ * @throws Error if the length is not a multiple of 32.
1297
+ */
1298
+ static randomMnemonic(strength = 256, words = english.wordlist) {
1299
+ core.Guards.number(Bip39._CLASS_NAME, "strength", strength);
1300
+ core.Guards.arrayValue(Bip39._CLASS_NAME, "words", words);
1301
+ if (strength % 32 !== 0) {
1302
+ throw new core.GuardError(Bip39._CLASS_NAME, "guard.length32Multiple", "strength", strength);
1303
+ }
1304
+ return bip39__namespace.generateMnemonic(words, strength);
1305
+ }
1306
+ /**
1307
+ * Generate a mnemonic from the entropy.
1308
+ * @param entropy The entropy to generate.
1309
+ * @param words The wordlist to use, defaults to the English wordlist.
1310
+ * @returns The mnemonic.
1311
+ * @throws Error if the length of the entropy is not a multiple of 4, or is less than 16 or greater than 32.
1312
+ */
1313
+ static entropyToMnemonic(entropy, words = english.wordlist) {
1314
+ core.Guards.uint8Array(Bip39._CLASS_NAME, "entropy", entropy);
1315
+ core.Guards.arrayValue(Bip39._CLASS_NAME, "words", words);
1316
+ if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
1317
+ throw new core.GuardError(Bip39._CLASS_NAME, "guard.lengthEntropy", "entropy", entropy.length);
1318
+ }
1319
+ return bip39__namespace.entropyToMnemonic(entropy, words);
1320
+ }
1321
+ /**
1322
+ * Convert a mnemonic to a seed.
1323
+ * @param mnemonic The mnemonic to convert.
1324
+ * @param password The password to apply to the seed generation.
1325
+ * @returns The seed.
1326
+ */
1327
+ static mnemonicToSeed(mnemonic, password) {
1328
+ core.Guards.stringValue(Bip39._CLASS_NAME, "mnemonic", mnemonic);
1329
+ return bip39__namespace.mnemonicToSeedSync(mnemonic, password);
1330
+ }
1331
+ /**
1332
+ * Convert the mnemonic back to entropy.
1333
+ * @param mnemonic The mnemonic to convert.
1334
+ * @param words The wordlist to use, defaults to the English wordlist.
1335
+ * @returns The entropy.
1336
+ * @throws Error if the number of words is not a multiple of 3.
1337
+ */
1338
+ static mnemonicToEntropy(mnemonic, words = english.wordlist) {
1339
+ core.Guards.stringValue(Bip39._CLASS_NAME, "mnemonic", mnemonic);
1340
+ core.Guards.arrayValue(Bip39._CLASS_NAME, "words", words);
1341
+ return bip39__namespace.mnemonicToEntropy(mnemonic, words);
1342
+ }
1343
+ }
1344
+
1345
+ // Copyright 2024 IOTA Stiftung.
1346
+ // SPDX-License-Identifier: Apache-2.0.
1347
+ /* eslint-disable no-bitwise */
1348
+ /**
1349
+ * Perform HOTP.
1350
+ * Implementation of https://datatracker.ietf.org/doc/html/rfc4226 .
1351
+ */
1352
+ class Hotp {
1353
+ /**
1354
+ * Runtime name for the class.
1355
+ * @internal
1356
+ */
1357
+ static _CLASS_NAME = "Hotp";
1358
+ /**
1359
+ * Generate a counter based One Time Password.
1360
+ * @param key Key for the one time password.
1361
+ * @param counter This should be stored by the application,
1362
+ * must be user specific, and be incremented for each request.
1363
+ * @returns The one time password.
1364
+ */
1365
+ static generate(key, counter) {
1366
+ core.Guards.uint8Array(Hotp._CLASS_NAME, "key", key);
1367
+ core.Guards.number(Hotp._CLASS_NAME, "counter", counter);
1368
+ return otp__namespace.hotp({ secret: key, digits: 6, algorithm: "sha1", interval: 30 }, counter);
1369
+ }
1370
+ }
1371
+
1372
+ // Copyright 2024 IOTA Stiftung.
1373
+ // SPDX-License-Identifier: Apache-2.0.
1374
+ /**
1375
+ * Perform TOTP.
1376
+ * Implementation of https://datatracker.ietf.org/doc/html/rfc4226 .
1377
+ */
1378
+ class Totp {
1379
+ /**
1380
+ * Generate a time based One Time Password.
1381
+ * @param key Key for the one time password.
1382
+ * @param interval The time step of the counter.
1383
+ * @param timestamp The timestamp.
1384
+ * @returns The one time password.
1385
+ */
1386
+ static generate(key, interval = 30, timestamp = Date.now()) {
1387
+ return otp__namespace.totp({ secret: key, digits: 6, algorithm: "sha1", interval }, timestamp);
1388
+ }
1389
+ /**
1390
+ * Check a One Time Password based on a timer.
1391
+ * @param token Passcode to validate.
1392
+ * @param key Key for the one time password. This should be unique and secret for
1393
+ * every user as it is the seed used to calculate the HMAC.
1394
+ * @param window The allowable margin for the counter.
1395
+ * @param interval The time step of the counter.
1396
+ * @param timestamp The timestamp now.
1397
+ * @returns Undefined if failure, delta on success
1398
+ */
1399
+ static verify(token, key, window = 2, interval = 30, timestamp = Date.now()) {
1400
+ for (let i = -window; i < window; i++) {
1401
+ const intervalWindow = i * interval * 1000;
1402
+ if (timestamp + intervalWindow > 0) {
1403
+ const gen = this.generate(key, interval, timestamp + intervalWindow);
1404
+ if (gen === token) {
1405
+ // We have found a matching code
1406
+ return i;
1407
+ }
1408
+ }
1409
+ }
1410
+ // If we get to here then no codes have matched, return undefined
1411
+ return undefined;
1412
+ }
1413
+ /**
1414
+ * Generate a secret.
1415
+ * @param length The length of the secret to generate.
1416
+ * @returns The secret encoded as base32.
1417
+ */
1418
+ static generateSecret(length) {
1419
+ const encodedBase32 = core.Base32.encode(core.RandomHelper.generate(length));
1420
+ // Strip the trailing = the authenticator apps don't need them
1421
+ return encodedBase32.replace(/=/g, "");
1422
+ }
1423
+ /**
1424
+ * Convert the secret back to bytes.
1425
+ * @param secretBase32 The secret encoded as base32.
1426
+ * @returns The bytes of the secret.
1427
+ */
1428
+ static secretToBytes(secretBase32) {
1429
+ return core.Base32.decode(secretBase32);
1430
+ }
1431
+ /**
1432
+ * Generate a url for use with authenticator apps.
1433
+ * See https://github.com/google/google-authenticator/wiki/Key-Uri-Format .
1434
+ * @param issuer The issuer of the totp.
1435
+ * @param label The label that will show in auth apps.
1436
+ * @param secretBase32 The secret as base 32.
1437
+ * @returns The url.
1438
+ */
1439
+ static generateAuthUrl(issuer, label, secretBase32) {
1440
+ const encodedIssuer = encodeURIComponent(issuer);
1441
+ return `otpauth://totp/${encodedIssuer}%3A${encodeURIComponent(label)}?secret=${secretBase32}&issuer=${encodedIssuer}&digits=6&algorithm=SHA1&interval=30`;
1442
+ }
1443
+ }
1444
+
1445
+ // Copyright 2024 IOTA Stiftung.
1446
+ // SPDX-License-Identifier: Apache-2.0.
1447
+ /**
1448
+ * Generate random passwords.
1449
+ */
1450
+ class PasswordGenerator {
1451
+ /**
1452
+ * Generate a password of given length.
1453
+ * @param length The length of the password to generate.
1454
+ * @returns The random password.
1455
+ */
1456
+ static generate(length) {
1457
+ const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1458
+ const alphabet2 = `${alphabet}0123456789!#$£%^&*+=@~?}`;
1459
+ const chars = [];
1460
+ while (chars.length < length) {
1461
+ const charSet = chars.length === 0 ? alphabet : alphabet2;
1462
+ let b = 0;
1463
+ do {
1464
+ b = core.RandomHelper.generate(1)[0];
1465
+ } while (b >= charSet.length);
1466
+ chars.push(charSet[b]);
1467
+ }
1468
+ return chars.join("");
1469
+ }
1470
+ }
1471
+
1472
+ // Copyright 2024 IOTA Stiftung.
1473
+ // SPDX-License-Identifier: Apache-2.0.
1474
+ /**
1475
+ * Test password strength.
1476
+ * Ref https://www.owasp.org/index.php/Authentication_Cheat_Sheet#Implement_Proper_Password_Strength_Controls .
1477
+ */
1478
+ class PasswordValidator {
1479
+ /**
1480
+ * Test the strength of the password.
1481
+ * @param property The name of the property.
1482
+ * @param password The password to test.
1483
+ * @param failures The list of failures to add to.
1484
+ * @param options Options to configure the testing.
1485
+ * @param options.minLength The minimum length of the password, defaults to 8.
1486
+ * @param options.maxLength The minimum length of the password, defaults to 128.
1487
+ * @param options.minPhraseLength The minimum length of the password for it to be considered a pass phrase.
1488
+ */
1489
+ static validate(property, password, failures, options) {
1490
+ const isString = core.Validation.stringValue(property, password, failures);
1491
+ if (isString) {
1492
+ const minLength = options?.minLength ?? 8;
1493
+ if (password.length < minLength) {
1494
+ failures.push({
1495
+ property,
1496
+ reason: "validation.minLengthRequired",
1497
+ properties: {
1498
+ minLength
1499
+ }
1500
+ });
1501
+ }
1502
+ const maxLength = options?.maxLength ?? 128;
1503
+ if (password.length > maxLength) {
1504
+ failures.push({
1505
+ property,
1506
+ reason: "validation.maxLengthRequired",
1507
+ properties: {
1508
+ maxLength
1509
+ }
1510
+ });
1511
+ }
1512
+ if (/(.)\1{2,}/.test(password)) {
1513
+ failures.push({
1514
+ property,
1515
+ reason: "validation.repeatedCharacters"
1516
+ });
1517
+ }
1518
+ // If this looks like a phrase then apply additional rules
1519
+ const minPhraseLength = options?.minPhraseLength ?? 20;
1520
+ if (password.length < minPhraseLength || !password.includes(" ")) {
1521
+ if (!/[a-z]/.test(password)) {
1522
+ failures.push({
1523
+ property,
1524
+ reason: "validation.atLeastOneLowerCase"
1525
+ });
1526
+ }
1527
+ if (!/[A-Z]/.test(password)) {
1528
+ failures.push({
1529
+ property,
1530
+ reason: "validation.atLeastOneUpperCase"
1531
+ });
1532
+ }
1533
+ if (!/\d/.test(password)) {
1534
+ failures.push({
1535
+ property,
1536
+ reason: "validation.atLeastOneNumber"
1537
+ });
1538
+ }
1539
+ if (!/[^\dA-Za-z]/.test(password)) {
1540
+ failures.push({
1541
+ property,
1542
+ reason: "validation.atLeastOneSpecialChar"
1543
+ });
1544
+ }
1545
+ }
1546
+ }
1547
+ }
1548
+ }
1549
+
1550
+ exports.Bech32 = Bech32;
1551
+ exports.Bip32Path = Bip32Path;
1552
+ exports.Bip39 = Bip39;
1553
+ exports.Bip44 = Bip44;
1554
+ exports.Blake2b = Blake2b;
1555
+ exports.ChaCha20Poly1305 = ChaCha20Poly1305;
1556
+ exports.Ed25519 = Ed25519;
1557
+ exports.HmacSha1 = HmacSha1;
1558
+ exports.HmacSha256 = HmacSha256;
1559
+ exports.HmacSha512 = HmacSha512;
1560
+ exports.Hotp = Hotp;
1561
+ exports.KeyType = KeyType;
1562
+ exports.PasswordGenerator = PasswordGenerator;
1563
+ exports.PasswordValidator = PasswordValidator;
1564
+ exports.Pbkdf2 = Pbkdf2;
1565
+ exports.Secp256k1 = Secp256k1;
1566
+ exports.Sha1 = Sha1;
1567
+ exports.Sha256 = Sha256;
1568
+ exports.Sha512 = Sha512;
1569
+ exports.Slip0010 = Slip0010;
1570
+ exports.Totp = Totp;
1571
+ exports.X25519 = X25519;
1572
+ exports.Zip215 = Zip215;