@push.rocks/smartcrypto 3.2.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import { SmartCryptoError, createSmartCryptoError } from './smartcrypto.errors.js';
2
2
  import {
3
+ decodeDerElement,
3
4
  derTags,
4
5
  encodeDerBitString,
5
6
  encodeDerBoolean,
@@ -10,9 +11,16 @@ import {
10
11
  encodeDerSequence,
11
12
  encodeDerSmallInteger,
12
13
  encodeDerUnsignedInteger,
14
+ readDerBitString,
15
+ readDerOid,
16
+ readDerSequence,
17
+ readDerSmallInteger,
18
+ type IDerElement,
13
19
  } from './smartcrypto.der.js';
14
- import { getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
15
- import { encodePem } from './smartcrypto.pem.js';
20
+ import { createSha256Hasher } from './smartcrypto.hash.js';
21
+ import { encodeBase64, getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
22
+ import { decodeFirstPemBlock, encodePem } from './smartcrypto.pem.js';
23
+ import { decodeRsaPublicKey, encodeSubjectPublicKeyInfo } from './smartcrypto.rsa.js';
16
24
 
17
25
  /** The key a self-signed certificate is issued for, signed with SHA-256. */
18
26
  export type TSelfSignedCertificateKeyAlgorithm = 'RSA-2048' | 'ECDSA-P256';
@@ -28,8 +36,18 @@ export interface ISelfSignedCertificateOptions {
28
36
  notBefore?: Date;
29
37
  /** End of the validity period, truncated to whole seconds. Defaults to `notBefore` plus 365 days. */
30
38
  notAfter?: Date;
31
- /** Defaults to `RSA-2048`. */
39
+ /**
40
+ * Defaults to `RSA-2048`, or to `ECDSA-P256` when `privateKeyPem` is given; a
41
+ * supplied key requires `ECDSA-P256`.
42
+ */
32
43
  keyAlgorithm?: TSelfSignedCertificateKeyAlgorithm;
44
+ /**
45
+ * An existing ECDSA P-256 key as an unencrypted PKCS#8 `PRIVATE KEY` PEM, such
46
+ * as the `privateKeyPem` of an earlier certificate. The certificate is issued
47
+ * for this key, so its public key and pin stay the same across certificates.
48
+ * Omitted, a fresh key is generated.
49
+ */
50
+ privateKeyPem?: string;
33
51
  }
34
52
 
35
53
  export interface ISelfSignedCertificate {
@@ -52,6 +70,8 @@ interface ISelfSignedKeyProfile {
52
70
 
53
71
  const oids = {
54
72
  commonName: '2.5.4.3',
73
+ ecPublicKey: '1.2.840.10045.2.1',
74
+ prime256v1: '1.2.840.10045.3.1.7',
55
75
  basicConstraints: '2.5.29.19',
56
76
  keyUsage: '2.5.29.15',
57
77
  extendedKeyUsage: '2.5.29.37',
@@ -106,6 +126,7 @@ const keyProfiles: Record<TSelfSignedCertificateKeyAlgorithm, ISelfSignedKeyProf
106
126
  };
107
127
 
108
128
  const invalidArgument = () => createSmartCryptoError('INVALID_ARGUMENT');
129
+ const invalidKey = (detailArg?: string) => createSmartCryptoError('INVALID_KEY', detailArg);
109
130
 
110
131
  const isKeyAlgorithm = (valueArg: unknown): valueArg is TSelfSignedCertificateKeyAlgorithm =>
111
132
  valueArg === 'RSA-2048' || valueArg === 'ECDSA-P256';
@@ -240,14 +261,126 @@ const createSerialNumber = (): Uint8Array => {
240
261
  return encodeDerUnsignedInteger(serialNumber);
241
262
  };
242
263
 
264
+ // ========================================
265
+ // Keys
266
+ // ========================================
267
+ /**
268
+ * Imports an unencrypted PKCS#8 ECDSA P-256 private key and derives its public
269
+ * key. The algorithm identifier is checked before WebCrypto sees the key, so a
270
+ * key of another type or curve fails with a named `INVALID_KEY`.
271
+ */
272
+ const importEcdsaP256KeyPair = async (privateKeyPemArg: unknown): Promise<CryptoKeyPair> => {
273
+ if (typeof privateKeyPemArg !== 'string') {
274
+ throw invalidArgument();
275
+ }
276
+ const privateKeyInfo = decodeFirstPemBlock(privateKeyPemArg, ['PRIVATE KEY']).body;
277
+ try {
278
+ // PrivateKeyInfo / OneAsymmetricKey (RFC 5958): version, algorithm, privateKey, ...
279
+ const [version, algorithm] = readDerSequence(decodeDerElement(privateKeyInfo), 3, 5);
280
+ if (readDerSmallInteger(version) > 1) {
281
+ throw invalidKey();
282
+ }
283
+ const [algorithmOid, namedCurve] = readDerSequence(algorithm, 1, 2);
284
+ if (
285
+ readDerOid(algorithmOid) !== oids.ecPublicKey
286
+ || namedCurve?.tag !== derTags.oid
287
+ || readDerOid(namedCurve) !== oids.prime256v1
288
+ ) {
289
+ throw invalidKey('the private key is not an ECDSA P-256 key');
290
+ }
291
+ const subtle = getWebCrypto().subtle;
292
+ const ecdsaP256 = { name: 'ECDSA', namedCurve: 'P-256' };
293
+ let privateKey: CryptoKey;
294
+ try {
295
+ privateKey = await subtle.importKey('pkcs8', toArrayBuffer(privateKeyInfo), ecdsaP256, true, [
296
+ 'sign',
297
+ ]);
298
+ } catch {
299
+ throw invalidKey();
300
+ }
301
+ // WebCrypto exports an EC private key as a JWK with its public point (x, y).
302
+ const { kty, crv, x, y } = await subtle.exportKey('jwk', privateKey);
303
+ const publicKey = await subtle.importKey('jwk', { kty, crv, x, y }, ecdsaP256, true, ['verify']);
304
+ return { privateKey, publicKey };
305
+ } finally {
306
+ privateKeyInfo.fill(0);
307
+ }
308
+ };
309
+
310
+ const generateKeyPair = (profileArg: ISelfSignedKeyProfile): Promise<CryptoKeyPair> =>
311
+ getWebCrypto().subtle.generateKey(profileArg.generateParams, true, ['sign', 'verify']);
312
+
313
+ // ========================================
314
+ // Public-key pins
315
+ // ========================================
316
+ /** Requires a DER `SubjectPublicKeyInfo` and returns it unchanged. */
317
+ const requireSubjectPublicKeyInfo = (derArg: Uint8Array): Uint8Array => {
318
+ const [algorithm, subjectPublicKey] = readDerSequence(decodeDerElement(derArg), 2, 2);
319
+ readDerOid(readDerSequence(algorithm, 1, 2)[0]);
320
+ readDerBitString(subjectPublicKey);
321
+ return derArg;
322
+ };
323
+
324
+ /** The DER `subjectPublicKeyInfo` of a DER X.509 certificate (RFC 5280 4.1). */
325
+ const readCertificateSubjectPublicKeyInfo = (derArg: Uint8Array): Uint8Array => {
326
+ const [tbsCertificate] = readDerSequence(decodeDerElement(derArg), 3, 3);
327
+ // version [0] (optional), serialNumber, signature, issuer, validity, subject, subjectPublicKeyInfo, ...
328
+ const fields: IDerElement[] = readDerSequence(tbsCertificate, 6, 10);
329
+ const subjectPublicKeyInfo =
330
+ fields[fields[0].tag === derTags.contextSpecificConstructed0 ? 6 : 5];
331
+ if (!subjectPublicKeyInfo) {
332
+ throw invalidKey();
333
+ }
334
+ // The strict DER reader admits one encoding per element, so re-encoding yields the original bytes.
335
+ return requireSubjectPublicKeyInfo(
336
+ encodeDerElement(subjectPublicKeyInfo.tag, subjectPublicKeyInfo.content),
337
+ );
338
+ };
339
+
340
+ const decodeHex = (hexArg: string): Uint8Array =>
341
+ new Uint8Array((hexArg.match(/../g) ?? []).map((byteArg) => parseInt(byteArg, 16)));
342
+
343
+ /**
344
+ * Computes the RFC 7469 `pin-sha256` of a public key: the SHA-256 digest of the
345
+ * DER `SubjectPublicKeyInfo`, as standard padded base64 (44 characters). The key
346
+ * is given as DER `SubjectPublicKeyInfo` bytes (WebCrypto `exportKey('spki')`,
347
+ * Node.js `KeyObject.export({ type: 'spki', format: 'der' })`), or as the first
348
+ * PEM block of a string: `PUBLIC KEY` (SPKI), `RSA PUBLIC KEY` (PKCS#1, pinned as
349
+ * its rsaEncryption SPKI) or `CERTIFICATE` (the certificate's subject public
350
+ * key). Synchronous, so it fits TLS identity callbacks. Malformed keys fail
351
+ * with `INVALID_KEY`, other input types with `INVALID_ARGUMENT`.
352
+ */
353
+ export const computePublicKeyPinSha256 = (publicKeyArg: string | Uint8Array): string => {
354
+ let subjectPublicKeyInfo: Uint8Array;
355
+ if (publicKeyArg instanceof Uint8Array) {
356
+ subjectPublicKeyInfo = requireSubjectPublicKeyInfo(publicKeyArg);
357
+ } else if (typeof publicKeyArg === 'string') {
358
+ const block = decodeFirstPemBlock(publicKeyArg, ['PUBLIC KEY', 'RSA PUBLIC KEY', 'CERTIFICATE']);
359
+ subjectPublicKeyInfo =
360
+ block.type === 'PUBLIC KEY'
361
+ ? requireSubjectPublicKeyInfo(block.body)
362
+ : block.type === 'RSA PUBLIC KEY'
363
+ ? encodeSubjectPublicKeyInfo(decodeRsaPublicKey(block.body))
364
+ : readCertificateSubjectPublicKeyInfo(block.body);
365
+ } else {
366
+ throw invalidArgument();
367
+ }
368
+ return encodeBase64(decodeHex(createSha256Hasher().update(subjectPublicKeyInfo).digest()));
369
+ };
370
+
371
+ // ========================================
372
+ // Certificate creation
373
+ // ========================================
243
374
  /**
244
375
  * Creates a self-signed X.509 v3 end-entity certificate and its key with
245
376
  * WebCrypto, for TLS servers that need a certificate without a CA, such as
246
377
  * test servers and fallback certificates. The certificate carries
247
378
  * `basicConstraints` CA:FALSE and `keyUsage` (both critical),
248
379
  * `extendedKeyUsage` serverAuth, and the requested subject alternative names.
249
- * Invalid options fail with `INVALID_ARGUMENT`; WebCrypto failures with
250
- * `CRYPTO_OPERATION_FAILED`.
380
+ * With `privateKeyPem` the certificate is issued for that ECDSA P-256 key
381
+ * instead of a fresh one. Invalid options fail with `INVALID_ARGUMENT`, a
382
+ * supplied key that is malformed or not ECDSA P-256 with `INVALID_KEY`, and
383
+ * WebCrypto failures with `CRYPTO_OPERATION_FAILED`.
251
384
  */
252
385
  export const createSelfSignedCertificate = async (
253
386
  optionsArg: ISelfSignedCertificateOptions,
@@ -256,8 +389,9 @@ export const createSelfSignedCertificate = async (
256
389
  throw invalidArgument();
257
390
  }
258
391
  const commonName = requireCommonName(optionsArg.commonName);
259
- const keyAlgorithm = optionsArg.keyAlgorithm ?? 'RSA-2048';
260
- if (!isKeyAlgorithm(keyAlgorithm)) {
392
+ const suppliesKey = optionsArg.privateKeyPem !== undefined;
393
+ const keyAlgorithm = optionsArg.keyAlgorithm ?? (suppliesKey ? 'ECDSA-P256' : 'RSA-2048');
394
+ if (!isKeyAlgorithm(keyAlgorithm) || (suppliesKey && keyAlgorithm !== 'ECDSA-P256')) {
261
395
  throw invalidArgument();
262
396
  }
263
397
  const profile = keyProfiles[keyAlgorithm];
@@ -278,7 +412,9 @@ export const createSelfSignedCertificate = async (
278
412
  const subtle = getWebCrypto().subtle;
279
413
  let privateKeyInfo: Uint8Array | undefined;
280
414
  try {
281
- const keyPair = await subtle.generateKey(profile.generateParams, true, ['sign', 'verify']);
415
+ const keyPair = suppliesKey
416
+ ? await importEcdsaP256KeyPair(optionsArg.privateKeyPem)
417
+ : await generateKeyPair(profile);
282
418
  const subjectPublicKeyInfo = new Uint8Array(await subtle.exportKey('spki', keyPair.publicKey));
283
419
  const extensions = [
284
420
  encodeExtension(oids.basicConstraints, true, encodeDerSequence()),