@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.
- package/.smartconfig.json +0 -1
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/index.d.ts +2 -2
- package/dist_ts/index.js +2 -3
- package/dist_ts/smartcrypto.classes.keypair.d.ts +1 -0
- package/dist_ts/smartcrypto.classes.keypair.js +34 -15
- package/dist_ts/smartcrypto.classes.privatekey.d.ts +26 -3
- package/dist_ts/smartcrypto.classes.privatekey.js +93 -14
- package/dist_ts/smartcrypto.classes.publickey.d.ts +20 -7
- package/dist_ts/smartcrypto.classes.publickey.js +59 -45
- package/dist_ts/smartcrypto.classes.smartcrypto.js +1 -2
- package/dist_ts/smartcrypto.der.d.ts +55 -0
- package/dist_ts/smartcrypto.der.js +207 -0
- package/dist_ts/smartcrypto.internal.d.ts +1 -0
- package/dist_ts/smartcrypto.internal.js +4 -3
- package/dist_ts/smartcrypto.openssh.d.ts +8 -0
- package/dist_ts/smartcrypto.openssh.js +51 -0
- package/dist_ts/smartcrypto.pem.d.ts +16 -0
- package/dist_ts/smartcrypto.pem.js +50 -0
- package/dist_ts/smartcrypto.pkcs8.d.ts +4 -6
- package/dist_ts/smartcrypto.pkcs8.js +33 -95
- package/dist_ts/smartcrypto.rsa.d.ts +30 -0
- package/dist_ts/smartcrypto.rsa.js +153 -0
- package/dist_ts/smartcrypto.x509.d.ts +32 -0
- package/dist_ts/smartcrypto.x509.js +222 -0
- package/package.json +2 -7
- package/readme.md +75 -8
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/index.ts +5 -4
- package/ts/smartcrypto.classes.keypair.ts +34 -17
- package/ts/smartcrypto.classes.privatekey.ts +111 -19
- package/ts/smartcrypto.classes.publickey.ts +83 -78
- package/ts/smartcrypto.classes.smartcrypto.ts +0 -1
- package/ts/smartcrypto.der.ts +248 -0
- package/ts/smartcrypto.internal.ts +5 -2
- package/ts/smartcrypto.openssh.ts +98 -0
- package/ts/smartcrypto.pem.ts +61 -0
- package/ts/smartcrypto.pkcs8.ts +63 -121
- package/ts/smartcrypto.rsa.ts +234 -0
- package/ts/smartcrypto.x509.ts +327 -0
- package/dist_ts/smartcrypto.plugins.d.ts +0 -4
- package/dist_ts/smartcrypto.plugins.js +0 -7
- package/ts/smartcrypto.plugins.ts +0 -9
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { concatBytes, encodeBase64, getWebCrypto } from './smartcrypto.internal.js';
|
|
2
|
+
import type {
|
|
3
|
+
IRsaPrivateKeyComponents,
|
|
4
|
+
IRsaPublicKeyComponents,
|
|
5
|
+
} from './smartcrypto.rsa.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* OpenSSH key encodings for RSA: the RFC 4253 `ssh-rsa` public key and the
|
|
9
|
+
* unencrypted `openssh-key-v1` private key container (OpenSSH PROTOCOL.key).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const sshRsaKeyType = 'ssh-rsa';
|
|
13
|
+
const opensshKeyMagic = 'openssh-key-v1\0';
|
|
14
|
+
const unencryptedBlockSize = 8;
|
|
15
|
+
const textEncoder = new TextEncoder();
|
|
16
|
+
|
|
17
|
+
const encodeUint32 = (valueArg: number): Uint8Array => {
|
|
18
|
+
const result = new Uint8Array(4);
|
|
19
|
+
new DataView(result.buffer).setUint32(0, valueArg, false);
|
|
20
|
+
return result;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** RFC 4251 `string`: a uint32 length followed by the bytes. */
|
|
24
|
+
const encodeSshString = (bytesArg: Uint8Array): Uint8Array =>
|
|
25
|
+
concatBytes(encodeUint32(bytesArg.byteLength), bytesArg);
|
|
26
|
+
|
|
27
|
+
const encodeSshText = (textArg: string): Uint8Array => encodeSshString(textEncoder.encode(textArg));
|
|
28
|
+
|
|
29
|
+
/** RFC 4251 `mpint` for a non-negative magnitude: minimal, with a zero byte before a set high bit. */
|
|
30
|
+
const encodeSshMpint = (magnitudeArg: Uint8Array): Uint8Array => {
|
|
31
|
+
let start = 0;
|
|
32
|
+
while (start < magnitudeArg.byteLength && magnitudeArg[start] === 0) {
|
|
33
|
+
start++;
|
|
34
|
+
}
|
|
35
|
+
const magnitude = magnitudeArg.subarray(start);
|
|
36
|
+
return encodeSshString(
|
|
37
|
+
magnitude.byteLength > 0 && magnitude[0] & 0x80
|
|
38
|
+
? concatBytes(new Uint8Array([0]), magnitude)
|
|
39
|
+
: magnitude,
|
|
40
|
+
);
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** The RFC 4253 `ssh-rsa` public key blob: string "ssh-rsa", mpint e, mpint n. */
|
|
44
|
+
const encodeSshRsaPublicKeyBlob = (componentsArg: IRsaPublicKeyComponents): Uint8Array =>
|
|
45
|
+
concatBytes(
|
|
46
|
+
encodeSshText(sshRsaKeyType),
|
|
47
|
+
encodeSshMpint(componentsArg.publicExponent),
|
|
48
|
+
encodeSshMpint(componentsArg.modulus),
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
/** Formats an `authorized_keys` line: `ssh-rsa <base64 blob> <comment>`. */
|
|
52
|
+
export const encodeOpenSshRsaPublicKey = (
|
|
53
|
+
componentsArg: IRsaPublicKeyComponents,
|
|
54
|
+
commentArg: string,
|
|
55
|
+
): string => `${sshRsaKeyType} ${encodeBase64(encodeSshRsaPublicKeyBlob(componentsArg))} ${commentArg}`;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Formats an unencrypted `-----BEGIN OPENSSH PRIVATE KEY-----` file as written
|
|
59
|
+
* by `ssh-keygen`, with a random check integer and 70-column base64 lines.
|
|
60
|
+
*/
|
|
61
|
+
export const encodeOpenSshRsaPrivateKey = (
|
|
62
|
+
componentsArg: IRsaPrivateKeyComponents,
|
|
63
|
+
commentArg: string,
|
|
64
|
+
): string => {
|
|
65
|
+
const checkInteger = encodeUint32(
|
|
66
|
+
getWebCrypto().getRandomValues(new Uint32Array(1))[0],
|
|
67
|
+
);
|
|
68
|
+
const privateSection = concatBytes(
|
|
69
|
+
checkInteger,
|
|
70
|
+
checkInteger,
|
|
71
|
+
encodeSshText(sshRsaKeyType),
|
|
72
|
+
encodeSshMpint(componentsArg.modulus),
|
|
73
|
+
encodeSshMpint(componentsArg.publicExponent),
|
|
74
|
+
encodeSshMpint(componentsArg.privateExponent),
|
|
75
|
+
encodeSshMpint(componentsArg.coefficient),
|
|
76
|
+
encodeSshMpint(componentsArg.prime1),
|
|
77
|
+
encodeSshMpint(componentsArg.prime2),
|
|
78
|
+
encodeSshText(commentArg),
|
|
79
|
+
);
|
|
80
|
+
const paddingLength = (unencryptedBlockSize - (privateSection.byteLength % unencryptedBlockSize))
|
|
81
|
+
% unencryptedBlockSize;
|
|
82
|
+
const padding = Uint8Array.from({ length: paddingLength }, (_valueArg, indexArg) => indexArg + 1);
|
|
83
|
+
const paddedPrivateSection = concatBytes(privateSection, padding);
|
|
84
|
+
const container = concatBytes(
|
|
85
|
+
textEncoder.encode(opensshKeyMagic),
|
|
86
|
+
encodeSshText('none'),
|
|
87
|
+
encodeSshText('none'),
|
|
88
|
+
encodeSshText(''),
|
|
89
|
+
encodeUint32(1),
|
|
90
|
+
encodeSshString(encodeSshRsaPublicKeyBlob(componentsArg)),
|
|
91
|
+
encodeSshString(paddedPrivateSection),
|
|
92
|
+
);
|
|
93
|
+
const lines = encodeBase64(container).match(/.{1,70}/g) ?? [];
|
|
94
|
+
privateSection.fill(0);
|
|
95
|
+
paddedPrivateSection.fill(0);
|
|
96
|
+
container.fill(0);
|
|
97
|
+
return `-----BEGIN OPENSSH PRIVATE KEY-----\n${lines.join('\n')}\n-----END OPENSSH PRIVATE KEY-----\n`;
|
|
98
|
+
};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createSmartCryptoError } from './smartcrypto.errors.js';
|
|
2
|
+
import { encodeBase64 } from './smartcrypto.internal.js';
|
|
3
|
+
|
|
4
|
+
export interface IPemBlock {
|
|
5
|
+
type: string;
|
|
6
|
+
body: Uint8Array;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const pemBlockPattern = /-----BEGIN ([A-Z0-9 -]+)-----([\s\S]*?)-----END \1-----/g;
|
|
10
|
+
const base64Pattern = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Decodes canonical standard padded base64; whitespace is not accepted. The
|
|
14
|
+
* input must equal the re-encoding of its bytes, which rejects non-zero unused
|
|
15
|
+
* bits in the final character, so every byte string has exactly one encoding.
|
|
16
|
+
*/
|
|
17
|
+
export const decodeBase64 = (valueArg: string): Uint8Array => {
|
|
18
|
+
if (valueArg.length % 4 !== 0 || !base64Pattern.test(valueArg)) {
|
|
19
|
+
throw createSmartCryptoError('INVALID_KEY');
|
|
20
|
+
}
|
|
21
|
+
const binary = atob(valueArg);
|
|
22
|
+
const result = new Uint8Array(binary.length);
|
|
23
|
+
for (let index = 0; index < binary.length; index++) {
|
|
24
|
+
result[index] = binary.charCodeAt(index);
|
|
25
|
+
}
|
|
26
|
+
if (encodeBase64(result) !== valueArg) {
|
|
27
|
+
throw createSmartCryptoError('INVALID_KEY');
|
|
28
|
+
}
|
|
29
|
+
return result;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const decodePemMatch = (matchArg: RegExpMatchArray): IPemBlock => {
|
|
33
|
+
// RFC 1421 headers, such as legacy `Proc-Type: 4,ENCRYPTED` keys, are not supported.
|
|
34
|
+
if (matchArg[2].includes(':')) {
|
|
35
|
+
throw createSmartCryptoError('INVALID_KEY');
|
|
36
|
+
}
|
|
37
|
+
return { type: matchArg[1], body: decodeBase64(matchArg[2].replace(/\s+/g, '')) };
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** Returns every PEM block in `textArg`, in order; text around the blocks is ignored. */
|
|
41
|
+
export const decodePemBlocks = (textArg: string): IPemBlock[] =>
|
|
42
|
+
[...textArg.matchAll(pemBlockPattern)].map(decodePemMatch);
|
|
43
|
+
|
|
44
|
+
/** Decodes the first PEM block of `textArg` and requires one of `typesArg`. */
|
|
45
|
+
export const decodeFirstPemBlock = (textArg: string, typesArg: readonly string[]): IPemBlock => {
|
|
46
|
+
if (typeof textArg !== 'string') {
|
|
47
|
+
throw createSmartCryptoError('INVALID_KEY');
|
|
48
|
+
}
|
|
49
|
+
const [match] = textArg.matchAll(pemBlockPattern);
|
|
50
|
+
const block = match ? decodePemMatch(match) : undefined;
|
|
51
|
+
if (!block || !typesArg.includes(block.type)) {
|
|
52
|
+
throw createSmartCryptoError('INVALID_KEY');
|
|
53
|
+
}
|
|
54
|
+
return block;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** Encodes DER as PEM with 64-column base64 lines and CRLF line endings. */
|
|
58
|
+
export const encodePem = (typeArg: string, derArg: Uint8Array): string => {
|
|
59
|
+
const lines = encodeBase64(derArg).match(/.{1,64}/g) ?? [];
|
|
60
|
+
return `-----BEGIN ${typeArg}-----\r\n${lines.join('\r\n')}\r\n-----END ${typeArg}-----\r\n`;
|
|
61
|
+
};
|
package/ts/smartcrypto.pkcs8.ts
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
|
-
import * as plugins from './smartcrypto.plugins.js';
|
|
2
1
|
import { createSmartCryptoError } from './smartcrypto.errors.js';
|
|
3
2
|
import { getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
import {
|
|
4
|
+
decodeDerElement,
|
|
5
|
+
derTags,
|
|
6
|
+
encodeDerNull,
|
|
7
|
+
encodeDerOctetString,
|
|
8
|
+
encodeDerOid,
|
|
9
|
+
encodeDerSequence,
|
|
10
|
+
encodeDerSmallInteger,
|
|
11
|
+
readDerOctetString,
|
|
12
|
+
readDerOid,
|
|
13
|
+
readDerSequence,
|
|
14
|
+
readDerSmallInteger,
|
|
15
|
+
type IDerElement,
|
|
16
|
+
} from './smartcrypto.der.js';
|
|
17
|
+
import { decodePemBlocks, encodePem } from './smartcrypto.pem.js';
|
|
6
18
|
|
|
7
19
|
const encryptedPemType = 'ENCRYPTED PRIVATE KEY';
|
|
8
20
|
const saltBytes = 16;
|
|
@@ -32,72 +44,9 @@ const aesCbcKeyBitsByOid = new Map<string, number>([
|
|
|
32
44
|
[aes256CbcOid, 256],
|
|
33
45
|
]);
|
|
34
46
|
|
|
35
|
-
const asn1 = plugins.nodeForge.asn1;
|
|
36
|
-
const rawBytes = plugins.nodeForge.util.binary.raw;
|
|
37
|
-
|
|
38
47
|
const invalidKey = () => createSmartCryptoError('INVALID_KEY');
|
|
39
48
|
const unsupportedProfile = () => createSmartCryptoError('UNSUPPORTED_PROFILE');
|
|
40
49
|
|
|
41
|
-
// ========================================
|
|
42
|
-
// ASN.1 encoding
|
|
43
|
-
// ========================================
|
|
44
|
-
const createSequence = (childrenArg: TAsn1[]): TAsn1 =>
|
|
45
|
-
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, childrenArg);
|
|
46
|
-
|
|
47
|
-
const createOid = (oidArg: string): TAsn1 =>
|
|
48
|
-
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oidArg).getBytes());
|
|
49
|
-
|
|
50
|
-
const createOctetString = (bytesArg: Uint8Array): TAsn1 =>
|
|
51
|
-
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, rawBytes.encode(bytesArg));
|
|
52
|
-
|
|
53
|
-
const createInteger = (valueArg: number): TAsn1 =>
|
|
54
|
-
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(valueArg).getBytes());
|
|
55
|
-
|
|
56
|
-
const createNull = (): TAsn1 => asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');
|
|
57
|
-
|
|
58
|
-
// ========================================
|
|
59
|
-
// ASN.1 decoding
|
|
60
|
-
// ========================================
|
|
61
|
-
const readSequence = (nodeArg: TAsn1 | undefined, minLengthArg: number, maxLengthArg: number): TAsn1[] => {
|
|
62
|
-
if (
|
|
63
|
-
!nodeArg
|
|
64
|
-
|| nodeArg.tagClass !== asn1.Class.UNIVERSAL
|
|
65
|
-
|| nodeArg.type !== asn1.Type.SEQUENCE
|
|
66
|
-
|| !Array.isArray(nodeArg.value)
|
|
67
|
-
|| nodeArg.value.length < minLengthArg
|
|
68
|
-
|| nodeArg.value.length > maxLengthArg
|
|
69
|
-
) {
|
|
70
|
-
throw invalidKey();
|
|
71
|
-
}
|
|
72
|
-
return nodeArg.value;
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
const readPrimitive = (nodeArg: TAsn1 | undefined, typeArg: plugins.nodeForge.asn1.Type): string => {
|
|
76
|
-
if (
|
|
77
|
-
!nodeArg
|
|
78
|
-
|| nodeArg.tagClass !== asn1.Class.UNIVERSAL
|
|
79
|
-
|| nodeArg.type !== typeArg
|
|
80
|
-
|| typeof nodeArg.value !== 'string'
|
|
81
|
-
) {
|
|
82
|
-
throw invalidKey();
|
|
83
|
-
}
|
|
84
|
-
return nodeArg.value;
|
|
85
|
-
};
|
|
86
|
-
|
|
87
|
-
const readOid = (nodeArg: TAsn1 | undefined): string => asn1.derToOid(readPrimitive(nodeArg, asn1.Type.OID));
|
|
88
|
-
|
|
89
|
-
const readOctetString = (nodeArg: TAsn1 | undefined): Uint8Array =>
|
|
90
|
-
rawBytes.decode(readPrimitive(nodeArg, asn1.Type.OCTETSTRING));
|
|
91
|
-
|
|
92
|
-
/** Reads a non-negative INTEGER that fits into 31 bits. */
|
|
93
|
-
const readSmallInteger = (nodeArg: TAsn1 | undefined): number => {
|
|
94
|
-
const integerBytes = readPrimitive(nodeArg, asn1.Type.INTEGER);
|
|
95
|
-
if (integerBytes.length < 1 || integerBytes.length > 4 || integerBytes.charCodeAt(0) >= 0x80) {
|
|
96
|
-
throw invalidKey();
|
|
97
|
-
}
|
|
98
|
-
return asn1.derToInteger(integerBytes);
|
|
99
|
-
};
|
|
100
|
-
|
|
101
50
|
// ========================================
|
|
102
51
|
// PBES2
|
|
103
52
|
// ========================================
|
|
@@ -150,7 +99,7 @@ const deriveAesCbcKey = async (optionsArg: {
|
|
|
150
99
|
* PBES2 with PBKDF2-HMAC-SHA256 (600,000 iterations, 16-byte salt) and AES-256-CBC.
|
|
151
100
|
*/
|
|
152
101
|
export const encryptPrivateKeyInfo = async (
|
|
153
|
-
|
|
102
|
+
privateKeyInfoDerArg: Uint8Array,
|
|
154
103
|
passphraseArg: string,
|
|
155
104
|
): Promise<string> => {
|
|
156
105
|
assertPassphrase(passphraseArg, { allowEmpty: false });
|
|
@@ -166,9 +115,7 @@ export const encryptPrivateKeyInfo = async (
|
|
|
166
115
|
usage: 'encrypt',
|
|
167
116
|
});
|
|
168
117
|
|
|
169
|
-
const privateKeyInfoBuffer = toArrayBuffer(
|
|
170
|
-
rawBytes.decode(asn1.toDer(privateKeyInfoArg).getBytes()),
|
|
171
|
-
);
|
|
118
|
+
const privateKeyInfoBuffer = toArrayBuffer(privateKeyInfoDerArg);
|
|
172
119
|
let encryptedData: Uint8Array;
|
|
173
120
|
try {
|
|
174
121
|
encryptedData = new Uint8Array(
|
|
@@ -180,82 +127,76 @@ export const encryptPrivateKeyInfo = async (
|
|
|
180
127
|
new Uint8Array(privateKeyInfoBuffer).fill(0);
|
|
181
128
|
}
|
|
182
129
|
|
|
183
|
-
const encryptedPrivateKeyInfo =
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
return
|
|
201
|
-
type: encryptedPemType,
|
|
202
|
-
body: asn1.toDer(encryptedPrivateKeyInfo).getBytes(),
|
|
203
|
-
});
|
|
130
|
+
const encryptedPrivateKeyInfo = encodeDerSequence(
|
|
131
|
+
encodeDerSequence(
|
|
132
|
+
encodeDerOid(pbes2Oid),
|
|
133
|
+
encodeDerSequence(
|
|
134
|
+
encodeDerSequence(
|
|
135
|
+
encodeDerOid(pbkdf2Oid),
|
|
136
|
+
encodeDerSequence(
|
|
137
|
+
encodeDerOctetString(salt),
|
|
138
|
+
encodeDerSmallInteger(pbkdf2Iterations),
|
|
139
|
+
encodeDerSequence(encodeDerOid(hmacWithSha256Oid), encodeDerNull()),
|
|
140
|
+
),
|
|
141
|
+
),
|
|
142
|
+
encodeDerSequence(encodeDerOid(aes256CbcOid), encodeDerOctetString(iv)),
|
|
143
|
+
),
|
|
144
|
+
),
|
|
145
|
+
encodeDerOctetString(encryptedData),
|
|
146
|
+
);
|
|
147
|
+
return encodePem(encryptedPemType, encryptedPrivateKeyInfo);
|
|
204
148
|
};
|
|
205
149
|
|
|
206
150
|
/**
|
|
207
151
|
* Decrypts an `ENCRYPTED PRIVATE KEY` PEM (PKCS#8 PBES2 with PBKDF2 and
|
|
208
152
|
* AES-CBC, as written by OpenSSL, Node.js and `encryptPrivateKeyInfo()`) and
|
|
209
|
-
* returns the PrivateKeyInfo
|
|
153
|
+
* returns the DER-encoded PrivateKeyInfo, which the caller must zero after use.
|
|
154
|
+
* An empty passphrase is accepted here only.
|
|
210
155
|
*/
|
|
211
156
|
export const decryptPrivateKeyInfo = async (
|
|
212
157
|
pemArg: string,
|
|
213
158
|
passphraseArg: string,
|
|
214
|
-
): Promise<
|
|
159
|
+
): Promise<Uint8Array> => {
|
|
215
160
|
assertPassphrase(passphraseArg, { allowEmpty: true });
|
|
216
161
|
if (typeof pemArg !== 'string') {
|
|
217
162
|
throw invalidKey();
|
|
218
163
|
}
|
|
219
|
-
let encryptedPrivateKeyInfo:
|
|
164
|
+
let encryptedPrivateKeyInfo: IDerElement;
|
|
220
165
|
try {
|
|
221
|
-
const
|
|
222
|
-
if (
|
|
223
|
-
pemMessages.length !== 1
|
|
224
|
-
|| pemMessages[0].type !== encryptedPemType
|
|
225
|
-
|| pemMessages[0].procType
|
|
226
|
-
) {
|
|
166
|
+
const pemBlocks = decodePemBlocks(pemArg);
|
|
167
|
+
if (pemBlocks.length !== 1 || pemBlocks[0].type !== encryptedPemType) {
|
|
227
168
|
throw invalidKey();
|
|
228
169
|
}
|
|
229
|
-
encryptedPrivateKeyInfo =
|
|
170
|
+
encryptedPrivateKeyInfo = decodeDerElement(pemBlocks[0].body);
|
|
230
171
|
} catch {
|
|
231
172
|
throw invalidKey();
|
|
232
173
|
}
|
|
233
174
|
|
|
234
|
-
const [encryptionAlgorithm, encryptedDataNode] =
|
|
235
|
-
const [schemeOidNode, pbes2Params] =
|
|
236
|
-
if (
|
|
175
|
+
const [encryptionAlgorithm, encryptedDataNode] = readDerSequence(encryptedPrivateKeyInfo, 2, 2);
|
|
176
|
+
const [schemeOidNode, pbes2Params] = readDerSequence(encryptionAlgorithm, 2, 2);
|
|
177
|
+
if (readDerOid(schemeOidNode) !== pbes2Oid) {
|
|
237
178
|
throw unsupportedProfile();
|
|
238
179
|
}
|
|
239
|
-
const [keyDerivationFunc, encryptionScheme] =
|
|
240
|
-
const [kdfOidNode, kdfParamsNode] =
|
|
241
|
-
if (
|
|
180
|
+
const [keyDerivationFunc, encryptionScheme] = readDerSequence(pbes2Params, 2, 2);
|
|
181
|
+
const [kdfOidNode, kdfParamsNode] = readDerSequence(keyDerivationFunc, 2, 2);
|
|
182
|
+
if (readDerOid(kdfOidNode) !== pbkdf2Oid) {
|
|
242
183
|
throw unsupportedProfile();
|
|
243
184
|
}
|
|
244
185
|
|
|
245
186
|
// PBKDF2-params ::= SEQUENCE { salt, iterationCount, keyLength OPTIONAL, prf DEFAULT hmacWithSHA1 }
|
|
246
|
-
const pbkdf2Params =
|
|
247
|
-
const salt =
|
|
248
|
-
const iterations =
|
|
187
|
+
const pbkdf2Params = readDerSequence(kdfParamsNode, 2, 4);
|
|
188
|
+
const salt = readDerOctetString(pbkdf2Params[0]);
|
|
189
|
+
const iterations = readDerSmallInteger(pbkdf2Params[1]);
|
|
249
190
|
let paramIndex = 2;
|
|
250
191
|
let keyLengthBytes: number | undefined;
|
|
251
|
-
if (pbkdf2Params[paramIndex]?.
|
|
252
|
-
keyLengthBytes =
|
|
192
|
+
if (pbkdf2Params[paramIndex]?.tag === derTags.integer) {
|
|
193
|
+
keyLengthBytes = readDerSmallInteger(pbkdf2Params[paramIndex]);
|
|
253
194
|
paramIndex++;
|
|
254
195
|
}
|
|
255
196
|
let prfHash = 'SHA-1';
|
|
256
197
|
if (pbkdf2Params[paramIndex]) {
|
|
257
|
-
const [prfOidNode] =
|
|
258
|
-
const configuredPrfHash = prfHashByOid.get(
|
|
198
|
+
const [prfOidNode] = readDerSequence(pbkdf2Params[paramIndex], 1, 2);
|
|
199
|
+
const configuredPrfHash = prfHashByOid.get(readDerOid(prfOidNode));
|
|
259
200
|
if (!configuredPrfHash) {
|
|
260
201
|
throw unsupportedProfile();
|
|
261
202
|
}
|
|
@@ -269,16 +210,16 @@ export const decryptPrivateKeyInfo = async (
|
|
|
269
210
|
throw unsupportedProfile();
|
|
270
211
|
}
|
|
271
212
|
|
|
272
|
-
const [cipherOidNode, ivNode] =
|
|
273
|
-
const keyBits = aesCbcKeyBitsByOid.get(
|
|
213
|
+
const [cipherOidNode, ivNode] = readDerSequence(encryptionScheme, 2, 2);
|
|
214
|
+
const keyBits = aesCbcKeyBitsByOid.get(readDerOid(cipherOidNode));
|
|
274
215
|
if (!keyBits) {
|
|
275
216
|
throw unsupportedProfile();
|
|
276
217
|
}
|
|
277
|
-
const iv =
|
|
218
|
+
const iv = readDerOctetString(ivNode);
|
|
278
219
|
if (iv.byteLength !== aesCbcIvBytes || (keyLengthBytes !== undefined && keyLengthBytes * 8 !== keyBits)) {
|
|
279
220
|
throw invalidKey();
|
|
280
221
|
}
|
|
281
|
-
const encryptedData =
|
|
222
|
+
const encryptedData = readDerOctetString(encryptedDataNode);
|
|
282
223
|
|
|
283
224
|
const key = await deriveAesCbcKey({
|
|
284
225
|
passphrase: passphraseArg,
|
|
@@ -301,11 +242,12 @@ export const decryptPrivateKeyInfo = async (
|
|
|
301
242
|
throw createSmartCryptoError('AUTHENTICATION_FAILED');
|
|
302
243
|
}
|
|
303
244
|
try {
|
|
304
|
-
|
|
245
|
+
// PrivateKeyInfo ::= SEQUENCE { version, privateKeyAlgorithm, privateKey, attributes OPTIONAL }
|
|
246
|
+
readDerSequence(decodeDerElement(privateKeyInfoBytes), 3, 4);
|
|
305
247
|
} catch {
|
|
306
248
|
// A wrong passphrase can yield valid CBC padding over undecodable plaintext.
|
|
307
|
-
throw createSmartCryptoError('AUTHENTICATION_FAILED');
|
|
308
|
-
} finally {
|
|
309
249
|
privateKeyInfoBytes.fill(0);
|
|
250
|
+
throw createSmartCryptoError('AUTHENTICATION_FAILED');
|
|
310
251
|
}
|
|
252
|
+
return privateKeyInfoBytes;
|
|
311
253
|
};
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { createSmartCryptoError } from './smartcrypto.errors.js';
|
|
2
|
+
import {
|
|
3
|
+
decodeDerElement,
|
|
4
|
+
derTags,
|
|
5
|
+
encodeDerBitString,
|
|
6
|
+
encodeDerNull,
|
|
7
|
+
encodeDerOctetString,
|
|
8
|
+
encodeDerOid,
|
|
9
|
+
encodeDerSequence,
|
|
10
|
+
encodeDerSmallInteger,
|
|
11
|
+
encodeDerUnsignedInteger,
|
|
12
|
+
readDerBitString,
|
|
13
|
+
readDerNull,
|
|
14
|
+
readDerOctetString,
|
|
15
|
+
readDerOid,
|
|
16
|
+
readDerSequence,
|
|
17
|
+
readDerSmallInteger,
|
|
18
|
+
readDerUnsignedInteger,
|
|
19
|
+
type IDerElement,
|
|
20
|
+
} from './smartcrypto.der.js';
|
|
21
|
+
|
|
22
|
+
/** RSA public key integers as unsigned big-endian bytes. */
|
|
23
|
+
export interface IRsaPublicKeyComponents {
|
|
24
|
+
modulus: Uint8Array;
|
|
25
|
+
publicExponent: Uint8Array;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Two-prime RSA private key integers as unsigned big-endian bytes, named after RFC 8017. */
|
|
29
|
+
export interface IRsaPrivateKeyComponents extends IRsaPublicKeyComponents {
|
|
30
|
+
privateExponent: Uint8Array;
|
|
31
|
+
prime1: Uint8Array;
|
|
32
|
+
prime2: Uint8Array;
|
|
33
|
+
exponent1: Uint8Array;
|
|
34
|
+
exponent2: Uint8Array;
|
|
35
|
+
coefficient: Uint8Array;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const rsaEncryptionOid = '1.2.840.113549.1.1.1';
|
|
39
|
+
const privateKeyComponentNames = [
|
|
40
|
+
'modulus',
|
|
41
|
+
'publicExponent',
|
|
42
|
+
'privateExponent',
|
|
43
|
+
'prime1',
|
|
44
|
+
'prime2',
|
|
45
|
+
'exponent1',
|
|
46
|
+
'exponent2',
|
|
47
|
+
'coefficient',
|
|
48
|
+
] as const;
|
|
49
|
+
|
|
50
|
+
const invalidKey = () => createSmartCryptoError('INVALID_KEY');
|
|
51
|
+
|
|
52
|
+
/** Copies a positive unsigned integer and strips its leading zero bytes. */
|
|
53
|
+
const requirePositiveInteger = (valueArg: unknown): Uint8Array => {
|
|
54
|
+
if (!(valueArg instanceof Uint8Array)) {
|
|
55
|
+
throw invalidKey();
|
|
56
|
+
}
|
|
57
|
+
let start = 0;
|
|
58
|
+
while (start < valueArg.byteLength && valueArg[start] === 0) {
|
|
59
|
+
start++;
|
|
60
|
+
}
|
|
61
|
+
if (start === valueArg.byteLength) {
|
|
62
|
+
throw invalidKey();
|
|
63
|
+
}
|
|
64
|
+
return valueArg.slice(start);
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export const bitLengthOf = (magnitudeArg: Uint8Array): number => {
|
|
68
|
+
const firstByteIndex = magnitudeArg.findIndex((byteArg) => byteArg !== 0);
|
|
69
|
+
if (firstByteIndex < 0) {
|
|
70
|
+
return 0;
|
|
71
|
+
}
|
|
72
|
+
return (magnitudeArg.byteLength - firstByteIndex - 1) * 8
|
|
73
|
+
+ (32 - Math.clz32(magnitudeArg[firstByteIndex]));
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export const copyRsaPublicKeyComponents = (
|
|
77
|
+
componentsArg: IRsaPublicKeyComponents,
|
|
78
|
+
): IRsaPublicKeyComponents => {
|
|
79
|
+
if (componentsArg === null || typeof componentsArg !== 'object') {
|
|
80
|
+
throw invalidKey();
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
modulus: requirePositiveInteger(componentsArg.modulus),
|
|
84
|
+
publicExponent: requirePositiveInteger(componentsArg.publicExponent),
|
|
85
|
+
};
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
export const copyRsaPrivateKeyComponents = (
|
|
89
|
+
componentsArg: IRsaPrivateKeyComponents,
|
|
90
|
+
): IRsaPrivateKeyComponents => {
|
|
91
|
+
if (componentsArg === null || typeof componentsArg !== 'object') {
|
|
92
|
+
throw invalidKey();
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
modulus: requirePositiveInteger(componentsArg.modulus),
|
|
96
|
+
publicExponent: requirePositiveInteger(componentsArg.publicExponent),
|
|
97
|
+
privateExponent: requirePositiveInteger(componentsArg.privateExponent),
|
|
98
|
+
prime1: requirePositiveInteger(componentsArg.prime1),
|
|
99
|
+
prime2: requirePositiveInteger(componentsArg.prime2),
|
|
100
|
+
exponent1: requirePositiveInteger(componentsArg.exponent1),
|
|
101
|
+
exponent2: requirePositiveInteger(componentsArg.exponent2),
|
|
102
|
+
coefficient: requirePositiveInteger(componentsArg.coefficient),
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
export const zeroRsaPrivateKeyComponents = (componentsArg: IRsaPrivateKeyComponents): void => {
|
|
107
|
+
for (const name of privateKeyComponentNames) {
|
|
108
|
+
componentsArg[name].fill(0);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/** AlgorithmIdentifier for rsaEncryption; the parameters must be NULL or absent. */
|
|
113
|
+
const readRsaAlgorithmIdentifier = (elementArg: IDerElement | undefined): void => {
|
|
114
|
+
const [oid, parameters] = readDerSequence(elementArg, 1, 2);
|
|
115
|
+
if (readDerOid(oid) !== rsaEncryptionOid) {
|
|
116
|
+
throw invalidKey();
|
|
117
|
+
}
|
|
118
|
+
if (parameters) {
|
|
119
|
+
readDerNull(parameters);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const encodeRsaAlgorithmIdentifier = (): Uint8Array =>
|
|
124
|
+
encodeDerSequence(encodeDerOid(rsaEncryptionOid), encodeDerNull());
|
|
125
|
+
|
|
126
|
+
// ========================================
|
|
127
|
+
// Public keys
|
|
128
|
+
// ========================================
|
|
129
|
+
/** Decodes a PKCS#1 `RSAPublicKey`. */
|
|
130
|
+
export const decodeRsaPublicKey = (derArg: Uint8Array): IRsaPublicKeyComponents => {
|
|
131
|
+
const [modulus, publicExponent] = readDerSequence(decodeDerElement(derArg), 2, 2);
|
|
132
|
+
return copyRsaPublicKeyComponents({
|
|
133
|
+
modulus: readDerUnsignedInteger(modulus),
|
|
134
|
+
publicExponent: readDerUnsignedInteger(publicExponent),
|
|
135
|
+
});
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
export const encodeRsaPublicKey = (componentsArg: IRsaPublicKeyComponents): Uint8Array =>
|
|
139
|
+
encodeDerSequence(
|
|
140
|
+
encodeDerUnsignedInteger(componentsArg.modulus),
|
|
141
|
+
encodeDerUnsignedInteger(componentsArg.publicExponent),
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
/** Decodes an RSA `SubjectPublicKeyInfo` (SPKI). */
|
|
145
|
+
export const decodeSubjectPublicKeyInfo = (derArg: Uint8Array): IRsaPublicKeyComponents => {
|
|
146
|
+
const [algorithm, subjectPublicKey] = readDerSequence(decodeDerElement(derArg), 2, 2);
|
|
147
|
+
readRsaAlgorithmIdentifier(algorithm);
|
|
148
|
+
return decodeRsaPublicKey(readDerBitString(subjectPublicKey));
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
export const encodeSubjectPublicKeyInfo = (componentsArg: IRsaPublicKeyComponents): Uint8Array =>
|
|
152
|
+
encodeDerSequence(
|
|
153
|
+
encodeRsaAlgorithmIdentifier(),
|
|
154
|
+
encodeDerBitString(encodeRsaPublicKey(componentsArg)),
|
|
155
|
+
);
|
|
156
|
+
|
|
157
|
+
// ========================================
|
|
158
|
+
// Private keys
|
|
159
|
+
// ========================================
|
|
160
|
+
/** Decodes a two-prime PKCS#1 `RSAPrivateKey` (version 0). */
|
|
161
|
+
export const decodeRsaPrivateKey = (derArg: Uint8Array): IRsaPrivateKeyComponents => {
|
|
162
|
+
const [version, ...integers] = readDerSequence(decodeDerElement(derArg), 9, 9);
|
|
163
|
+
if (readDerSmallInteger(version) !== 0) {
|
|
164
|
+
throw invalidKey();
|
|
165
|
+
}
|
|
166
|
+
const values = integers.map(readDerUnsignedInteger);
|
|
167
|
+
const [
|
|
168
|
+
modulus,
|
|
169
|
+
publicExponent,
|
|
170
|
+
privateExponent,
|
|
171
|
+
prime1,
|
|
172
|
+
prime2,
|
|
173
|
+
exponent1,
|
|
174
|
+
exponent2,
|
|
175
|
+
coefficient,
|
|
176
|
+
] = values;
|
|
177
|
+
try {
|
|
178
|
+
return copyRsaPrivateKeyComponents({
|
|
179
|
+
modulus,
|
|
180
|
+
publicExponent,
|
|
181
|
+
privateExponent,
|
|
182
|
+
prime1,
|
|
183
|
+
prime2,
|
|
184
|
+
exponent1,
|
|
185
|
+
exponent2,
|
|
186
|
+
coefficient,
|
|
187
|
+
});
|
|
188
|
+
} finally {
|
|
189
|
+
for (const value of values) {
|
|
190
|
+
value.fill(0);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
export const encodeRsaPrivateKey = (componentsArg: IRsaPrivateKeyComponents): Uint8Array =>
|
|
196
|
+
encodeDerSequence(
|
|
197
|
+
encodeDerSmallInteger(0),
|
|
198
|
+
...privateKeyComponentNames.map((nameArg) => encodeDerUnsignedInteger(componentsArg[nameArg])),
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
/** Decodes a PKCS#8 `PrivateKeyInfo` that wraps an RSA private key; attributes are ignored. */
|
|
202
|
+
export const decodePrivateKeyInfo = (derArg: Uint8Array): IRsaPrivateKeyComponents => {
|
|
203
|
+
const [version, algorithm, privateKey, attributes] = readDerSequence(
|
|
204
|
+
decodeDerElement(derArg),
|
|
205
|
+
3,
|
|
206
|
+
4,
|
|
207
|
+
);
|
|
208
|
+
if (readDerSmallInteger(version) !== 0) {
|
|
209
|
+
throw invalidKey();
|
|
210
|
+
}
|
|
211
|
+
if (attributes && attributes.tag !== derTags.contextSpecificConstructed0) {
|
|
212
|
+
throw invalidKey();
|
|
213
|
+
}
|
|
214
|
+
readRsaAlgorithmIdentifier(algorithm);
|
|
215
|
+
const rsaPrivateKeyDer = readDerOctetString(privateKey);
|
|
216
|
+
try {
|
|
217
|
+
return decodeRsaPrivateKey(rsaPrivateKeyDer);
|
|
218
|
+
} finally {
|
|
219
|
+
rsaPrivateKeyDer.fill(0);
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
export const encodePrivateKeyInfo = (componentsArg: IRsaPrivateKeyComponents): Uint8Array => {
|
|
224
|
+
const rsaPrivateKeyDer = encodeRsaPrivateKey(componentsArg);
|
|
225
|
+
try {
|
|
226
|
+
return encodeDerSequence(
|
|
227
|
+
encodeDerSmallInteger(0),
|
|
228
|
+
encodeRsaAlgorithmIdentifier(),
|
|
229
|
+
encodeDerOctetString(rsaPrivateKeyDer),
|
|
230
|
+
);
|
|
231
|
+
} finally {
|
|
232
|
+
rsaPrivateKeyDer.fill(0);
|
|
233
|
+
}
|
|
234
|
+
};
|