@push.rocks/smartcrypto 2.5.0 → 3.1.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.
Files changed (43) hide show
  1. package/.smartconfig.json +0 -1
  2. package/dist_ts/00_commitinfo_data.js +1 -1
  3. package/dist_ts/index.d.ts +2 -2
  4. package/dist_ts/index.js +2 -3
  5. package/dist_ts/smartcrypto.classes.keypair.d.ts +1 -0
  6. package/dist_ts/smartcrypto.classes.keypair.js +34 -15
  7. package/dist_ts/smartcrypto.classes.privatekey.d.ts +26 -3
  8. package/dist_ts/smartcrypto.classes.privatekey.js +93 -14
  9. package/dist_ts/smartcrypto.classes.publickey.d.ts +20 -7
  10. package/dist_ts/smartcrypto.classes.publickey.js +59 -45
  11. package/dist_ts/smartcrypto.classes.smartcrypto.js +1 -2
  12. package/dist_ts/smartcrypto.der.d.ts +55 -0
  13. package/dist_ts/smartcrypto.der.js +207 -0
  14. package/dist_ts/smartcrypto.internal.d.ts +1 -0
  15. package/dist_ts/smartcrypto.internal.js +4 -3
  16. package/dist_ts/smartcrypto.openssh.d.ts +8 -0
  17. package/dist_ts/smartcrypto.openssh.js +51 -0
  18. package/dist_ts/smartcrypto.pem.d.ts +16 -0
  19. package/dist_ts/smartcrypto.pem.js +50 -0
  20. package/dist_ts/smartcrypto.pkcs8.d.ts +4 -6
  21. package/dist_ts/smartcrypto.pkcs8.js +33 -95
  22. package/dist_ts/smartcrypto.rsa.d.ts +30 -0
  23. package/dist_ts/smartcrypto.rsa.js +153 -0
  24. package/dist_ts/smartcrypto.x509.d.ts +32 -0
  25. package/dist_ts/smartcrypto.x509.js +222 -0
  26. package/package.json +2 -7
  27. package/readme.md +75 -8
  28. package/ts/00_commitinfo_data.ts +1 -1
  29. package/ts/index.ts +5 -4
  30. package/ts/smartcrypto.classes.keypair.ts +34 -17
  31. package/ts/smartcrypto.classes.privatekey.ts +111 -19
  32. package/ts/smartcrypto.classes.publickey.ts +83 -78
  33. package/ts/smartcrypto.classes.smartcrypto.ts +0 -1
  34. package/ts/smartcrypto.der.ts +248 -0
  35. package/ts/smartcrypto.internal.ts +5 -2
  36. package/ts/smartcrypto.openssh.ts +98 -0
  37. package/ts/smartcrypto.pem.ts +61 -0
  38. package/ts/smartcrypto.pkcs8.ts +63 -121
  39. package/ts/smartcrypto.rsa.ts +234 -0
  40. package/ts/smartcrypto.x509.ts +327 -0
  41. package/dist_ts/smartcrypto.plugins.d.ts +0 -4
  42. package/dist_ts/smartcrypto.plugins.js +0 -7
  43. package/ts/smartcrypto.plugins.ts +0 -9
