-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathhash.ts
More file actions
336 lines (306 loc) · 9.61 KB
/
hash.ts
File metadata and controls
336 lines (306 loc) · 9.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import { Stream } from 'readable-stream';
import { NitroModules } from 'react-native-nitro-modules';
import type { TransformOptions } from 'readable-stream';
import { Buffer } from '@craftzdog/react-native-buffer';
import type { Hash as NativeHash } from './specs/hash.nitro';
import type {
BinaryLike,
Encoding,
BufferLike,
SubtleAlgorithm,
} from './utils';
import {
ab2str,
binaryLikeToArrayBuffer,
bufferLikeToArrayBuffer,
} from './utils';
import { validateMaxBufferLength } from './utils/validation';
import { lazyDOMException } from './utils/errors';
import { normalizeHashName } from './utils/hashnames';
class HashUtils {
private static native = NitroModules.createHybridObject<NativeHash>('Hash');
public static getSupportedHashAlgorithms(): string[] {
return this.native.getSupportedHashAlgorithms();
}
}
export function getHashes() {
return HashUtils.getSupportedHashAlgorithms();
}
interface HashOptions extends TransformOptions {
/**
* For XOF hash functions such as `shake256`, the
* outputLength option can be used to specify the desired output length in bytes.
*/
outputLength?: number | undefined;
}
interface HashArgs {
algorithm: string;
options?: HashOptions;
native?: NativeHash;
}
class Hash extends Stream.Transform {
private algorithm: string;
private options: HashOptions;
private native: NativeHash;
private validate(args: HashArgs) {
if (typeof args.algorithm !== 'string' || args.algorithm.length === 0)
throw new Error('Algorithm must be a non-empty string');
if (
args.options?.outputLength !== undefined &&
args.options.outputLength < 0
)
throw new Error('Output length must be a non-negative number');
if (
args.options?.outputLength !== undefined &&
typeof args.options.outputLength !== 'number'
)
throw new Error('Output length must be a number');
}
/**
* @internal use `createHash()` instead
*/
private constructor(args: HashArgs) {
super(args.options);
this.validate(args);
this.algorithm = args.algorithm;
this.options = args.options ?? {};
if (args.native) {
this.native = args.native;
return;
}
this.native = NitroModules.createHybridObject<NativeHash>('Hash');
this.native.createHash(this.algorithm, this.options.outputLength);
}
/**
* Updates the hash content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v1.0.0
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): Hash;
update(data: BinaryLike, inputEncoding: Encoding): Buffer;
update(data: BinaryLike, inputEncoding?: Encoding): Hash | Buffer {
const defaultEncoding: Encoding = 'utf8';
inputEncoding = inputEncoding ?? defaultEncoding;
// OPTIMIZED PATH: Pass UTF-8 strings directly to native without conversion
if (typeof data === 'string' && inputEncoding === 'utf8') {
this.native.update(data);
} else {
this.native.update(binaryLikeToArrayBuffer(data, inputEncoding));
}
return this; // to support chaining syntax createHash().update().digest()
}
/**
* Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method).
* If `encoding` is provided a string will be returned; otherwise
* a `Buffer` is returned.
*
* The `Hash` object can not be used again after `hash.digest()` method has been
* called. Multiple calls will cause an error to be thrown.
* @since v1.0.0
* @param encoding The `encoding` of the return value.
*/
digest(): Buffer;
digest(encoding: Encoding): string;
digest(encoding?: Encoding): Buffer | string {
const nativeDigest = this.native.digest(encoding);
if (encoding && encoding !== 'buffer') {
return ab2str(nativeDigest, encoding);
}
return Buffer.from(nativeDigest);
}
/**
* Creates a new `Hash` object that contains a deep copy of the internal state
* of the current `Hash` object.
*
* The optional `options` argument controls stream behavior. For XOF hash
* functions such as `'shake256'`, the `outputLength` option can be used to
* specify the desired output length in bytes.
*
* An error is thrown when an attempt is made to copy the `Hash` object after
* its `hash.digest()` method has been called.
*
* ```js
* // Calculate a rolling hash.
* import { createHash } from 'react-native-quick-crypto';
*
* const hash = createHash('sha256');
*
* hash.update('one');
* console.log(hash.copy().digest('hex'));
*
* hash.update('two');
* console.log(hash.copy().digest('hex'));
*
* hash.update('three');
* console.log(hash.copy().digest('hex'));
*
* // Etc.
* ```
* @since v1.0.0
* @param options `stream.transform` options
*/
copy(): Hash;
copy(options: HashOptions): Hash;
copy(options?: HashOptions): Hash {
const newOptions = options ?? this.options;
const newNativeHash = this.native.copy(newOptions.outputLength);
const hash = new Hash({
algorithm: this.algorithm,
options: newOptions,
native: newNativeHash,
});
return hash;
}
/**
* Returns the OpenSSL version string
* @since v1.0.0
*/
getOpenSSLVersion(): string {
return this.native.getOpenSSLVersion();
}
// Stream interface — surface synchronous errors via the callback so
// they emit as stream 'error' events instead of throwing out of the
// Transform plumbing (which would crash the host pipeline).
_transform(
chunk: BinaryLike,
encoding: BufferEncoding,
callback: (err?: Error | null) => void,
) {
try {
this.update(chunk, encoding as Encoding);
callback();
} catch (err) {
callback(err as Error);
}
}
_flush(callback: (err?: Error | null) => void) {
try {
this.push(this.digest());
callback();
} catch (err) {
callback(err as Error);
}
}
}
/**
* Creates and returns a `Hash` object that can be used to generate hash digests
* using the given `algorithm`. Optional `options` argument controls stream
* behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
* can be used to specify the desired output length in bytes.
*
* The `algorithm` is dependent on the available algorithms supported by the
* version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
* On recent releases of OpenSSL, `openssl list -digest-algorithms` will
* display the available digest algorithms.
*
* Example: generating the sha256 sum of a file
*
* ```js
* import crypto from 'react-native-quick-crypto';
*
* const hash = crypto.createHash('sha256').update('Test123').digest('hex');
* console.log('SHA-256 of "Test123":', hash);
* ```
* @since v1.0.0
* @param options `stream.transform` options
*/
export function createHash(algorithm: string, options?: HashOptions): Hash {
// @ts-expect-error private constructor
return new Hash({
algorithm,
options,
});
}
// Implementation for WebCrypto subtle.digest()
/**
* Asynchronous digest function for WebCrypto SubtleCrypto API
* @param algorithm The hash algorithm to use
* @param data The data to hash
* @returns Promise resolving to the hash digest as ArrayBuffer
*/
export const asyncDigest = async (
algorithm: SubtleAlgorithm,
data: BufferLike,
): Promise<ArrayBuffer> => {
validateMaxBufferLength(data, 'data');
const name = algorithm.name;
if (
name === 'SHA-1' ||
name === 'SHA-256' ||
name === 'SHA-384' ||
name === 'SHA-512' ||
name === 'SHA3-256' ||
name === 'SHA3-384' ||
name === 'SHA3-512'
) {
return internalDigest(algorithm, data);
}
if (name === 'cSHAKE128' || name === 'cSHAKE256') {
// CShakeParams.outputLength is required (in bits) per the WICG modern-algos
// spec, renamed from `length` (commit ab8dc2b84c2). Mirror Node's
// hash.js:223-228 / webidl.js:570-595.
if (
typeof algorithm.outputLength !== 'number' ||
algorithm.outputLength <= 0
) {
throw lazyDOMException(
'CShakeParams.outputLength is required',
'OperationError',
);
}
if (algorithm.outputLength % 8) {
throw lazyDOMException(
'Unsupported CShakeParams outputLength',
'NotSupportedError',
);
}
return internalDigest(algorithm, data, algorithm.outputLength / 8);
}
throw lazyDOMException(
`Unrecognized algorithm name: ${name}`,
'NotSupportedError',
);
};
const internalDigest = (
algorithm: SubtleAlgorithm,
data: BufferLike,
outputLength?: number,
): ArrayBuffer => {
const normalizedHashName = normalizeHashName(algorithm.name);
const hash = createHash(
normalizedHashName,
outputLength ? { outputLength } : undefined,
);
hash.update(bufferLikeToArrayBuffer(data));
const result = hash.digest();
const arrayBuffer = new ArrayBuffer(result.length);
const view = new Uint8Array(arrayBuffer);
view.set(result);
return arrayBuffer;
};
export function hash(
algorithm: string,
data: BinaryLike,
outputEncoding: Encoding,
): string;
export function hash(algorithm: string, data: BinaryLike): Buffer;
export function hash(
algorithm: string,
data: BinaryLike,
outputEncoding?: Encoding,
): string | Buffer {
const h = createHash(algorithm);
h.update(data);
return outputEncoding ? h.digest(outputEncoding) : h.digest();
}
export const hashExports = {
createHash,
getHashes,
hash,
asyncDigest,
};