-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwkImporter.js
65 lines (61 loc) · 2.16 KB
/
jwkImporter.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
import { ASN_OID, decodeDER } from '../utils/asn1.js';
import { derFromPrivateKeyInformation } from '../utils/certificate.js';
/**
* Automatically suggest an importKey algorithm
* @see https://datatracker.ietf.org/doc/html/rfc5208#section-5
* @see https://datatracker.ietf.org/doc/html/rfc2313#section-11
* @param {string|Uint8Array} privateKeyInformation pkcs8
* @return {Parameters<SubtleCrypto['importKey']>[2]}
*/
export function suggestImportKeyAlgorithm(privateKeyInformation) {
const der = derFromPrivateKeyInformation(privateKeyInformation);
const [
[privateKeyInfoType, [
[versionType, version],
algorithmIdentifierSequence,
[privateKeyType, privateKey], // Skip validation
]],
] = decodeDER(der);
if (privateKeyInfoType !== 'SEQUENCE') throw new Error('Invalid Private Key Information');
if (versionType !== 'INTEGER') throw new Error('Invalid Private Key Information');
if (version !== 0) throw new Error('Unsupported Private Key Information Version');
const [algorithmIdentifierSequenceType, algorithmIdentifierSequenceValues] = algorithmIdentifierSequence;
if (algorithmIdentifierSequenceType !== 'SEQUENCE') throw new Error('Invalid Private Key Information');
/** @type {Set<string>} */
const objectIdentifiers = new Set();
for (const [type, value] of algorithmIdentifierSequenceValues) {
if (type === 'OBJECT_IDENTIFIER') {
objectIdentifiers.add(value);
}
}
if (objectIdentifiers.has(ASN_OID.rsaEncryption)) {
return {
name: 'RSASSA-PKCS1-v1_5', // RSA-PSS isn't supported by LetsEncrypt
hash: { name: 'SHA-256' },
};
}
if (objectIdentifiers.has(ASN_OID.ecPublicKey)) {
if (objectIdentifiers.has(ASN_OID.secp256r1)) {
return {
name: 'ECDSA',
namedCurve: 'P-256',
hash: { name: 'SHA-256' },
};
}
if (objectIdentifiers.has(ASN_OID.secp384r1)) {
return {
name: 'ECDSA',
namedCurve: 'P-384',
hash: { name: 'SHA-384' },
};
}
if (objectIdentifiers.has(ASN_OID.secp521r1)) {
return {
name: 'ECDSA',
namedCurve: 'P-521',
hash: { name: 'SHA-512' },
};
}
}
return null;
}