@push.rocks/smartcrypto 2.4.1 → 3.0.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 +1 -2
- package/dist_ts/index.js +1 -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 +44 -0
- package/dist_ts/smartcrypto.der.js +196 -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/package.json +3 -7
- package/readme.md +63 -9
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/index.ts +4 -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 +235 -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/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,235 @@
|
|
|
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
|
+
integer: 0x02,
|
|
12
|
+
bitString: 0x03,
|
|
13
|
+
octetString: 0x04,
|
|
14
|
+
null: 0x05,
|
|
15
|
+
oid: 0x06,
|
|
16
|
+
sequence: 0x30,
|
|
17
|
+
contextSpecificConstructed0: 0xa0,
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
export interface IDerElement {
|
|
21
|
+
tag: number;
|
|
22
|
+
content: Uint8Array;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const invalidKey = () => createSmartCryptoError('INVALID_KEY');
|
|
26
|
+
|
|
27
|
+
/** Reads the element starting at `offsetArg` and returns it with the offset just past it. */
|
|
28
|
+
const readElementAt = (
|
|
29
|
+
bytesArg: Uint8Array,
|
|
30
|
+
offsetArg: number,
|
|
31
|
+
): { element: IDerElement; end: number } => {
|
|
32
|
+
if (offsetArg + 2 > bytesArg.byteLength) {
|
|
33
|
+
throw invalidKey();
|
|
34
|
+
}
|
|
35
|
+
const tag = bytesArg[offsetArg];
|
|
36
|
+
if ((tag & 0x1f) === 0x1f) {
|
|
37
|
+
throw invalidKey();
|
|
38
|
+
}
|
|
39
|
+
const lengthByte = bytesArg[offsetArg + 1];
|
|
40
|
+
let offset = offsetArg + 2;
|
|
41
|
+
let length = lengthByte;
|
|
42
|
+
if (lengthByte & 0x80) {
|
|
43
|
+
const lengthOctets = lengthByte & 0x7f;
|
|
44
|
+
if (lengthOctets < 1 || lengthOctets > 4 || offset + lengthOctets > bytesArg.byteLength) {
|
|
45
|
+
throw invalidKey();
|
|
46
|
+
}
|
|
47
|
+
if (bytesArg[offset] === 0) {
|
|
48
|
+
throw invalidKey();
|
|
49
|
+
}
|
|
50
|
+
length = 0;
|
|
51
|
+
for (let index = 0; index < lengthOctets; index++) {
|
|
52
|
+
length = length * 0x100 + bytesArg[offset + index];
|
|
53
|
+
}
|
|
54
|
+
if (length < 0x80) {
|
|
55
|
+
throw invalidKey();
|
|
56
|
+
}
|
|
57
|
+
offset += lengthOctets;
|
|
58
|
+
}
|
|
59
|
+
const end = offset + length;
|
|
60
|
+
if (end > bytesArg.byteLength) {
|
|
61
|
+
throw invalidKey();
|
|
62
|
+
}
|
|
63
|
+
return { element: { tag, content: bytesArg.subarray(offset, end) }, end };
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** Decodes exactly one DER element that spans all of `bytesArg`. */
|
|
67
|
+
export const decodeDerElement = (bytesArg: Uint8Array): IDerElement => {
|
|
68
|
+
const { element, end } = readElementAt(bytesArg, 0);
|
|
69
|
+
if (end !== bytesArg.byteLength) {
|
|
70
|
+
throw invalidKey();
|
|
71
|
+
}
|
|
72
|
+
return element;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** Decodes the concatenated elements inside a constructed element's content. */
|
|
76
|
+
export const decodeDerChildren = (contentArg: Uint8Array): IDerElement[] => {
|
|
77
|
+
const children: IDerElement[] = [];
|
|
78
|
+
let offset = 0;
|
|
79
|
+
while (offset < contentArg.byteLength) {
|
|
80
|
+
const { element, end } = readElementAt(contentArg, offset);
|
|
81
|
+
children.push(element);
|
|
82
|
+
offset = end;
|
|
83
|
+
}
|
|
84
|
+
return children;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const requireTag = (elementArg: IDerElement | undefined, tagArg: number): IDerElement => {
|
|
88
|
+
if (!elementArg || elementArg.tag !== tagArg) {
|
|
89
|
+
throw invalidKey();
|
|
90
|
+
}
|
|
91
|
+
return elementArg;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
export const readDerSequence = (
|
|
95
|
+
elementArg: IDerElement | undefined,
|
|
96
|
+
minLengthArg: number,
|
|
97
|
+
maxLengthArg: number,
|
|
98
|
+
): IDerElement[] => {
|
|
99
|
+
const children = decodeDerChildren(requireTag(elementArg, derTags.sequence).content);
|
|
100
|
+
if (children.length < minLengthArg || children.length > maxLengthArg) {
|
|
101
|
+
throw invalidKey();
|
|
102
|
+
}
|
|
103
|
+
return children;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Reads a non-negative INTEGER and returns its magnitude without leading zero
|
|
108
|
+
* bytes (zero yields an empty array). Negative values are rejected.
|
|
109
|
+
*/
|
|
110
|
+
export const readDerUnsignedInteger = (elementArg: IDerElement | undefined): Uint8Array => {
|
|
111
|
+
const content = requireTag(elementArg, derTags.integer).content;
|
|
112
|
+
if (content.byteLength < 1 || content[0] & 0x80) {
|
|
113
|
+
throw invalidKey();
|
|
114
|
+
}
|
|
115
|
+
if (content[0] === 0 && content.byteLength > 1 && !(content[1] & 0x80)) {
|
|
116
|
+
throw invalidKey();
|
|
117
|
+
}
|
|
118
|
+
return content.slice(content[0] === 0 ? 1 : 0);
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/** Reads a non-negative INTEGER that fits into 31 bits. */
|
|
122
|
+
export const readDerSmallInteger = (elementArg: IDerElement | undefined): number => {
|
|
123
|
+
const magnitude = readDerUnsignedInteger(elementArg);
|
|
124
|
+
if (magnitude.byteLength > 4 || (magnitude.byteLength === 4 && magnitude[0] & 0x80)) {
|
|
125
|
+
throw invalidKey();
|
|
126
|
+
}
|
|
127
|
+
return magnitude.reduce((valueArg, byteArg) => valueArg * 0x100 + byteArg, 0);
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
export const readDerOctetString = (elementArg: IDerElement | undefined): Uint8Array =>
|
|
131
|
+
requireTag(elementArg, derTags.octetString).content.slice();
|
|
132
|
+
|
|
133
|
+
/** Reads a BIT STRING without unused trailing bits. */
|
|
134
|
+
export const readDerBitString = (elementArg: IDerElement | undefined): Uint8Array => {
|
|
135
|
+
const content = requireTag(elementArg, derTags.bitString).content;
|
|
136
|
+
if (content.byteLength < 1 || content[0] !== 0) {
|
|
137
|
+
throw invalidKey();
|
|
138
|
+
}
|
|
139
|
+
return content.slice(1);
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
export const readDerNull = (elementArg: IDerElement | undefined): void => {
|
|
143
|
+
if (requireTag(elementArg, derTags.null).content.byteLength !== 0) {
|
|
144
|
+
throw invalidKey();
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
export const readDerOid = (elementArg: IDerElement | undefined): string => {
|
|
149
|
+
const content = requireTag(elementArg, derTags.oid).content;
|
|
150
|
+
if (content.byteLength < 1 || content[content.byteLength - 1] & 0x80) {
|
|
151
|
+
throw invalidKey();
|
|
152
|
+
}
|
|
153
|
+
const arcs: number[] = [];
|
|
154
|
+
let value = 0;
|
|
155
|
+
let arcStart = true;
|
|
156
|
+
for (const byte of content) {
|
|
157
|
+
if (arcStart && byte === 0x80) {
|
|
158
|
+
throw invalidKey();
|
|
159
|
+
}
|
|
160
|
+
if (value > (Number.MAX_SAFE_INTEGER - 0x7f) / 0x80) {
|
|
161
|
+
throw invalidKey();
|
|
162
|
+
}
|
|
163
|
+
value = value * 0x80 + (byte & 0x7f);
|
|
164
|
+
arcStart = !(byte & 0x80);
|
|
165
|
+
if (arcStart) {
|
|
166
|
+
arcs.push(value);
|
|
167
|
+
value = 0;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const first = arcs[0];
|
|
171
|
+
const leadingArcs = first < 40 ? [0, first] : first < 80 ? [1, first - 40] : [2, first - 80];
|
|
172
|
+
return [...leadingArcs, ...arcs.slice(1)].join('.');
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// ========================================
|
|
176
|
+
// Encoding
|
|
177
|
+
// ========================================
|
|
178
|
+
const encodeLength = (lengthArg: number): Uint8Array => {
|
|
179
|
+
if (lengthArg < 0x80) {
|
|
180
|
+
return new Uint8Array([lengthArg]);
|
|
181
|
+
}
|
|
182
|
+
const lengthBytes: number[] = [];
|
|
183
|
+
for (let remaining = lengthArg; remaining > 0; remaining = Math.floor(remaining / 0x100)) {
|
|
184
|
+
lengthBytes.unshift(remaining & 0xff);
|
|
185
|
+
}
|
|
186
|
+
return new Uint8Array([0x80 | lengthBytes.length, ...lengthBytes]);
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export const encodeDerElement = (tagArg: number, contentArg: Uint8Array): Uint8Array =>
|
|
190
|
+
concatBytes(new Uint8Array([tagArg]), encodeLength(contentArg.byteLength), contentArg);
|
|
191
|
+
|
|
192
|
+
export const encodeDerSequence = (...childrenArg: Uint8Array[]): Uint8Array =>
|
|
193
|
+
encodeDerElement(derTags.sequence, concatBytes(...childrenArg));
|
|
194
|
+
|
|
195
|
+
/** Encodes an unsigned magnitude as a minimal non-negative INTEGER. */
|
|
196
|
+
export const encodeDerUnsignedInteger = (magnitudeArg: Uint8Array): Uint8Array => {
|
|
197
|
+
let start = 0;
|
|
198
|
+
while (start < magnitudeArg.byteLength && magnitudeArg[start] === 0) {
|
|
199
|
+
start++;
|
|
200
|
+
}
|
|
201
|
+
const magnitude = magnitudeArg.subarray(start);
|
|
202
|
+
if (magnitude.byteLength === 0 || magnitude[0] & 0x80) {
|
|
203
|
+
return encodeDerElement(derTags.integer, concatBytes(new Uint8Array([0]), magnitude));
|
|
204
|
+
}
|
|
205
|
+
return encodeDerElement(derTags.integer, magnitude);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
export const encodeDerSmallInteger = (valueArg: number): Uint8Array => {
|
|
209
|
+
const magnitude: number[] = [];
|
|
210
|
+
for (let remaining = valueArg; remaining > 0; remaining = Math.floor(remaining / 0x100)) {
|
|
211
|
+
magnitude.unshift(remaining & 0xff);
|
|
212
|
+
}
|
|
213
|
+
return encodeDerUnsignedInteger(new Uint8Array(magnitude));
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
export const encodeDerOctetString = (bytesArg: Uint8Array): Uint8Array =>
|
|
217
|
+
encodeDerElement(derTags.octetString, bytesArg);
|
|
218
|
+
|
|
219
|
+
export const encodeDerBitString = (bytesArg: Uint8Array): Uint8Array =>
|
|
220
|
+
encodeDerElement(derTags.bitString, concatBytes(new Uint8Array([0]), bytesArg));
|
|
221
|
+
|
|
222
|
+
export const encodeDerNull = (): Uint8Array => encodeDerElement(derTags.null, new Uint8Array(0));
|
|
223
|
+
|
|
224
|
+
export const encodeDerOid = (oidArg: string): Uint8Array => {
|
|
225
|
+
const arcs = oidArg.split('.').map(Number);
|
|
226
|
+
const content: number[] = [];
|
|
227
|
+
for (const arc of [arcs[0] * 40 + arcs[1], ...arcs.slice(2)]) {
|
|
228
|
+
const arcBytes = [arc & 0x7f];
|
|
229
|
+
for (let remaining = Math.floor(arc / 0x80); remaining > 0; remaining = Math.floor(remaining / 0x80)) {
|
|
230
|
+
arcBytes.unshift(0x80 | (remaining & 0x7f));
|
|
231
|
+
}
|
|
232
|
+
content.push(...arcBytes);
|
|
233
|
+
}
|
|
234
|
+
return encodeDerElement(derTags.oid, new Uint8Array(content));
|
|
235
|
+
};
|
|
@@ -137,15 +137,18 @@ export const isAllZero = (valueArg: Uint8Array): boolean => {
|
|
|
137
137
|
return combined === 0;
|
|
138
138
|
};
|
|
139
139
|
|
|
140
|
-
export const
|
|
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)
|
|
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,
|
|
@@ -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
|
};
|