deno.land / std@0.166.0 / crypto / mod.ts

نووسراو ببینە
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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
/** * Extensions to the * [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API) * supporting additional encryption APIs. * * Provides additional digest algorithms that are not part of the WebCrypto * standard as well as a `subtle.digest` and `subtle.digestSync` methods. It * also provide a `subtle.timingSafeEqual()` method to compare array buffers * or data views in a way that isn't prone to timing based attacks. * * The "polyfill" delegates to `WebCrypto` where possible. * * The {@linkcode KeyStack} export implements the {@linkcode KeyRing} interface * for managing rotatable keys for signing data to prevent tampering, like with * HTTP cookies. * * @module */
import { DigestAlgorithm as WasmDigestAlgorithm, digestAlgorithms as wasmDigestAlgorithms, instantiateWasm,} from "./_wasm/mod.ts";import { timingSafeEqual } from "./timing_safe_equal.ts";import { fnv } from "./_fnv/index.ts";
export { type Data, type Key, KeyStack } from "./keystack.ts";export { toHashString } from "./util.ts";
/** * A copy of the global WebCrypto interface, with methods bound so they're * safe to re-export. */const webCrypto = ((crypto) => ({ getRandomValues: crypto.getRandomValues?.bind(crypto), randomUUID: crypto.randomUUID?.bind(crypto), subtle: { decrypt: crypto.subtle?.decrypt?.bind(crypto.subtle), deriveBits: crypto.subtle?.deriveBits?.bind(crypto.subtle), deriveKey: crypto.subtle?.deriveKey?.bind(crypto.subtle), digest: crypto.subtle?.digest?.bind(crypto.subtle), encrypt: crypto.subtle?.encrypt?.bind(crypto.subtle), exportKey: crypto.subtle?.exportKey?.bind(crypto.subtle), generateKey: crypto.subtle?.generateKey?.bind(crypto.subtle), importKey: crypto.subtle?.importKey?.bind(crypto.subtle), sign: crypto.subtle?.sign?.bind(crypto.subtle), unwrapKey: crypto.subtle?.unwrapKey?.bind(crypto.subtle), verify: crypto.subtle?.verify?.bind(crypto.subtle), wrapKey: crypto.subtle?.wrapKey?.bind(crypto.subtle), },}))(globalThis.crypto);
const bufferSourceBytes = (data: BufferSource | unknown) => { let bytes: Uint8Array | undefined; if (data instanceof Uint8Array) { bytes = data; } else if (ArrayBuffer.isView(data)) { bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); } else if (data instanceof ArrayBuffer) { bytes = new Uint8Array(data); } return bytes;};
/** Extensions to the web standard `SubtleCrypto` interface. */export interface StdSubtleCrypto extends SubtleCrypto { /** * Returns a new `Promise` object that will digest `data` using the specified * `AlgorithmIdentifier`. */ digest( algorithm: DigestAlgorithm, data: BufferSource | AsyncIterable<BufferSource> | Iterable<BufferSource>, ): Promise<ArrayBuffer>;
/** * Returns a ArrayBuffer with the result of digesting `data` using the * specified `AlgorithmIdentifier`. */ digestSync( algorithm: DigestAlgorithm, data: BufferSource | Iterable<BufferSource>, ): ArrayBuffer;
/** Compare to array buffers or data views in a way that timing based attacks * cannot gain information about the platform. */ timingSafeEqual( a: ArrayBufferLike | DataView, b: ArrayBufferLike | DataView, ): boolean;}
/** Extensions to the Web {@linkcode Crypto} interface. */export interface StdCrypto extends Crypto { readonly subtle: StdSubtleCrypto;}
/** * An wrapper for WebCrypto adding support for additional non-standard * algorithms, but delegating to the runtime WebCrypto implementation whenever * possible. */const stdCrypto: StdCrypto = ((x) => x)({ ...webCrypto, subtle: { ...webCrypto.subtle,
/** * Polyfills stream support until the Web Crypto API does so: * @see {@link https://github.com/wintercg/proposal-webcrypto-streams} */ async digest( algorithm: DigestAlgorithm, data: BufferSource | AsyncIterable<BufferSource> | Iterable<BufferSource>, ): Promise<ArrayBuffer> { const { name, length } = normalizeAlgorithm(algorithm); const bytes = bufferSourceBytes(data);
if (FNVAlgorithms.includes(name)) { return fnv(name, bytes); }
// We delegate to WebCrypto whenever possible, if ( // if the algorithm is supported by the WebCrypto standard, (webCryptoDigestAlgorithms as readonly string[]).includes(name) && // and the data is a single buffer, bytes ) { return webCrypto.subtle.digest(algorithm, bytes); } else if (wasmDigestAlgorithms.includes(name as WasmDigestAlgorithm)) { if (bytes) { // Otherwise, we use our bundled Wasm implementation via digestSync // if it supports the algorithm. return stdCrypto.subtle.digestSync(algorithm, bytes); } else if ((data as Iterable<BufferSource>)[Symbol.iterator]) { return stdCrypto.subtle.digestSync( algorithm, data as Iterable<BufferSource>, ); } else if ( (data as AsyncIterable<BufferSource>)[Symbol.asyncIterator] ) { const wasmCrypto = instantiateWasm(); const context = new wasmCrypto.DigestContext(name); for await (const chunk of data as AsyncIterable<BufferSource>) { const chunkBytes = bufferSourceBytes(chunk); if (!chunkBytes) { throw new TypeError("data contained chunk of the wrong type"); } context.update(chunkBytes); } return context.digestAndDrop(length).buffer; } else { throw new TypeError( "data must be a BufferSource or [Async]Iterable<BufferSource>", ); } } else if (webCrypto.subtle?.digest) { // (TypeScript type definitions prohibit this case.) If they're trying // to call an algorithm we don't recognize, pass it along to WebCrypto // in case it's a non-standard algorithm supported by the the runtime // they're using. return webCrypto.subtle.digest( algorithm, (data as unknown) as Uint8Array, ); } else { throw new TypeError(`unsupported digest algorithm: ${algorithm}`); } },
digestSync( algorithm: DigestAlgorithm, data: BufferSource | Iterable<BufferSource>, ): ArrayBuffer { algorithm = normalizeAlgorithm(algorithm);
const bytes = bufferSourceBytes(data);
if (FNVAlgorithms.includes(algorithm.name)) { return fnv(algorithm.name, bytes); }
const wasmCrypto = instantiateWasm(); if (bytes) { return wasmCrypto.digest(algorithm.name, bytes, algorithm.length) .buffer; } else if ((data as Iterable<BufferSource>)[Symbol.iterator]) { const context = new wasmCrypto.DigestContext(algorithm.name); for (const chunk of data as Iterable<BufferSource>) { const chunkBytes = bufferSourceBytes(chunk); if (!chunkBytes) { throw new TypeError("data contained chunk of the wrong type"); } context.update(chunkBytes); } return context.digestAndDrop(algorithm.length).buffer; } else { throw new TypeError( "data must be a BufferSource or Iterable<BufferSource>", ); } },
// TODO(@kitsonk): rework when https://github.com/w3c/webcrypto/issues/270 resolved timingSafeEqual, },});
const FNVAlgorithms = ["FNV32", "FNV32A", "FNV64", "FNV64A"];
/** Digest algorithms supported by WebCrypto. */const webCryptoDigestAlgorithms = [ "SHA-384", "SHA-256", "SHA-512", // insecure (length-extendable and collidable): "SHA-1",] as const;
export type FNVAlgorithms = "FNV32" | "FNV32A" | "FNV64" | "FNV64A";export type DigestAlgorithmName = WasmDigestAlgorithm | FNVAlgorithms;
export type DigestAlgorithmObject = { name: DigestAlgorithmName; length?: number;};
export type DigestAlgorithm = DigestAlgorithmName | DigestAlgorithmObject;
const normalizeAlgorithm = (algorithm: DigestAlgorithm) => ((typeof algorithm === "string") ? { name: algorithm.toUpperCase() } : { ...algorithm, name: algorithm.name.toUpperCase(), }) as DigestAlgorithmObject;
export { stdCrypto as crypto };
std

Version Info

Tagged at
a year ago