@@ -1,16 +1,44 @@
1
- import * as plugins from './smartcrypto.plugins.js';
2
- import { createSmartCryptoError } from './smartcrypto.errors.js';
1
+ import { SmartCryptoError, createSmartCryptoError } from './smartcrypto.errors.js';
2
+ import { getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
3
+ import { encodeOpenSshRsaPrivateKey } from './smartcrypto.openssh.js';
4
+ import { decodeFirstPemBlock, encodePem } from './smartcrypto.pem.js';
3
5
  import { decryptPrivateKeyInfo, encryptPrivateKeyInfo } from './smartcrypto.pkcs8.js';
6
+ import {
7
+ bitLengthOf,
8
+ copyRsaPrivateKeyComponents,
9
+ decodePrivateKeyInfo,
10
+ decodeRsaPrivateKey,
11
+ encodePrivateKeyInfo,
12
+ encodeRsaPrivateKey,
13
+ type IRsaPrivateKeyComponents,
14
+ } from './smartcrypto.rsa.js';
15
+
16
+ const pkcs1PrivatePemType = 'RSA PRIVATE KEY';
17
+ const pkcs8PrivatePemType = 'PRIVATE KEY';
4
18
 
5
19
  export class PrivateKey {
6
20
  // STATIC
21
+ /** Parses an unencrypted RSA private-key PEM; the same as `fromPemString()`. */
7
22
  public static createFromPrivateKey(pemString: string) {
8
- const privateKey = plugins.nodeForge.pki.privateKeyFromPem(pemString);
9
- return new PrivateKey(privateKey);
23
+ return PrivateKey.fromPemString(pemString);
10
24
  }
11
25
 
26
+ /**
27
+ * Parses the first PEM block of `pemString` as an unencrypted PKCS#1
28
+ * (`RSA PRIVATE KEY`) or PKCS#8 (`PRIVATE KEY`) RSA private key.
29
+ * Fails with `INVALID_KEY`.
30
+ */
12
31
  public static fromPemString(pemString: string) {
13
- return new PrivateKey(plugins.nodeForge.pki.privateKeyFromPem(pemString));
32
+ const pemBlock = decodeFirstPemBlock(pemString, [pkcs1PrivatePemType, pkcs8PrivatePemType]);
33
+ try {
34
+ return new PrivateKey(
35
+ pemBlock.type === pkcs1PrivatePemType
36
+ ? decodeRsaPrivateKey(pemBlock.body)
37
+ : decodePrivateKeyInfo(pemBlock.body),
38
+ );
39
+ } finally {
40
+ pemBlock.body.fill(0);
41
+ }
14
42
  }
15
43
 
16
44
  /**
@@ -25,21 +53,34 @@ export class PrivateKey {
25
53
  ): Promise<PrivateKey> {
26
54
  const privateKeyInfo = await decryptPrivateKeyInfo(pemString, passphraseArg);
27
55
  try {
28
- return new PrivateKey(plugins.nodeForge.pki.privateKeyFromAsn1(privateKeyInfo));
29
- } catch {
30
- throw createSmartCryptoError('INVALID_KEY');
56
+ return new PrivateKey(decodePrivateKeyInfo(privateKeyInfo));
57
+ } finally {
58
+ privateKeyInfo.fill(0);
31
59
  }
32
60
  }
33
61
 
34
62
  // INSTANCE
35
- public forgePrivateKey: plugins.nodeForge.pki.rsa.PrivateKey;
63
+ private readonly components: IRsaPrivateKeyComponents;
64
+ private signingKey?: Promise<CryptoKey>;
36
65
 
37
- constructor(privateKeyArg: plugins.nodeForge.pki.rsa.PrivateKey) {
38
- this.forgePrivateKey = privateKeyArg;
66
+ /** Creates a private key from its RFC 8017 integers. Fails with `INVALID_KEY`. */
67
+ constructor(componentsArg: IRsaPrivateKeyComponents) {
68
+ this.components = copyRsaPrivateKeyComponents(componentsArg);
39
69
  }
40
70
 
71
+ /** The RSA modulus length in bits. */
72
+ public get modulusLength(): number {
73
+ return bitLengthOf(this.components.modulus);
74
+ }
75
+
76
+ /** Writes an unencrypted PKCS#1 `-----BEGIN RSA PRIVATE KEY-----` PEM (64-column lines, CRLF). */
41
77
  public toPemString(): string {
42
- return plugins.nodeForge.pki.privateKeyToPem(this.forgePrivateKey);
78
+ const der = encodeRsaPrivateKey(this.components);
79
+ try {
80
+ return encodePem(pkcs1PrivatePemType, der);
81
+ } finally {
82
+ der.fill(0);
83
+ }
43
84
  }
44
85
 
45
86
  /**
@@ -48,15 +89,66 @@ export class PrivateKey {
48
89
  * PBKDF2-HMAC-SHA256 (600,000 iterations) and AES-256-CBC via WebCrypto.
49
90
  */
50
91
  public async toEncryptedPemString(passphraseArg: string): Promise<string> {
51
- return encryptPrivateKeyInfo(
52
- plugins.nodeForge.pki.wrapRsaPrivateKey(
53
- plugins.nodeForge.pki.privateKeyToAsn1(this.forgePrivateKey),
54
- ),
55
- passphraseArg,
56
- );
92
+ const privateKeyInfo = encodePrivateKeyInfo(this.components);
93
+ try {
94
+ return await encryptPrivateKeyInfo(privateKeyInfo, passphraseArg);
95
+ } finally {
96
+ privateKeyInfo.fill(0);
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Signs `dataArg` with RSASSA-PKCS1-v1_5 over SHA-256 (JWS `RS256`) via
102
+ * WebCrypto and returns the signature bytes.
103
+ */
104
+ public async createRs256Signature(dataArg: Uint8Array): Promise<Uint8Array> {
105
+ if (!(dataArg instanceof Uint8Array)) {
106
+ throw createSmartCryptoError('INVALID_ARGUMENT');
107
+ }
108
+ const subtle = getWebCrypto().subtle;
109
+ const signingKey = await this.getSigningKey();
110
+ try {
111
+ return new Uint8Array(
112
+ await subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, signingKey, toArrayBuffer(dataArg)),
113
+ );
114
+ } catch {
115
+ throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
116
+ }
57
117
  }
58
118
 
119
+ /**
120
+ * Writes an unencrypted OpenSSH private key
121
+ * (`-----BEGIN OPENSSH PRIVATE KEY-----`, `openssh-key-v1`) with the comment
122
+ * `user@host`, as `ssh-keygen` does.
123
+ */
59
124
  public toOpenSSH(): string {
60
- return plugins.nodeForge.ssh.privateKeyToOpenSSH(this.forgePrivateKey, 'user@host');
125
+ return encodeOpenSshRsaPrivateKey(this.components, 'user@host');
126
+ }
127
+
128
+ private async getSigningKey(): Promise<CryptoKey> {
129
+ this.signingKey ??= this.importSigningKey();
130
+ return await this.signingKey;
131
+ }
132
+
133
+ private async importSigningKey(): Promise<CryptoKey> {
134
+ const privateKeyInfo = encodePrivateKeyInfo(this.components);
135
+ const privateKeyInfoBuffer = toArrayBuffer(privateKeyInfo);
136
+ try {
137
+ return await getWebCrypto().subtle.importKey(
138
+ 'pkcs8',
139
+ privateKeyInfoBuffer,
140
+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
141
+ false,
142
+ ['sign'],
143
+ );
144
+ } catch (error) {
145
+ if (error instanceof SmartCryptoError) {
146
+ throw error;
147
+ }
148
+ throw createSmartCryptoError('INVALID_KEY');
149
+ } finally {
150
+ privateKeyInfo.fill(0);
151
+ new Uint8Array(privateKeyInfoBuffer).fill(0);
152
+ }
61
153
  }
62
154
  }
@@ -1,17 +1,41 @@
1
- import * as plugins from './smartcrypto.plugins.js';
1
+ import { bytesEqual, getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
2
+ import { encodeOpenSshRsaPublicKey } from './smartcrypto.openssh.js';
3
+ import { decodeBase64, decodeFirstPemBlock, encodePem } from './smartcrypto.pem.js';
4
+ import {
5
+ bitLengthOf,
6
+ copyRsaPublicKeyComponents,
7
+ decodeRsaPublicKey,
8
+ decodeSubjectPublicKeyInfo,
9
+ encodeRsaPublicKey,
10
+ encodeSubjectPublicKeyInfo,
11
+ type IRsaPublicKeyComponents,
12
+ } from './smartcrypto.rsa.js';
13
+
14
+ const spkiPemType = 'PUBLIC KEY';
15
+ const pkcs1PublicPemType = 'RSA PUBLIC KEY';
16
+ const canonicalPublicKeyErrorPrefix = 'Invalid canonical RSA public key:';
2
17
 
3
18
  const canonicalPublicKeyError = (messageArg: string): Error =>
4
- new Error(`Invalid canonical RSA public key: ${messageArg}`);
19
+ new Error(`${canonicalPublicKeyErrorPrefix} ${messageArg}`);
5
20
 
6
21
  export class PublicKey {
7
22
  // STATIC
23
+ /** Parses an SPKI or PKCS#1 RSA public-key PEM; despite its name it reads a public key. */
8
24
  public static createFromPrivateKey(pemString: string) {
9
- const privateKey = plugins.nodeForge.pki.publicKeyFromPem(pemString);
10
- return new PublicKey(privateKey);
25
+ return PublicKey.fromPemString(pemString);
11
26
  }
12
27
 
28
+ /**
29
+ * Parses the first PEM block of `pemString` as an SPKI (`PUBLIC KEY`) or
30
+ * PKCS#1 (`RSA PUBLIC KEY`) RSA public key. Fails with `INVALID_KEY`.
31
+ */
13
32
  public static fromPemString(pemString: string) {
14
- return new PublicKey(plugins.nodeForge.pki.publicKeyFromPem(pemString));
33
+ const pemBlock = decodeFirstPemBlock(pemString, [spkiPemType, pkcs1PublicPemType]);
34
+ return new PublicKey(
35
+ pemBlock.type === spkiPemType
36
+ ? decodeSubjectPublicKeyInfo(pemBlock.body)
37
+ : decodeRsaPublicKey(pemBlock.body),
38
+ );
15
39
  }
16
40
 
17
41
  /**
@@ -45,30 +69,27 @@ export class PublicKey {
45
69
  throw canonicalPublicKeyError('PEM body is malformed');
46
70
  }
47
71
 
72
+ let der: Uint8Array;
48
73
  try {
49
- const pemMessages = plugins.nodeForge.pem.decode(normalizedPem);
50
- if (pemMessages.length !== 1) {
51
- throw canonicalPublicKeyError('expected exactly one decoded PEM block');
52
- }
53
- const pemMessage = pemMessages[0];
54
- if (plugins.nodeForge.util.encode64(pemMessage.body) !== flattenedBase64) {
55
- throw canonicalPublicKeyError('PEM body is not canonical base64');
56
- }
57
- const publicKeyAsn1 = plugins.nodeForge.asn1.fromDer(pemMessage.body, true);
58
- const publicKey = plugins.nodeForge.pki.publicKeyFromAsn1(publicKeyAsn1);
59
- if (publicKey.n.bitLength() < 2_048) {
74
+ der = decodeBase64(flattenedBase64);
75
+ } catch {
76
+ throw canonicalPublicKeyError('PEM body is not canonical base64');
77
+ }
78
+
79
+ try {
80
+ const components = spkiMatch ? decodeSubjectPublicKeyInfo(der) : decodeRsaPublicKey(der);
81
+ if (bitLengthOf(components.modulus) < 2_048) {
60
82
  throw canonicalPublicKeyError('RSA modulus must contain at least 2048 bits');
61
83
  }
62
- const canonicalAsn1 = spkiMatch
63
- ? plugins.nodeForge.pki.publicKeyToAsn1(publicKey)
64
- : plugins.nodeForge.pki.publicKeyToRSAPublicKey(publicKey);
65
- const canonicalDer = plugins.nodeForge.asn1.toDer(canonicalAsn1).getBytes();
66
- if (canonicalDer !== pemMessage.body) {
84
+ const canonicalDer = spkiMatch
85
+ ? encodeSubjectPublicKeyInfo(components)
86
+ : encodeRsaPublicKey(components);
87
+ if (!bytesEqual(canonicalDer, der)) {
67
88
  throw canonicalPublicKeyError('public-key DER is not canonical');
68
89
  }
69
- return new PublicKey(publicKey);
90
+ return new PublicKey(components);
70
91
  } catch (error) {
71
- if (error instanceof Error && error.message.startsWith('Invalid canonical RSA public key:')) {
92
+ if (error instanceof Error && error.message.startsWith(canonicalPublicKeyErrorPrefix)) {
72
93
  throw error;
73
94
  }
74
95
  throw canonicalPublicKeyError('PEM does not encode a valid RSA public key');
@@ -76,79 +97,63 @@ export class PublicKey {
76
97
  }
77
98
 
78
99
  // INSTANCE
79
- public forgePublicKey: plugins.nodeForge.pki.rsa.PublicKey;
100
+ private readonly components: IRsaPublicKeyComponents;
101
+ private verificationKey?: Promise<CryptoKey>;
80
102
 
81
- constructor(publicKeyArg: plugins.nodeForge.pki.rsa.PublicKey) {
82
- this.forgePublicKey = publicKeyArg;
103
+ /** Creates a public key from its modulus and public exponent. Fails with `INVALID_KEY`. */
104
+ constructor(componentsArg: IRsaPublicKeyComponents) {
105
+ this.components = copyRsaPublicKeyComponents(componentsArg);
83
106
  }
84
107
 
108
+ /** The RSA modulus length in bits. */
109
+ public get modulusLength(): number {
110
+ return bitLengthOf(this.components.modulus);
111
+ }
112
+
113
+ /** Writes an SPKI `-----BEGIN PUBLIC KEY-----` PEM (64-column lines, CRLF). */
85
114
  public toPemString(): string {
86
- return plugins.nodeForge.pki.publicKeyToPem(this.forgePublicKey);
115
+ return encodePem(spkiPemType, encodeSubjectPublicKeyInfo(this.components));
87
116
  }
88
117
 
89
118
  /**
90
- * Verifies RSASSA-PKCS1-v1_5 with an exact SHA-256 DigestInfo. The exact
91
- * encoding check prevents accepting signatures that label the digest with a
92
- * different algorithm identifier.
119
+ * Verifies an RSASSA-PKCS1-v1_5 signature over SHA-256 with WebCrypto. The
120
+ * platform verifier compares the complete encoded message, so a signature
121
+ * whose DigestInfo names another algorithm or carries extra elements fails.
122
+ * Malformed input and invalid signatures resolve to `false`.
93
123
  */
94
- public verifyRs256(dataArg: Uint8Array, signatureArg: Uint8Array): boolean {
124
+ public async verifyRs256Signature(dataArg: Uint8Array, signatureArg: Uint8Array): Promise<boolean> {
95
125
  if (!(dataArg instanceof Uint8Array) || !(signatureArg instanceof Uint8Array)) {
96
126
  return false;
97
127
  }
128
+ if (signatureArg.byteLength !== Math.ceil(this.modulusLength / 8)) {
129
+ return false;
130
+ }
131
+ const subtle = getWebCrypto().subtle;
98
132
  try {
99
- if (signatureArg.byteLength !== Math.ceil(this.forgePublicKey.n.bitLength() / 8)) {
100
- return false;
101
- }
102
- const messageDigest = plugins.nodeForge.md.sha256.create();
103
- messageDigest.update(
104
- plugins.nodeForge.util.createBuffer(dataArg.slice()).getBytes(),
105
- 'raw',
106
- );
107
- const digestInfo = plugins.nodeForge.asn1.create(
108
- plugins.nodeForge.asn1.Class.UNIVERSAL,
109
- plugins.nodeForge.asn1.Type.SEQUENCE,
110
- true,
111
- [
112
- plugins.nodeForge.asn1.create(
113
- plugins.nodeForge.asn1.Class.UNIVERSAL,
114
- plugins.nodeForge.asn1.Type.SEQUENCE,
115
- true,
116
- [
117
- plugins.nodeForge.asn1.create(
118
- plugins.nodeForge.asn1.Class.UNIVERSAL,
119
- plugins.nodeForge.asn1.Type.OID,
120
- false,
121
- plugins.nodeForge.asn1.oidToDer(
122
- plugins.nodeForge.pki.oids.sha256,
123
- ).getBytes(),
124
- ),
125
- plugins.nodeForge.asn1.create(
126
- plugins.nodeForge.asn1.Class.UNIVERSAL,
127
- plugins.nodeForge.asn1.Type.NULL,
128
- false,
129
- '',
130
- ),
131
- ],
132
- ),
133
- plugins.nodeForge.asn1.create(
134
- plugins.nodeForge.asn1.Class.UNIVERSAL,
135
- plugins.nodeForge.asn1.Type.OCTETSTRING,
136
- false,
137
- messageDigest.digest().getBytes(),
138
- ),
139
- ],
140
- );
141
- return this.forgePublicKey.verify(
142
- plugins.nodeForge.asn1.toDer(digestInfo).getBytes(),
143
- plugins.nodeForge.util.createBuffer(signatureArg.slice()).getBytes(),
144
- 'NONE',
133
+ return await subtle.verify(
134
+ { name: 'RSASSA-PKCS1-v1_5' },
135
+ await this.getVerificationKey(),
136
+ toArrayBuffer(signatureArg),
137
+ toArrayBuffer(dataArg),
145
138
  );
146
139
  } catch {
147
140
  return false;
148
141
  }
149
142
  }
150
143
 
144
+ /** Writes an OpenSSH `ssh-rsa` public key line with the comment `user@host`. */
151
145
  public toOpenSSH(): string {
152
- return plugins.nodeForge.ssh.publicKeyToOpenSSH(this.forgePublicKey, 'user@host');
146
+ return encodeOpenSshRsaPublicKey(this.components, 'user@host');
147
+ }
148
+
149
+ private getVerificationKey(): Promise<CryptoKey> {
150
+ this.verificationKey ??= getWebCrypto().subtle.importKey(
151
+ 'spki',
152
+ toArrayBuffer(encodeSubjectPublicKeyInfo(this.components)),
153
+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
154
+ false,
155
+ ['verify'],
156
+ );
157
+ return this.verificationKey;
153
158
  }
154
159
  }
@@ -1,4 +1,3 @@
1
- import * as plugins from './smartcrypto.plugins.js';
2
1
  import { KeyPair, type IKeyPairOptions } from './smartcrypto.classes.keypair.js';
3
2
 
4
3
  export class Smartcrypto {
@@ -0,0 +1,248 @@
1
+ import { createSmartCryptoError } from './smartcrypto.errors.js';
2
+ import { concatBytes } from './smartcrypto.internal.js';
3
+
4
+ /**
5
+ * A strict DER reader and writer for the few ASN.1 types that key formats use.
6
+ * Only definite, minimally encoded lengths and single-byte tags are accepted,
7
+ * so every accepted encoding has exactly one byte representation.
8
+ */
9
+
10
+ export const derTags = {
11
+ boolean: 0x01,
12
+ integer: 0x02,
13
+ bitString: 0x03,
14
+ octetString: 0x04,
15
+ null: 0x05,
16
+ oid: 0x06,
17
+ utf8String: 0x0c,
18
+ utcTime: 0x17,
19
+ generalizedTime: 0x18,
20
+ sequence: 0x30,
21
+ set: 0x31,
22
+ contextSpecificConstructed0: 0xa0,
23
+ contextSpecificConstructed3: 0xa3,
24
+ } as const;
25
+
26
+ export interface IDerElement {
27
+ tag: number;
28
+ content: Uint8Array;
29
+ }
30
+
31
+ const invalidKey = () => createSmartCryptoError('INVALID_KEY');
32
+
33
+ /** Reads the element starting at `offsetArg` and returns it with the offset just past it. */
34
+ const readElementAt = (
35
+ bytesArg: Uint8Array,
36
+ offsetArg: number,
37
+ ): { element: IDerElement; end: number } => {
38
+ if (offsetArg + 2 > bytesArg.byteLength) {
39
+ throw invalidKey();
40
+ }
41
+ const tag = bytesArg[offsetArg];
42
+ if ((tag & 0x1f) === 0x1f) {
43
+ throw invalidKey();
44
+ }
45
+ const lengthByte = bytesArg[offsetArg + 1];
46
+ let offset = offsetArg + 2;
47
+ let length = lengthByte;
48
+ if (lengthByte & 0x80) {
49
+ const lengthOctets = lengthByte & 0x7f;
50
+ if (lengthOctets < 1 || lengthOctets > 4 || offset + lengthOctets > bytesArg.byteLength) {
51
+ throw invalidKey();
52
+ }
53
+ if (bytesArg[offset] === 0) {
54
+ throw invalidKey();
55
+ }
56
+ length = 0;
57
+ for (let index = 0; index < lengthOctets; index++) {
58
+ length = length * 0x100 + bytesArg[offset + index];
59
+ }
60
+ if (length < 0x80) {
61
+ throw invalidKey();
62
+ }
63
+ offset += lengthOctets;
64
+ }
65
+ const end = offset + length;
66
+ if (end > bytesArg.byteLength) {
67
+ throw invalidKey();
68
+ }
69
+ return { element: { tag, content: bytesArg.subarray(offset, end) }, end };
70
+ };
71
+
72
+ /** Decodes exactly one DER element that spans all of `bytesArg`. */
73
+ export const decodeDerElement = (bytesArg: Uint8Array): IDerElement => {
74
+ const { element, end } = readElementAt(bytesArg, 0);
75
+ if (end !== bytesArg.byteLength) {
76
+ throw invalidKey();
77
+ }
78
+ return element;
79
+ };
80
+
81
+ /** Decodes the concatenated elements inside a constructed element's content. */
82
+ export const decodeDerChildren = (contentArg: Uint8Array): IDerElement[] => {
83
+ const children: IDerElement[] = [];
84
+ let offset = 0;
85
+ while (offset < contentArg.byteLength) {
86
+ const { element, end } = readElementAt(contentArg, offset);
87
+ children.push(element);
88
+ offset = end;
89
+ }
90
+ return children;
91
+ };
92
+
93
+ const requireTag = (elementArg: IDerElement | undefined, tagArg: number): IDerElement => {
94
+ if (!elementArg || elementArg.tag !== tagArg) {
95
+ throw invalidKey();
96
+ }
97
+ return elementArg;
98
+ };
99
+
100
+ export const readDerSequence = (
101
+ elementArg: IDerElement | undefined,
102
+ minLengthArg: number,
103
+ maxLengthArg: number,
104
+ ): IDerElement[] => {
105
+ const children = decodeDerChildren(requireTag(elementArg, derTags.sequence).content);
106
+ if (children.length < minLengthArg || children.length > maxLengthArg) {
107
+ throw invalidKey();
108
+ }
109
+ return children;
110
+ };
111
+
112
+ /**
113
+ * Reads a non-negative INTEGER and returns its magnitude without leading zero
114
+ * bytes (zero yields an empty array). Negative values are rejected.
115
+ */
116
+ export const readDerUnsignedInteger = (elementArg: IDerElement | undefined): Uint8Array => {
117
+ const content = requireTag(elementArg, derTags.integer).content;
118
+ if (content.byteLength < 1 || content[0] & 0x80) {
119
+ throw invalidKey();
120
+ }
121
+ if (content[0] === 0 && content.byteLength > 1 && !(content[1] & 0x80)) {
122
+ throw invalidKey();
123
+ }
124
+ return content.slice(content[0] === 0 ? 1 : 0);
125
+ };
126
+
127
+ /** Reads a non-negative INTEGER that fits into 31 bits. */
128
+ export const readDerSmallInteger = (elementArg: IDerElement | undefined): number => {
129
+ const magnitude = readDerUnsignedInteger(elementArg);
130
+ if (magnitude.byteLength > 4 || (magnitude.byteLength === 4 && magnitude[0] & 0x80)) {
131
+ throw invalidKey();
132
+ }
133
+ return magnitude.reduce((valueArg, byteArg) => valueArg * 0x100 + byteArg, 0);
134
+ };
135
+
136
+ export const readDerOctetString = (elementArg: IDerElement | undefined): Uint8Array =>
137
+ requireTag(elementArg, derTags.octetString).content.slice();
138
+
139
+ /** Reads a BIT STRING without unused trailing bits. */
140
+ export const readDerBitString = (elementArg: IDerElement | undefined): Uint8Array => {
141
+ const content = requireTag(elementArg, derTags.bitString).content;
142
+ if (content.byteLength < 1 || content[0] !== 0) {
143
+ throw invalidKey();
144
+ }
145
+ return content.slice(1);
146
+ };
147
+
148
+ export const readDerNull = (elementArg: IDerElement | undefined): void => {
149
+ if (requireTag(elementArg, derTags.null).content.byteLength !== 0) {
150
+ throw invalidKey();
151
+ }
152
+ };
153
+
154
+ export const readDerOid = (elementArg: IDerElement | undefined): string => {
155
+ const content = requireTag(elementArg, derTags.oid).content;
156
+ if (content.byteLength < 1 || content[content.byteLength - 1] & 0x80) {
157
+ throw invalidKey();
158
+ }
159
+ const arcs: number[] = [];
160
+ let value = 0;
161
+ let arcStart = true;
162
+ for (const byte of content) {
163
+ if (arcStart && byte === 0x80) {
164
+ throw invalidKey();
165
+ }
166
+ if (value > (Number.MAX_SAFE_INTEGER - 0x7f) / 0x80) {
167
+ throw invalidKey();
168
+ }
169
+ value = value * 0x80 + (byte & 0x7f);
170
+ arcStart = !(byte & 0x80);
171
+ if (arcStart) {
172
+ arcs.push(value);
173
+ value = 0;
174
+ }
175
+ }
176
+ const first = arcs[0];
177
+ const leadingArcs = first < 40 ? [0, first] : first < 80 ? [1, first - 40] : [2, first - 80];
178
+ return [...leadingArcs, ...arcs.slice(1)].join('.');
179
+ };
180
+
181
+ // ========================================
182
+ // Encoding
183
+ // ========================================
184
+ const encodeLength = (lengthArg: number): Uint8Array => {
185
+ if (lengthArg < 0x80) {
186
+ return new Uint8Array([lengthArg]);
187
+ }
188
+ const lengthBytes: number[] = [];
189
+ for (let remaining = lengthArg; remaining > 0; remaining = Math.floor(remaining / 0x100)) {
190
+ lengthBytes.unshift(remaining & 0xff);
191
+ }
192
+ return new Uint8Array([0x80 | lengthBytes.length, ...lengthBytes]);
193
+ };
194
+
195
+ export const encodeDerElement = (tagArg: number, contentArg: Uint8Array): Uint8Array =>
196
+ concatBytes(new Uint8Array([tagArg]), encodeLength(contentArg.byteLength), contentArg);
197
+
198
+ export const encodeDerSequence = (...childrenArg: Uint8Array[]): Uint8Array =>
199
+ encodeDerElement(derTags.sequence, concatBytes(...childrenArg));
200
+
201
+ /** Encodes an unsigned magnitude as a minimal non-negative INTEGER. */
202
+ export const encodeDerUnsignedInteger = (magnitudeArg: Uint8Array): Uint8Array => {
203
+ let start = 0;
204
+ while (start < magnitudeArg.byteLength && magnitudeArg[start] === 0) {
205
+ start++;
206
+ }
207
+ const magnitude = magnitudeArg.subarray(start);
208
+ if (magnitude.byteLength === 0 || magnitude[0] & 0x80) {
209
+ return encodeDerElement(derTags.integer, concatBytes(new Uint8Array([0]), magnitude));
210
+ }
211
+ return encodeDerElement(derTags.integer, magnitude);
212
+ };
213
+
214
+ export const encodeDerSmallInteger = (valueArg: number): Uint8Array => {
215
+ const magnitude: number[] = [];
216
+ for (let remaining = valueArg; remaining > 0; remaining = Math.floor(remaining / 0x100)) {
217
+ magnitude.unshift(remaining & 0xff);
218
+ }
219
+ return encodeDerUnsignedInteger(new Uint8Array(magnitude));
220
+ };
221
+
222
+ export const encodeDerOctetString = (bytesArg: Uint8Array): Uint8Array =>
223
+ encodeDerElement(derTags.octetString, bytesArg);
224
+
225
+ /**
226
+ * Encodes a BIT STRING whose last `unusedBitsArg` bits are padding. DER
227
+ * requires the padding bits to be zero; the caller supplies them that way.
228
+ */
229
+ export const encodeDerBitString = (bytesArg: Uint8Array, unusedBitsArg = 0): Uint8Array =>
230
+ encodeDerElement(derTags.bitString, concatBytes(new Uint8Array([unusedBitsArg]), bytesArg));
231
+
232
+ export const encodeDerBoolean = (valueArg: boolean): Uint8Array =>
233
+ encodeDerElement(derTags.boolean, new Uint8Array([valueArg ? 0xff : 0x00]));
234
+
235
+ export const encodeDerNull = (): Uint8Array => encodeDerElement(derTags.null, new Uint8Array(0));
236
+
237
+ export const encodeDerOid = (oidArg: string): Uint8Array => {
238
+ const arcs = oidArg.split('.').map(Number);
239
+ const content: number[] = [];
240
+ for (const arc of [arcs[0] * 40 + arcs[1], ...arcs.slice(2)]) {
241
+ const arcBytes = [arc & 0x7f];
242
+ for (let remaining = Math.floor(arc / 0x80); remaining > 0; remaining = Math.floor(remaining / 0x80)) {
243
+ arcBytes.unshift(0x80 | (remaining & 0x7f));
244
+ }
245
+ content.push(...arcBytes);
246
+ }
247
+ return encodeDerElement(derTags.oid, new Uint8Array(content));
248
+ };
@@ -137,15 +137,18 @@ export const isAllZero = (valueArg: Uint8Array): boolean => {
137
137
  return combined === 0;
138
138
  };
139
139
 
140
- export const encodeBase64Url = (valueArg: Uint8Array): string => {
140
+ export const encodeBase64 = (valueArg: Uint8Array): string => {
141
141
  let binary = '';
142
142
  const chunkSize = 0x8000;
143
143
  for (let offset = 0; offset < valueArg.byteLength; offset += chunkSize) {
144
144
  binary += String.fromCharCode(...valueArg.subarray(offset, offset + chunkSize));
145
145
  }
146
- return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
146
+ return btoa(binary);
147
147
  };
148
148
 
149
+ export const encodeBase64Url = (valueArg: Uint8Array): string =>
150
+ encodeBase64(valueArg).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
151
+
149
152
  export const decodeCanonicalBase64Url = (
150
153
  valueArg: unknown,
151
154
  maximumBytesArg: number,