forked from nodejs/webcrypto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithms.js
81 lines (68 loc) · 1.75 KB
/
algorithms.js
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
'use strict';
const { AES_CTR, AES_CBC, AES_GCM, AES_KW } = require('./algorithms/aes');
const { HKDF } = require('./algorithms/hkdf');
const { HMAC } = require('./algorithms/hmac');
const { PBKDF2 } = require('./algorithms/pbkdf2');
const { RSASSA_PKCS1, RSA_PSS } = require('./algorithms/rsa');
const { SHA_1, SHA_256, SHA_384, SHA_512 } = require('./algorithms/sha');
const { NotSupportedError } = require('./errors');
const algorithms = [
AES_CTR,
AES_CBC,
AES_GCM,
AES_KW,
HKDF,
HMAC,
PBKDF2,
RSASSA_PKCS1,
RSA_PSS,
SHA_1,
SHA_256,
SHA_384,
SHA_512
];
function objectFromArray(array, fn) {
const obj = {};
for (const val of array)
fn(obj, val);
return obj;
}
// Spec: https://www.w3.org/TR/WebCryptoAPI/#dfn-supportedAlgorithms
const supportedAlgorithms = objectFromArray([
// This corresponds to section 18.2.2 of the WebCrypto spec.
'encrypt',
'decrypt',
'sign',
'verify',
'deriveBits',
'wrapKey',
'unwrapKey',
'digest',
'generateKey',
'importKey',
'exportKey',
'get key length',
// The following APIs are for internal use only.
'get hash function',
'get hash block size'
], (opsByName, op) => {
opsByName[op] = objectFromArray(algorithms, (algsByName, alg) => {
if (typeof alg[op] === 'function')
algsByName[alg.name.toLowerCase()] = alg;
});
});
function getAlgorithm(alg, op) {
if (typeof alg !== 'string') {
if (typeof alg !== 'object')
throw new SyntaxError();
const { name } = alg;
if (typeof name !== 'string')
throw new SyntaxError();
return getAlgorithm(alg.name, op);
}
const impl = supportedAlgorithms[op][alg.toLowerCase()];
if (impl === undefined)
throw new NotSupportedError();
return impl;
}
module.exports.getAlgorithm = getAlgorithm;