-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpemPublicToCrypto.ts
More file actions
203 lines (190 loc) · 6.42 KB
/
Copy pathpemPublicToCrypto.ts
File metadata and controls
203 lines (190 loc) · 6.42 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
/**
*
* Copyright (c) 2016 SafeBash
* Cryptography consultant: Andrew Kozlik, Ph.D.
*
* @link https://github.com/safebash/opencrypto
*
*/
/**
* MIT License
*
* Copyright (c) 2016 SafeBash
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import * as base64 from '../encodings/base64.js';
import { importX509 } from 'jose';
import { encodeArrayBuffer as hexEncodeArrayBuffer } from '../encodings/hex.js';
import { ConfigurationError, TdfError } from '../errors.js';
import { NamedCurve } from './enums.js';
// OID constants for algorithm detection (hex-encoded ASN.1 OIDs)
export const RSA_OID = '06092a864886f70d010101';
export const EC_OID = '06072a8648ce3d0201';
export const P256_OID = '06082a8648ce3d030107';
export const P384_OID = '06052b81040022';
export const P521_OID = '06052b81040023';
// NIST CSRC OID arc 2.16.840.1.101.3.4.4.{2,3} = id-alg-ml-kem-{768,1024}
export const ML_KEM_768_OID = '0609608648016503040402';
export const ML_KEM_1024_OID = '0609608648016503040403';
const SHA_512 = 'SHA-512';
const SPKI = 'spki';
const CERT_BEGIN = '-----BEGIN CERTIFICATE-----';
const CERT_END = '-----END CERTIFICATE-----';
const ECDH = 'ECDH';
const ECDSA = 'ECDSA';
const RSA_OAEP = 'RSA-OAEP';
const RSA_PSS = 'RSA-PSS';
export type AlgorithmName = typeof ECDH | typeof ECDSA | typeof RSA_OAEP | typeof RSA_PSS;
interface PemPublicToCryptoOptions {
name?: string;
hash?: string;
usages?: KeyUsage[];
isExtractable: boolean;
}
function guessKeyUsages(algorithmName: AlgorithmName, usages?: KeyUsage[]): KeyUsage[] {
if (usages) return usages;
switch (algorithmName) {
case ECDSA:
return ['verify'];
case RSA_OAEP:
return ['encrypt', 'wrapKey'];
case RSA_PSS:
return ['verify'];
case ECDH:
default:
return [];
}
}
export function guessAlgorithmName(hex: string, algorithmName?: string): AlgorithmName {
if (hex.includes(EC_OID)) {
if (!algorithmName || algorithmName === ECDH) {
return ECDH;
} else if (algorithmName === ECDSA) {
return ECDSA;
}
} else if (hex.includes(RSA_OID)) {
if (!algorithmName || algorithmName === RSA_OAEP) {
return RSA_OAEP;
} else if (algorithmName === RSA_PSS) {
return RSA_PSS;
}
}
throw new TypeError(`Invalid public key, ${algorithmName}`);
}
export function guessCurveName(hex: string): NamedCurve {
if (hex.includes(P256_OID)) {
return NamedCurve.P256;
} else if (hex.includes(P384_OID)) {
return NamedCurve.P384;
} else if (hex.includes(P521_OID)) {
return NamedCurve.P521;
}
throw new TdfError('Unsupported curve name or invalid key');
}
/**
*
* Converts asymmetric public key from PEM to CryptoKey
* - publicKey {String} default: "undefined" PEM public key
* - options {Object} default: (depends on algorithm)
* -- ECDH: { name: 'ECDH', usages: [], isExtractable: true }
* -- ECDSA: { name: 'ECDSA', usages: ['verify'], isExtractable: true }
* -- RSA-OAEP: { name: 'RSA-OAEP', hash: { name: 'SHA-512' }, usages: ['encrypt', 'wrapKey'], isExtractable: true }
* -- RSA-PSS: { name: 'RSA-PSS', hash: { name: 'SHA-512' }, usages: ['verify'], isExtractable: true }
*/
export async function pemPublicToCrypto(
pem: string,
options: PemPublicToCryptoOptions = {
isExtractable: true,
}
): Promise<CryptoKey> {
pem = pem.replace('-----BEGIN PUBLIC KEY-----', '');
pem = pem.replace('-----END PUBLIC KEY-----', '');
const b64 = pem.replace(/\s/g, '');
const arrayBuffer = base64.decodeArrayBuffer(b64);
const hex = hexEncodeArrayBuffer(arrayBuffer);
const algorithmName = guessAlgorithmName(hex, options.name);
const keyUsages = guessKeyUsages(algorithmName, options.usages);
if (algorithmName === ECDH || algorithmName === ECDSA) {
const namedCurve = guessCurveName(hex);
return crypto.subtle.importKey(
SPKI,
arrayBuffer,
{
name: algorithmName,
namedCurve,
},
options.isExtractable,
keyUsages
);
} else if (algorithmName === RSA_OAEP || algorithmName === RSA_PSS) {
return crypto.subtle.importKey(
SPKI,
arrayBuffer,
{
name: algorithmName,
hash: {
name: options.hash || SHA_512,
},
},
options.isExtractable,
keyUsages
);
} else {
throw new TypeError('Invalid public key');
}
}
/**
* Detect JWS algorithm from hex-encoded key/certificate data.
* Look up JWK algorithm at https://github.com/panva/jose/issues/210
*/
export function toJwsAlg(hex: string) {
const a = guessAlgorithmName(hex);
if (a === ECDH) {
return 'ECDH-ES';
} else if (a === ECDSA) {
switch (guessCurveName(hex)) {
case NamedCurve.P256:
return 'ES256';
case NamedCurve.P384:
return 'ES384';
case NamedCurve.P521:
return 'ES512';
}
} else if (a === RSA_OAEP) {
return 'RS512';
} else {
return 'RSA-OAEP-512';
}
}
export async function pemCertToCrypto(
pem: string,
options: PemPublicToCryptoOptions = {
isExtractable: true,
}
): Promise<CryptoKey> {
let crt = pem.replace(CERT_BEGIN, '');
crt = crt.replace(CERT_END, '');
const b64 = crt.replace(/\s/g, '');
const arrayBuffer = base64.decodeArrayBuffer(b64);
const hex = hexEncodeArrayBuffer(arrayBuffer);
const jwsAlg = toJwsAlg(hex);
const key = await importX509(pem, jwsAlg, { extractable: options.isExtractable });
const { type } = key;
if (type !== 'public') {
throw new ConfigurationError('unpublic');
}
return key;
}