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