@decryption/hashes 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -0
  3. package/_blake.d.ts +20 -0
  4. package/_blake.js +56 -0
  5. package/_md.d.ts +98 -0
  6. package/_md.js +207 -0
  7. package/_u64.d.ts +62 -0
  8. package/_u64.js +106 -0
  9. package/argon2.d.ts +111 -0
  10. package/argon2.js +525 -0
  11. package/blake1.d.ts +155 -0
  12. package/blake1.js +599 -0
  13. package/blake2.d.ts +183 -0
  14. package/blake2.js +540 -0
  15. package/blake3.d.ts +67 -0
  16. package/blake3.js +287 -0
  17. package/eskdf.d.ts +91 -0
  18. package/eskdf.js +223 -0
  19. package/esm/_blake.js +51 -0
  20. package/esm/_md.js +201 -0
  21. package/esm/_u64.js +83 -0
  22. package/esm/argon2.js +516 -0
  23. package/esm/blake1.js +559 -0
  24. package/esm/blake2.js +500 -0
  25. package/esm/blake3.js +283 -0
  26. package/esm/eskdf.js +217 -0
  27. package/esm/hkdf.js +119 -0
  28. package/esm/hmac.js +92 -0
  29. package/esm/index.js +34 -0
  30. package/esm/legacy.js +326 -0
  31. package/esm/pbkdf2.js +134 -0
  32. package/esm/scrypt.js +256 -0
  33. package/esm/sha2.js +457 -0
  34. package/esm/sha3-addons.js +782 -0
  35. package/esm/sha3.js +430 -0
  36. package/esm/utils.js +577 -0
  37. package/esm/webcrypto.js +163 -0
  38. package/hkdf.d.ts +63 -0
  39. package/hkdf.js +125 -0
  40. package/hmac.d.ts +46 -0
  41. package/hmac.js +96 -0
  42. package/index.d.ts +0 -0
  43. package/index.js +34 -0
  44. package/legacy.d.ts +101 -0
  45. package/legacy.js +332 -0
  46. package/package.json +47 -0
  47. package/pbkdf2.d.ts +55 -0
  48. package/pbkdf2.js +138 -0
  49. package/scrypt.d.ts +64 -0
  50. package/scrypt.js +260 -0
  51. package/sha2.d.ts +248 -0
  52. package/sha2.js +499 -0
  53. package/sha3-addons.d.ts +460 -0
  54. package/sha3-addons.js +791 -0
  55. package/sha3.d.ts +198 -0
  56. package/sha3.js +435 -0
  57. package/utils.d.ts +518 -0
  58. package/utils.js +606 -0
  59. package/webcrypto.d.ts +119 -0
  60. package/webcrypto.js +168 -0
