-
Notifications
You must be signed in to change notification settings - Fork 2
/
generation.ts
57 lines (50 loc) · 1.88 KB
/
generation.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
import { ECDHCurveName, HashingAlgorithm, RSAModulus } from '../algorithms';
import { NODE_ENGINE } from '../pkijs';
import { derDeserializeRSAPublicKey, derSerializePublicKey } from './serialisation';
export interface RSAKeyGenOptions {
readonly modulus: RSAModulus;
readonly hashingAlgorithm: HashingAlgorithm;
}
/**
* Generate an RSA-PSS key pair.
*
* @param options The RSA key generation options
* @throws Error If the modulus or the hashing algorithm is disallowed by RS-018.
*/
export async function generateRSAKeyPair(
options: Partial<RSAKeyGenOptions> = {},
): Promise<CryptoKeyPair> {
const modulus = options.modulus ?? 2048;
if (modulus < 2048) {
throw new Error(`RSA modulus must be => 2048 per RS-018 (got ${modulus})`);
}
const hashingAlgorithm = options.hashingAlgorithm ?? 'SHA-256';
// RS-018 disallows MD5 and SHA-1, but only SHA-1 is supported in WebCrypto
if ((hashingAlgorithm as any) === 'SHA-1') {
throw new Error('SHA-1 is disallowed by RS-018');
}
const algorithm = NODE_ENGINE.getAlgorithmParameters('RSA-PSS', 'generateKey');
const rsaAlgorithm = algorithm.algorithm as RsaHashedKeyAlgorithm;
// tslint:disable-next-line:no-object-mutation
rsaAlgorithm.hash.name = hashingAlgorithm;
// tslint:disable-next-line:no-object-mutation
rsaAlgorithm.modulusLength = modulus;
return NODE_ENGINE.generateKey(rsaAlgorithm, true, algorithm.usages);
}
/**
* Generate ECDH key pair.
*
* @param curveName
*/
export async function generateECDHKeyPair(
curveName: ECDHCurveName = 'P-256',
): Promise<CryptoKeyPair> {
return NODE_ENGINE.generateKey({ name: 'ECDH', namedCurve: curveName }, true, [
'deriveBits',
'deriveKey',
]);
}
export async function getRSAPublicKeyFromPrivate(privateKey: CryptoKey): Promise<CryptoKey> {
const publicKeyDer = await derSerializePublicKey(privateKey);
return derDeserializeRSAPublicKey(publicKeyDer);
}