@@ -0,0 +1,163 @@
1
+ import { abytes, ahash, anumber, checkOpts, kdfInputToBytes, } from './utils';
2
+ function _subtle() {
3
+ const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
4
+ const sb = cr?.subtle;
5
+ if (typeof sb === 'object' && sb != null)
6
+ return sb;
7
+ throw new Error('crypto.subtle must be defined');
8
+ }
9
+ function createWebHash(name, blockLen, outputLen) {
10
+ const hashC = async (msg) => {
11
+ abytes(msg);
12
+ const crypto = _subtle();
13
+ return new Uint8Array(await crypto.digest(name, msg));
14
+ };
15
+ hashC.webCryptoName = name; // make sure it won't interfere with function name
16
+ hashC.outputLen = outputLen;
17
+ hashC.blockLen = blockLen;
18
+ hashC.create = () => {
19
+ // Present only so this async wrapper satisfies the shared
20
+ // hash-wrapper shape checked by `ahashWeb()`.
21
+ throw new Error('not implemented');
22
+ };
23
+ // Later WebCrypto HMAC/HKDF/PBKDF2 calls read descriptor metadata directly, so freezing prevents
24
+ // callers from retargeting a `sha256` wrapper into a different backend digest by mutation.
25
+ return Object.freeze(hashC);
26
+ }
27
+ function ahashWeb(hash) {
28
+ ahash(hash);
29
+ if (typeof hash.webCryptoName !== 'string')
30
+ throw new Error('non-web hash');
31
+ }
32
+ /** WebCrypto SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */
33
+ // export const sha1: WebHash = createHash('SHA-1', 64, 20);
34
+ /**
35
+ * WebCrypto SHA2-256 hash function from RFC 6234.
36
+ * @param msg - message bytes to hash
37
+ * @returns Promise resolving to digest bytes.
38
+ * @example
39
+ * Hash a message with WebCrypto SHA2-256.
40
+ * ```ts
41
+ * await sha256(new Uint8Array([97, 98, 99]));
42
+ * ```
43
+ */
44
+ export const sha256 = /* @__PURE__ */ createWebHash('SHA-256', 64, 32);
45
+ /**
46
+ * WebCrypto SHA2-384 hash function from RFC 6234.
47
+ * @param msg - message bytes to hash
48
+ * @returns Promise resolving to digest bytes.
49
+ * @example
50
+ * Hash a message with WebCrypto SHA2-384.
51
+ * ```ts
52
+ * await sha384(new Uint8Array([97, 98, 99]));
53
+ * ```
54
+ */
55
+ export const sha384 = /* @__PURE__ */ createWebHash('SHA-384', 128, 48);
56
+ /**
57
+ * WebCrypto SHA2-512 hash function from RFC 6234.
58
+ * @param msg - message bytes to hash
59
+ * @returns Promise resolving to digest bytes.
60
+ * @example
61
+ * Hash a message with WebCrypto SHA2-512.
62
+ * ```ts
63
+ * await sha512(new Uint8Array([97, 98, 99]));
64
+ * ```
65
+ */
66
+ export const sha512 = /* @__PURE__ */ createWebHash('SHA-512', 128, 64);
67
+ export const hmac = /* @__PURE__ */ (() => {
68
+ const hmac_ = async (hash, key, message) => {
69
+ const crypto = _subtle();
70
+ abytes(key, undefined, 'key');
71
+ abytes(message, undefined, 'message');
72
+ ahashWeb(hash);
73
+ // WebCrypto keys can't be zeroized
74
+ // prettier-ignore
75
+ const wkey = await crypto.importKey('raw', key, { name: 'HMAC', hash: hash.webCryptoName }, false, ['sign']);
76
+ return new Uint8Array(await crypto.sign('HMAC', wkey, message));
77
+ };
78
+ hmac_.create = (_hash, _key) => {
79
+ throw new Error('not implemented');
80
+ };
81
+ return hmac_;
82
+ })();
83
+ /**
84
+ * WebCrypto HKDF (RFC 5869): derive keys from an initial input.
85
+ * Combines hkdf_extract + hkdf_expand in one step
86
+ * @param hash - hash function that would be used (e.g. sha256). Webcrypto version.
87
+ * @param ikm - input keying material, the initial key
88
+ * @param salt - optional salt value (a non-secret random value)
89
+ * @param info - optional context and application specific information bytes
90
+ * @param length - length of output keying material in bytes.
91
+ * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` requests an empty OKM.
92
+ * @returns Promise resolving to derived key bytes.
93
+ * The RFC `L <= 255 * HashLen` bound is currently enforced only by backend
94
+ * `deriveBits()` rejection, not by an explicit library-side guard.
95
+ * @throws If the current runtime does not provide `crypto.subtle`. {@link Error}
96
+ * @example
97
+ * WebCrypto HKDF (RFC 5869): derive keys from an initial input.
98
+ * ```ts
99
+ * import { hkdf, sha256 } from '@decryption/hashes/webcrypto.js';
100
+ * import { randomBytes, utf8ToBytes } from '@decryption/hashes/utils.js';
101
+ * const inputKey = randomBytes(32);
102
+ * const salt = randomBytes(32);
103
+ * const info = utf8ToBytes('application-key');
104
+ * const okm = await hkdf(sha256, inputKey, salt, info, 32);
105
+ * ```
106
+ */
107
+ export async function hkdf(hash, ikm, salt, info, length) {
108
+ const crypto = _subtle();
109
+ ahashWeb(hash);
110
+ abytes(ikm, undefined, 'ikm');
111
+ anumber(length, 'length');
112
+ if (salt !== undefined)
113
+ abytes(salt, undefined, 'salt');
114
+ if (info !== undefined)
115
+ abytes(info, undefined, 'info');
116
+ const wkey = await crypto.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);
117
+ const opts = {
118
+ name: 'HKDF',
119
+ hash: hash.webCryptoName,
120
+ salt: salt === undefined ? new Uint8Array(0) : salt,
121
+ info: info === undefined ? new Uint8Array(0) : info,
122
+ };
123
+ return new Uint8Array(await crypto.deriveBits(opts, wkey, 8 * length));
124
+ }
125
+ /**
126
+ * WebCrypto PBKDF2-HMAC: RFC 8018 key derivation function.
127
+ * @param hash - hash function that would be used e.g. sha256. Webcrypto version.
128
+ * @param password - password from which a derived key is generated; string
129
+ * inputs are normalized through `kdfInputToBytes()`, i.e. UTF-8
130
+ * @param salt - cryptographic salt; string inputs are normalized through
131
+ * `kdfInputToBytes()`, i.e. UTF-8
132
+ * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,
133
+ * must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}.
134
+ * @returns Promise resolving to derived key bytes.
135
+ * Positive-iteration enforcement is currently delegated to backend
136
+ * `deriveBits()` rejection (for example `c = 0`), not a dedicated
137
+ * library-side guard.
138
+ * @throws If the current runtime does not provide `crypto.subtle`. {@link Error}
139
+ * @example
140
+ * WebCrypto PBKDF2-HMAC: RFC 2898 key derivation function.
141
+ * ```ts
142
+ * import { pbkdf2, sha256 } from '@decryption/hashes/webcrypto.js';
143
+ * const key = await pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
144
+ * ```
145
+ */
146
+ export async function pbkdf2(hash, password, salt, opts) {
147
+ const crypto = _subtle();
148
+ ahashWeb(hash);
149
+ const _opts = checkOpts({ dkLen: 32 }, opts);
150
+ const { c, dkLen } = _opts;
151
+ anumber(c, 'c');
152
+ anumber(dkLen, 'dkLen');
153
+ // RFC 8018 §5.2 defines dkLen as a positive integer.
154
+ if (dkLen < 1)
155
+ throw new Error('"dkLen" must be >= 1');
156
+ const _password = kdfInputToBytes(password, 'password');
157
+ const _salt = kdfInputToBytes(salt, 'salt');
158
+ const key = await crypto.importKey('raw', _password, 'PBKDF2', false, [
159
+ 'deriveBits',
160
+ ]);
161
+ const deriveOpts = { name: 'PBKDF2', salt: _salt, iterations: c, hash: hash.webCryptoName };
162
+ return new Uint8Array(await crypto.deriveBits(deriveOpts, key, 8 * dkLen));
163
+ }
package/hkdf.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ import { type CHash, type TArg, type TRet } from './utils';
2
+ /**
3
+ * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
4
+ * Arguments position differs from spec (IKM is first one, since it is not optional)
5
+ * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.
6
+ * @param hash - hash function that would be used (e.g. sha256)
7
+ * @param ikm - input keying material, the initial key
8
+ * @param salt - optional salt value (a non-secret random value)
9
+ * @returns Pseudorandom key derived from input keying material.
10
+ * @example
11
+ * Run the HKDF extract step.
12
+ * ```ts
13
+ * import { extract } from '@decryption/hashes/hkdf.js';
14
+ * import { sha256 } from '@decryption/hashes/sha2.js';
15
+ * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));
16
+ * ```
17
+ */
18
+ export declare function extract(hash: TArg<CHash>, ikm: TArg<Uint8Array>, salt?: TArg<Uint8Array>): TRet<Uint8Array>;
19
+ /**
20
+ * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
21
+ * @param hash - hash function that would be used (e.g. sha256)
22
+ * @param prk - a pseudorandom key of at least HashLen octets
23
+ * (usually, the output from the extract step)
24
+ * @param info - optional context and application specific information (can be a zero-length string)
25
+ * @param length - length of output keying material in bytes.
26
+ * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
27
+ * @returns Output keying material with the requested length.
28
+ * @throws If the requested output length exceeds the HKDF limit
29
+ * for the selected hash. {@link Error}
30
+ * @example
31
+ * Run the HKDF expand step.
32
+ * ```ts
33
+ * import { expand } from '@decryption/hashes/hkdf.js';
34
+ * import { sha256 } from '@decryption/hashes/sha2.js';
35
+ * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);
36
+ * ```
37
+ */
38
+ export declare function expand(hash: TArg<CHash>, prk: TArg<Uint8Array>, info?: TArg<Uint8Array>, length?: number): TRet<Uint8Array>;
39
+ /**
40
+ * HKDF (RFC 5869): derive keys from an initial input.
41
+ * Combines hkdf_extract + hkdf_expand in one step
42
+ * @param hash - hash function that would be used (e.g. sha256)
43
+ * @param ikm - input keying material, the initial key
44
+ * @param salt - optional salt value (a non-secret random value)
45
+ * @param info - optional context and application specific information bytes
46
+ * @param length - length of output keying material in bytes.
47
+ * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
48
+ * @returns Output keying material derived from the input key.
49
+ * @throws If the requested output length exceeds the HKDF limit
50
+ * for the selected hash. {@link Error}
51
+ * @example
52
+ * HKDF (RFC 5869): derive keys from an initial input.
53
+ * ```ts
54
+ * import { hkdf } from '@decryption/hashes/hkdf.js';
55
+ * import { sha256 } from '@decryption/hashes/sha2.js';
56
+ * import { randomBytes, utf8ToBytes } from '@decryption/hashes/utils.js';
57
+ * const inputKey = randomBytes(32);
58
+ * const salt = randomBytes(32);
59
+ * const info = utf8ToBytes('application-key');
60
+ * const okm = hkdf(sha256, inputKey, salt, info, 32);
61
+ * ```
62
+ */
63
+ export declare const hkdf: (hash: TArg<CHash>, ikm: TArg<Uint8Array>, salt: TArg<Uint8Array | undefined>, info: TArg<Uint8Array | undefined>, length: number) => TRet<Uint8Array>;
package/hkdf.js ADDED
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hkdf = void 0;
4
+ exports.extract = extract;
5
+ exports.expand = expand;
6
+ /**
7
+ * HKDF (RFC 5869): extract + expand in one step.
8
+ * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.
9
+ * @module
10
+ */
11
+ const hmac_1 = require("./hmac");
12
+ const utils_1 = require("./utils");
13
+ /**
14
+ * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
15
+ * Arguments position differs from spec (IKM is first one, since it is not optional)
16
+ * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.
17
+ * @param hash - hash function that would be used (e.g. sha256)
18
+ * @param ikm - input keying material, the initial key
19
+ * @param salt - optional salt value (a non-secret random value)
20
+ * @returns Pseudorandom key derived from input keying material.
21
+ * @example
22
+ * Run the HKDF extract step.
23
+ * ```ts
24
+ * import { extract } from '@decryption/hashes/hkdf.js';
25
+ * import { sha256 } from '@decryption/hashes/sha2.js';
26
+ * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));
27
+ * ```
28
+ */
29
+ function extract(hash, ikm, salt) {
30
+ (0, utils_1.ahash)(hash);
31
+ // NOTE: some libraries treat zero-length array as 'not provided';
32
+ // we don't, since we have undefined as 'not provided'
33
+ // https://github.com/RustCrypto/KDFs/issues/15
34
+ if (salt === undefined)
35
+ salt = new Uint8Array(hash.outputLen);
36
+ return (0, hmac_1.hmac)(hash, salt, ikm);
37
+ }
38
+ // Shared mutable scratch byte for the RFC 5869 block counter `N`.
39
+ // Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning.
40
+ const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
41
+ // Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input.
42
+ const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
43
+ /**
44
+ * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
45
+ * @param hash - hash function that would be used (e.g. sha256)
46
+ * @param prk - a pseudorandom key of at least HashLen octets
47
+ * (usually, the output from the extract step)
48
+ * @param info - optional context and application specific information (can be a zero-length string)
49
+ * @param length - length of output keying material in bytes.
50
+ * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
51
+ * @returns Output keying material with the requested length.
52
+ * @throws If the requested output length exceeds the HKDF limit
53
+ * for the selected hash. {@link Error}
54
+ * @example
55
+ * Run the HKDF expand step.
56
+ * ```ts
57
+ * import { expand } from '@decryption/hashes/hkdf.js';
58
+ * import { sha256 } from '@decryption/hashes/sha2.js';
59
+ * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);
60
+ * ```
61
+ */
62
+ function expand(hash, prk, info, length = 32) {
63
+ (0, utils_1.ahash)(hash);
64
+ (0, utils_1.anumber)(length, 'length');
65
+ (0, utils_1.abytes)(prk, undefined, 'prk');
66
+ const olen = hash.outputLen;
67
+ // RFC 5869 §2.3: PRK is "a pseudorandom key of at least HashLen octets".
68
+ if (prk.length < olen)
69
+ throw new Error('"prk" must be at least HashLen octets');
70
+ // RFC 5869 §2.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM.
71
+ if (length > 255 * olen)
72
+ throw new Error('Length must be <= 255*HashLen');
73
+ const blocks = Math.ceil(length / olen);
74
+ if (info === undefined)
75
+ info = EMPTY_BUFFER;
76
+ else
77
+ (0, utils_1.abytes)(info, undefined, 'info');
78
+ // first L(ength) octets of T
79
+ const okm = new Uint8Array(blocks * olen);
80
+ // Re-use HMAC instance between blocks
81
+ const HMAC = hmac_1.hmac.create(hash, prk);
82
+ const HMACTmp = HMAC._cloneInto();
83
+ const T = new Uint8Array(HMAC.outputLen);
84
+ for (let counter = 0; counter < blocks; counter++) {
85
+ HKDF_COUNTER[0] = counter + 1;
86
+ // T(0) = empty string (zero length)
87
+ // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)
88
+ HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)
89
+ .update(info)
90
+ .update(HKDF_COUNTER)
91
+ .digestInto(T);
92
+ okm.set(T, olen * counter);
93
+ HMAC._cloneInto(HMACTmp);
94
+ }
95
+ HMAC.destroy();
96
+ HMACTmp.destroy();
97
+ (0, utils_1.clean)(T, HKDF_COUNTER);
98
+ return okm.slice(0, length);
99
+ }
100
+ /**
101
+ * HKDF (RFC 5869): derive keys from an initial input.
102
+ * Combines hkdf_extract + hkdf_expand in one step
103
+ * @param hash - hash function that would be used (e.g. sha256)
104
+ * @param ikm - input keying material, the initial key
105
+ * @param salt - optional salt value (a non-secret random value)
106
+ * @param info - optional context and application specific information bytes
107
+ * @param length - length of output keying material in bytes.
108
+ * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
109
+ * @returns Output keying material derived from the input key.
110
+ * @throws If the requested output length exceeds the HKDF limit
111
+ * for the selected hash. {@link Error}
112
+ * @example
113
+ * HKDF (RFC 5869): derive keys from an initial input.
114
+ * ```ts
115
+ * import { hkdf } from '@decryption/hashes/hkdf.js';
116
+ * import { sha256 } from '@decryption/hashes/sha2.js';
117
+ * import { randomBytes, utf8ToBytes } from '@decryption/hashes/utils.js';
118
+ * const inputKey = randomBytes(32);
119
+ * const salt = randomBytes(32);
120
+ * const info = utf8ToBytes('application-key');
121
+ * const okm = hkdf(sha256, inputKey, salt, info, 32);
122
+ * ```
123
+ */
124
+ const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
125
+ exports.hkdf = hkdf;
package/hmac.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * HMAC: RFC2104 message authentication code.
3
+ * @module
4
+ */
5
+ import { type CHash, type Hash, type TArg, type TRet } from './utils';
6
+ /**
7
+ * Internal class for HMAC.
8
+ * Accepts any byte key, although RFC 2104 §3 recommends keys at least
9
+ * `HashLen` bytes long.
10
+ */
11
+ export declare class _HMAC<T extends Hash<T>> implements Hash<_HMAC<T>> {
12
+ oHash: T;
13
+ iHash: T;
14
+ blockLen: number;
15
+ outputLen: number;
16
+ canXOF: boolean;
17
+ private finished;
18
+ private destroyed;
19
+ constructor(hash: TArg<CHash>, key: TArg<Uint8Array>);
20
+ update(buf: TArg<Uint8Array>): this;
21
+ digestInto(out: TArg<Uint8Array>): void;
22
+ digest(): TRet<Uint8Array>;
23
+ _cloneInto(to?: _HMAC<T>): _HMAC<T>;
24
+ clone(): _HMAC<T>;
25
+ destroy(): void;
26
+ }
27
+ /**
28
+ * HMAC: RFC2104 message authentication code.
29
+ * @param hash - function that would be used e.g. sha256
30
+ * @param key - authentication key bytes
31
+ * @param message - message bytes to authenticate
32
+ * @returns Authentication tag bytes.
33
+ * @example
34
+ * Compute an RFC 2104 HMAC.
35
+ * ```ts
36
+ * import { hmac } from '@decryption/hashes/hmac.js';
37
+ * import { sha256 } from '@decryption/hashes/sha2.js';
38
+ * const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));
39
+ * ```
40
+ */
41
+ type HmacFn = {
42
+ (hash: TArg<CHash>, key: TArg<Uint8Array>, message: TArg<Uint8Array>): TRet<Uint8Array>;
43
+ create(hash: TArg<CHash>, key: TArg<Uint8Array>): TRet<_HMAC<any>>;
44
+ };
45
+ export declare const hmac: TRet<HmacFn>;
46
+ export {};
package/hmac.js ADDED
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hmac = exports._HMAC = void 0;
4
+ /**
5
+ * HMAC: RFC2104 message authentication code.
6
+ * @module
7
+ */
8
+ const utils_1 = require("./utils");
9
+ /**
10
+ * Internal class for HMAC.
11
+ * Accepts any byte key, although RFC 2104 §3 recommends keys at least
12
+ * `HashLen` bytes long.
13
+ */
14
+ class _HMAC {
15
+ oHash;
16
+ iHash;
17
+ blockLen;
18
+ outputLen;
19
+ canXOF = false;
20
+ finished = false;
21
+ destroyed = false;
22
+ constructor(hash, key) {
23
+ (0, utils_1.ahash)(hash);
24
+ (0, utils_1.abytes)(key, undefined, 'key');
25
+ this.iHash = hash.create();
26
+ if (typeof this.iHash.update !== 'function')
27
+ throw new Error('Expected instance of class which extends utils.Hash');
28
+ this.blockLen = this.iHash.blockLen;
29
+ this.outputLen = this.iHash.outputLen;
30
+ const blockLen = this.blockLen;
31
+ const pad = new Uint8Array(blockLen);
32
+ // blockLen can be bigger than outputLen
33
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
34
+ for (let i = 0; i < pad.length; i++)
35
+ pad[i] ^= 0x36;
36
+ this.iHash.update(pad);
37
+ // By doing update (processing of the first block) of the outer hash here,
38
+ // we can re-use it between multiple calls via clone.
39
+ this.oHash = hash.create();
40
+ // Undo internal XOR && apply outer XOR
41
+ for (let i = 0; i < pad.length; i++)
42
+ pad[i] ^= 0x36 ^ 0x5c;
43
+ this.oHash.update(pad);
44
+ (0, utils_1.clean)(pad);
45
+ }
46
+ update(buf) {
47
+ (0, utils_1.aexists)(this);
48
+ this.iHash.update(buf);
49
+ return this;
50
+ }
51
+ digestInto(out) {
52
+ (0, utils_1.aexists)(this);
53
+ (0, utils_1.aoutput)(out, this);
54
+ this.finished = true;
55
+ const buf = out.subarray(0, this.outputLen);
56
+ // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before
57
+ // overwriting that same prefix with the final tag, leaving any oversized tail untouched.
58
+ this.iHash.digestInto(buf);
59
+ this.oHash.update(buf);
60
+ this.oHash.digestInto(buf);
61
+ this.destroy();
62
+ }
63
+ digest() {
64
+ const out = new Uint8Array(this.oHash.outputLen);
65
+ this.digestInto(out);
66
+ return out;
67
+ }
68
+ _cloneInto(to) {
69
+ // Create new instance without calling constructor since the key
70
+ // is already in state and we don't know it.
71
+ to ||= Object.create(Object.getPrototypeOf(this), {});
72
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
73
+ to = to;
74
+ to.finished = finished;
75
+ to.destroyed = destroyed;
76
+ to.blockLen = blockLen;
77
+ to.outputLen = outputLen;
78
+ to.oHash = oHash._cloneInto(to.oHash);
79
+ to.iHash = iHash._cloneInto(to.iHash);
80
+ return to;
81
+ }
82
+ clone() {
83
+ return this._cloneInto();
84
+ }
85
+ destroy() {
86
+ this.destroyed = true;
87
+ this.oHash.destroy();
88
+ this.iHash.destroy();
89
+ }
90
+ }
91
+ exports._HMAC = _HMAC;
92
+ exports.hmac = (() => {
93
+ const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
94
+ hmac_.create = (hash, key) => new _HMAC(hash, key);
95
+ return hmac_;
96
+ })();
package/index.d.ts ADDED
File without changes
package/index.js ADDED
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ /**
3
+ * Audited & minimal JS implementation of hash functions, MACs, and KDFs.
4
+ * Check out individual modules.
5
+ * @module
6
+ * @example
7
+ ```js
8
+ import {
9
+ sha256, sha384, sha512, sha224, sha512_224, sha512_256
10
+ } from '@decryption/hashes/sha2.js';
11
+ import {
12
+ sha3_224, sha3_256, sha3_384, sha3_512,
13
+ keccak_224, keccak_256, keccak_384, keccak_512,
14
+ shake128, shake256
15
+ } from '@decryption/hashes/sha3.js';
16
+ import {
17
+ cshake128, cshake256,
18
+ turboshake128, turboshake256,
19
+ kt128, kt256,
20
+ kmac128, kmac256,
21
+ tuplehash256, parallelhash256,
22
+ keccakprg
23
+ } from '@decryption/hashes/sha3-addons.js';
24
+ import { blake3 } from '@decryption/hashes/blake3.js';
25
+ import { blake2b, blake2s } from '@decryption/hashes/blake2.js';
26
+ import { hmac } from '@decryption/hashes/hmac.js';
27
+ import { hkdf } from '@decryption/hashes/hkdf.js';
28
+ import { pbkdf2, pbkdf2Async } from '@decryption/hashes/pbkdf2.js';
29
+ import { scrypt, scryptAsync } from '@decryption/hashes/scrypt.js';
30
+ import { md5, ripemd160, sha1 } from '@decryption/hashes/legacy.js';
31
+ import * as utils from '@decryption/hashes/utils.js';
32
+ ```
33
+ */
34
+ throw new Error('root module cannot be imported: import submodules instead. Check out README');
package/legacy.d.ts ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+
3
+ SHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions.
4
+ RFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors,
5
+ not the base RIPEMD-160 compression spec.
6
+ Don't use them in a new protocol. What "weak" means:
7
+
8
+ - Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
9
+ - No practical pre-image attacks (only theoretical, 2^123.4)
10
+ - HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151
11
+ * @module
12
+ */
13
+ import { HashMD } from './_md';
14
+ import { type CHash, type TRet } from './utils';
15
+ /** Internal SHA1 legacy hash class. */
16
+ export declare class _SHA1 extends HashMD<_SHA1> {
17
+ private A;
18
+ private B;
19
+ private C;
20
+ private D;
21
+ private E;
22
+ constructor();
23
+ protected get(): [number, number, number, number, number];
24
+ protected set(A: number, B: number, C: number, D: number, E: number): void;
25
+ protected process(view: DataView, offset: number): void;
26
+ protected roundClean(): void;
27
+ destroy(): void;
28
+ }
29
+ /**
30
+ * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken.
31
+ * @param msg - message bytes to hash
32
+ * @returns Digest bytes.
33
+ * @example
34
+ * Hash a message with SHA1.
35
+ * ```ts
36
+ * sha1(new Uint8Array([97, 98, 99]));
37
+ * ```
38
+ */
39
+ export declare const sha1: TRet<CHash>;
40
+ /** Internal MD5 legacy hash class. */
41
+ export declare class _MD5 extends HashMD<_MD5> {
42
+ private A;
43
+ private B;
44
+ private C;
45
+ private D;
46
+ constructor();
47
+ protected get(): [number, number, number, number];
48
+ protected set(A: number, B: number, C: number, D: number): void;
49
+ protected process(view: DataView, offset: number): void;
50
+ protected roundClean(): void;
51
+ destroy(): void;
52
+ }
53
+ /**
54
+ * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.
55
+ * MD5 architecture is similar to SHA1, with some differences:
56
+ * - Reduced output length: 16 bytes (128 bit) instead of 20
57
+ * - 64 rounds, instead of 80
58
+ * - Little-endian: could be faster, but will require more code
59
+ * - Non-linear index selection: huge speed-up for unroll
60
+ * - Per round constants: more memory accesses, additional speed-up for unroll
61
+ * @param msg - message bytes to hash
62
+ * @returns Digest bytes.
63
+ * @example
64
+ * Hash a message with MD5.
65
+ * ```ts
66
+ * md5(new Uint8Array([97, 98, 99]));
67
+ * ```
68
+ */
69
+ export declare const md5: TRet<CHash>;
70
+ /**
71
+ * Internal RIPEMD-160 legacy hash class.
72
+ * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification.
73
+ */
74
+ export declare class _RIPEMD160 extends HashMD<_RIPEMD160> {
75
+ private h0;
76
+ private h1;
77
+ private h2;
78
+ private h3;
79
+ private h4;
80
+ constructor();
81
+ protected get(): [number, number, number, number, number];
82
+ protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void;
83
+ protected process(view: DataView, offset: number): void;
84
+ protected roundClean(): void;
85
+ destroy(): void;
86
+ }
87
+ /**
88
+ * RIPEMD-160 - a legacy hash function from 1990s.
89
+ * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point
90
+ * at the base RIPEMD-160 references.
91
+ * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html}
92
+ * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf}
93
+ * @param msg - message bytes to hash
94
+ * @returns Digest bytes.
95
+ * @example
96
+ * Hash a message with RIPEMD-160.
97
+ * ```ts
98
+ * ripemd160(new Uint8Array([97, 98, 99]));
99
+ * ```
100
+ */
101
+ export declare const ripemd160: TRet<CHash>;