@push.rocks/smartcrypto 2.2.0 → 2.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.
- package/.smartconfig.json +1 -4
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/index.d.ts +1 -0
- package/dist_ts/index.js +2 -1
- package/dist_ts/smartcrypto.classes.keypair.d.ts +6 -1
- package/dist_ts/smartcrypto.classes.keypair.js +11 -5
- package/dist_ts/smartcrypto.classes.privatekey.d.ts +13 -0
- package/dist_ts/smartcrypto.classes.privatekey.js +26 -1
- package/dist_ts/smartcrypto.classes.smartcrypto.d.ts +2 -2
- package/dist_ts/smartcrypto.classes.smartcrypto.js +3 -3
- package/dist_ts/smartcrypto.errors.d.ts +1 -1
- package/dist_ts/smartcrypto.errors.js +1 -1
- package/dist_ts/smartcrypto.hash.d.ts +15 -0
- package/dist_ts/smartcrypto.hash.js +159 -0
- package/dist_ts/smartcrypto.internal.d.ts +10 -0
- package/dist_ts/smartcrypto.internal.js +51 -1
- package/dist_ts/smartcrypto.pkcs8.d.ts +14 -0
- package/dist_ts/smartcrypto.pkcs8.js +252 -0
- package/dist_ts_node/index.d.ts +1 -0
- package/dist_ts_node/index.js +2 -0
- package/dist_ts_node/smartcrypto.hash.d.ts +17 -0
- package/dist_ts_node/smartcrypto.hash.js +60 -0
- package/dist_ts_node/smartcrypto.plugins.d.ts +4 -0
- package/dist_ts_node/smartcrypto.plugins.js +6 -0
- package/package.json +16 -8
- package/readme.md +110 -3
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/index.ts +1 -0
- package/ts/smartcrypto.classes.keypair.ts +18 -4
- package/ts/smartcrypto.classes.privatekey.ts +34 -0
- package/ts/smartcrypto.classes.smartcrypto.ts +3 -3
- package/ts/smartcrypto.errors.ts +1 -0
- package/ts/smartcrypto.hash.ts +203 -0
- package/ts/smartcrypto.internal.ts +57 -0
- package/ts/smartcrypto.pkcs8.ts +311 -0
- package/ts_node/index.ts +1 -0
- package/ts_node/smartcrypto.hash.ts +88 -0
- package/ts_node/smartcrypto.plugins.ts +6 -0
- package/ts_node/tsconfig.json +6 -0
- package/readme.hints.md +0 -1
- /package/{license → license.md} +0 -0
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import * as plugins from './smartcrypto.plugins.js';
|
|
2
|
+
import { createSmartCryptoError } from './smartcrypto.errors.js';
|
|
3
|
+
import { decryptPrivateKeyInfo, encryptPrivateKeyInfo } from './smartcrypto.pkcs8.js';
|
|
2
4
|
|
|
3
5
|
export class PrivateKey {
|
|
4
6
|
// STATIC
|
|
@@ -11,6 +13,24 @@ export class PrivateKey {
|
|
|
11
13
|
return new PrivateKey(plugins.nodeForge.pki.privateKeyFromPem(pemString));
|
|
12
14
|
}
|
|
13
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Parses a passphrase-encrypted PKCS#8 RSA private key
|
|
18
|
+
* (`-----BEGIN ENCRYPTED PRIVATE KEY-----`, PBES2 with PBKDF2 and AES-CBC),
|
|
19
|
+
* as produced by `toEncryptedPemString()`, Node.js or OpenSSL. An empty
|
|
20
|
+
* passphrase is accepted for keys stored by `@push.rocks/smartkey`.
|
|
21
|
+
*/
|
|
22
|
+
public static async fromEncryptedPemString(
|
|
23
|
+
pemString: string,
|
|
24
|
+
passphraseArg: string,
|
|
25
|
+
): Promise<PrivateKey> {
|
|
26
|
+
const privateKeyInfo = await decryptPrivateKeyInfo(pemString, passphraseArg);
|
|
27
|
+
try {
|
|
28
|
+
return new PrivateKey(plugins.nodeForge.pki.privateKeyFromAsn1(privateKeyInfo));
|
|
29
|
+
} catch {
|
|
30
|
+
throw createSmartCryptoError('INVALID_KEY');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
14
34
|
// INSTANCE
|
|
15
35
|
public forgePrivateKey: plugins.nodeForge.pki.rsa.PrivateKey;
|
|
16
36
|
|
|
@@ -22,6 +42,20 @@ export class PrivateKey {
|
|
|
22
42
|
return plugins.nodeForge.pki.privateKeyToPem(this.forgePrivateKey);
|
|
23
43
|
}
|
|
24
44
|
|
|
45
|
+
/**
|
|
46
|
+
* Exports the key as a passphrase-encrypted PKCS#8 PEM
|
|
47
|
+
* (`-----BEGIN ENCRYPTED PRIVATE KEY-----`) using PBES2 with
|
|
48
|
+
* PBKDF2-HMAC-SHA256 (600,000 iterations) and AES-256-CBC via WebCrypto.
|
|
49
|
+
*/
|
|
50
|
+
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
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
25
59
|
public toOpenSSH(): string {
|
|
26
60
|
return plugins.nodeForge.ssh.privateKeyToOpenSSH(this.forgePrivateKey, 'user@host');
|
|
27
61
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as plugins from './smartcrypto.plugins.js';
|
|
2
|
-
import { KeyPair } from './smartcrypto.classes.keypair.js';
|
|
2
|
+
import { KeyPair, type IKeyPairOptions } from './smartcrypto.classes.keypair.js';
|
|
3
3
|
|
|
4
4
|
export class Smartcrypto {
|
|
5
|
-
public async createKeyPair(): Promise<KeyPair> {
|
|
6
|
-
return KeyPair.createNewKeyPair();
|
|
5
|
+
public async createKeyPair(optionsArg: IKeyPairOptions = {}): Promise<KeyPair> {
|
|
6
|
+
return KeyPair.createNewKeyPair(optionsArg);
|
|
7
7
|
}
|
|
8
8
|
}
|
package/ts/smartcrypto.errors.ts
CHANGED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { createSmartCryptoError } from './smartcrypto.errors.js';
|
|
2
|
+
import {
|
|
3
|
+
encodeHex,
|
|
4
|
+
hashReadableStream,
|
|
5
|
+
requireHashInput,
|
|
6
|
+
requireString,
|
|
7
|
+
sha256,
|
|
8
|
+
} from './smartcrypto.internal.js';
|
|
9
|
+
|
|
10
|
+
/** An incremental SHA-256 hasher. `digest()` returns lowercase hex and finalizes the instance. */
|
|
11
|
+
export interface ISha256Hasher {
|
|
12
|
+
update(dataArg: ArrayBuffer | Uint8Array): this;
|
|
13
|
+
digest(): string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const roundConstants = new Uint32Array([
|
|
17
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
|
|
18
|
+
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
19
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
|
20
|
+
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
21
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
|
|
22
|
+
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
23
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
|
|
24
|
+
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
25
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
|
26
|
+
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
27
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
|
|
28
|
+
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
29
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
|
|
30
|
+
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
31
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
|
32
|
+
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
const initialState = new Uint32Array([
|
|
36
|
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
|
37
|
+
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
const rotateRight = (valueArg: number, bitsArg: number): number =>
|
|
41
|
+
(valueArg >>> bitsArg) | (valueArg << (32 - bitsArg));
|
|
42
|
+
|
|
43
|
+
const textEncoder = new TextEncoder();
|
|
44
|
+
|
|
45
|
+
/** FIPS 180-4 SHA-256 in pure JavaScript, so synchronous and incremental hashing works in every runtime. */
|
|
46
|
+
class Sha256Hasher implements ISha256Hasher {
|
|
47
|
+
private readonly state = new Uint32Array(initialState);
|
|
48
|
+
private readonly block = new Uint8Array(64);
|
|
49
|
+
private readonly words = new Uint32Array(64);
|
|
50
|
+
private blockLength = 0;
|
|
51
|
+
private totalBytesHigh = 0;
|
|
52
|
+
private totalBytesLow = 0;
|
|
53
|
+
private finalized = false;
|
|
54
|
+
|
|
55
|
+
public update(dataArg: ArrayBuffer | Uint8Array): this {
|
|
56
|
+
this.requireOpen();
|
|
57
|
+
const bytes = requireHashInput(dataArg);
|
|
58
|
+
this.addByteLength(bytes.byteLength);
|
|
59
|
+
|
|
60
|
+
let offset = 0;
|
|
61
|
+
if (this.blockLength > 0) {
|
|
62
|
+
const copyLength = Math.min(64 - this.blockLength, bytes.byteLength);
|
|
63
|
+
this.block.set(bytes.subarray(0, copyLength), this.blockLength);
|
|
64
|
+
this.blockLength += copyLength;
|
|
65
|
+
offset = copyLength;
|
|
66
|
+
if (this.blockLength === 64) {
|
|
67
|
+
this.processBlock(this.block, 0);
|
|
68
|
+
this.blockLength = 0;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
while (offset + 64 <= bytes.byteLength) {
|
|
73
|
+
this.processBlock(bytes, offset);
|
|
74
|
+
offset += 64;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (offset < bytes.byteLength) {
|
|
78
|
+
this.block.set(bytes.subarray(offset), 0);
|
|
79
|
+
this.blockLength = bytes.byteLength - offset;
|
|
80
|
+
}
|
|
81
|
+
return this;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
public digest(): string {
|
|
85
|
+
this.requireOpen();
|
|
86
|
+
this.finalized = true;
|
|
87
|
+
|
|
88
|
+
const finalLength = this.blockLength < 56 ? 64 : 128;
|
|
89
|
+
const finalBlocks = new Uint8Array(finalLength);
|
|
90
|
+
finalBlocks.set(this.block.subarray(0, this.blockLength));
|
|
91
|
+
finalBlocks[this.blockLength] = 0x80;
|
|
92
|
+
|
|
93
|
+
const bitLengthHigh = ((this.totalBytesHigh << 3) | (this.totalBytesLow >>> 29)) >>> 0;
|
|
94
|
+
const bitLengthLow = (this.totalBytesLow << 3) >>> 0;
|
|
95
|
+
const finalView = new DataView(finalBlocks.buffer);
|
|
96
|
+
finalView.setUint32(finalLength - 8, bitLengthHigh, false);
|
|
97
|
+
finalView.setUint32(finalLength - 4, bitLengthLow, false);
|
|
98
|
+
|
|
99
|
+
for (let offset = 0; offset < finalLength; offset += 64) {
|
|
100
|
+
this.processBlock(finalBlocks, offset);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
let result = '';
|
|
104
|
+
for (const value of this.state) {
|
|
105
|
+
result += value.toString(16).padStart(8, '0');
|
|
106
|
+
}
|
|
107
|
+
this.block.fill(0);
|
|
108
|
+
this.words.fill(0);
|
|
109
|
+
this.state.fill(0);
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private requireOpen(): void {
|
|
114
|
+
if (this.finalized) {
|
|
115
|
+
throw createSmartCryptoError('INVALID_STATE');
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private addByteLength(byteLengthArg: number): void {
|
|
120
|
+
const previousLow = this.totalBytesLow;
|
|
121
|
+
this.totalBytesLow = (this.totalBytesLow + byteLengthArg) >>> 0;
|
|
122
|
+
this.totalBytesHigh = (
|
|
123
|
+
this.totalBytesHigh
|
|
124
|
+
+ Math.floor(byteLengthArg / 0x100000000)
|
|
125
|
+
+ (this.totalBytesLow < previousLow ? 1 : 0)
|
|
126
|
+
) >>> 0;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
private processBlock(bytesArg: Uint8Array, offsetArg: number): void {
|
|
130
|
+
const words = this.words;
|
|
131
|
+
for (let index = 0; index < 16; index++) {
|
|
132
|
+
const offset = offsetArg + index * 4;
|
|
133
|
+
words[index] = (
|
|
134
|
+
(bytesArg[offset] << 24)
|
|
135
|
+
| (bytesArg[offset + 1] << 16)
|
|
136
|
+
| (bytesArg[offset + 2] << 8)
|
|
137
|
+
| bytesArg[offset + 3]
|
|
138
|
+
) >>> 0;
|
|
139
|
+
}
|
|
140
|
+
for (let index = 16; index < 64; index++) {
|
|
141
|
+
const left = words[index - 15];
|
|
142
|
+
const right = words[index - 2];
|
|
143
|
+
const sigma0 = rotateRight(left, 7) ^ rotateRight(left, 18) ^ (left >>> 3);
|
|
144
|
+
const sigma1 = rotateRight(right, 17) ^ rotateRight(right, 19) ^ (right >>> 10);
|
|
145
|
+
words[index] = (words[index - 16] + sigma0 + words[index - 7] + sigma1) >>> 0;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
let a = this.state[0];
|
|
149
|
+
let b = this.state[1];
|
|
150
|
+
let c = this.state[2];
|
|
151
|
+
let d = this.state[3];
|
|
152
|
+
let e = this.state[4];
|
|
153
|
+
let f = this.state[5];
|
|
154
|
+
let g = this.state[6];
|
|
155
|
+
let h = this.state[7];
|
|
156
|
+
|
|
157
|
+
for (let index = 0; index < 64; index++) {
|
|
158
|
+
const sigma1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
|
|
159
|
+
const choice = (e & f) ^ (~e & g);
|
|
160
|
+
const temporary1 = (h + sigma1 + choice + roundConstants[index] + words[index]) >>> 0;
|
|
161
|
+
const sigma0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
|
|
162
|
+
const majority = (a & b) ^ (a & c) ^ (b & c);
|
|
163
|
+
const temporary2 = (sigma0 + majority) >>> 0;
|
|
164
|
+
|
|
165
|
+
h = g;
|
|
166
|
+
g = f;
|
|
167
|
+
f = e;
|
|
168
|
+
e = (d + temporary1) >>> 0;
|
|
169
|
+
d = c;
|
|
170
|
+
c = b;
|
|
171
|
+
b = a;
|
|
172
|
+
a = (temporary1 + temporary2) >>> 0;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
this.state[0] = (this.state[0] + a) >>> 0;
|
|
176
|
+
this.state[1] = (this.state[1] + b) >>> 0;
|
|
177
|
+
this.state[2] = (this.state[2] + c) >>> 0;
|
|
178
|
+
this.state[3] = (this.state[3] + d) >>> 0;
|
|
179
|
+
this.state[4] = (this.state[4] + e) >>> 0;
|
|
180
|
+
this.state[5] = (this.state[5] + f) >>> 0;
|
|
181
|
+
this.state[6] = (this.state[6] + g) >>> 0;
|
|
182
|
+
this.state[7] = (this.state[7] + h) >>> 0;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Creates an incremental SHA-256 hasher that keeps memory bounded regardless of input size. */
|
|
187
|
+
export const createSha256Hasher = (): ISha256Hasher => new Sha256Hasher();
|
|
188
|
+
|
|
189
|
+
/** SHA-256 of the UTF-8 bytes of a string, computed synchronously. */
|
|
190
|
+
export const sha256FromStringSync = (stringArg: string): string =>
|
|
191
|
+
createSha256Hasher().update(textEncoder.encode(requireString(stringArg))).digest();
|
|
192
|
+
|
|
193
|
+
/** SHA-256 of bytes via WebCrypto. */
|
|
194
|
+
export const sha256FromBuffer = async (bufferArg: ArrayBuffer | Uint8Array): Promise<string> =>
|
|
195
|
+
encodeHex(await sha256(requireHashInput(bufferArg)));
|
|
196
|
+
|
|
197
|
+
/** SHA-256 of the UTF-8 bytes of a string via WebCrypto. */
|
|
198
|
+
export const sha256FromString = async (stringArg: string): Promise<string> =>
|
|
199
|
+
await sha256FromBuffer(textEncoder.encode(requireString(stringArg)));
|
|
200
|
+
|
|
201
|
+
/** SHA-256 of a WHATWG byte stream, hashed incrementally. */
|
|
202
|
+
export const sha256FromStream = async (streamArg: ReadableStream<Uint8Array>): Promise<string> =>
|
|
203
|
+
await hashReadableStream(streamArg, createSha256Hasher());
|
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
createSmartCryptoError,
|
|
4
4
|
type TSmartCryptoErrorCode,
|
|
5
5
|
} from './smartcrypto.errors.js';
|
|
6
|
+
import type { ISha256Hasher } from './smartcrypto.hash.js';
|
|
6
7
|
|
|
7
8
|
const base64UrlPattern = /^[A-Za-z0-9_-]*$/;
|
|
8
9
|
|
|
@@ -35,6 +36,62 @@ export const requireLength = (
|
|
|
35
36
|
return valueArg;
|
|
36
37
|
};
|
|
37
38
|
|
|
39
|
+
/** Views hash input as bytes without copying. */
|
|
40
|
+
export const requireHashInput = (valueArg: unknown): Uint8Array => {
|
|
41
|
+
if (valueArg instanceof Uint8Array) {
|
|
42
|
+
return valueArg;
|
|
43
|
+
}
|
|
44
|
+
if (valueArg instanceof ArrayBuffer) {
|
|
45
|
+
return new Uint8Array(valueArg);
|
|
46
|
+
}
|
|
47
|
+
throw createSmartCryptoError('INVALID_ARGUMENT');
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export const requireString = (valueArg: unknown): string => {
|
|
51
|
+
if (typeof valueArg !== 'string') {
|
|
52
|
+
throw createSmartCryptoError('INVALID_ARGUMENT');
|
|
53
|
+
}
|
|
54
|
+
return valueArg;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export const encodeHex = (valueArg: Uint8Array): string => {
|
|
58
|
+
let result = '';
|
|
59
|
+
for (const value of valueArg) {
|
|
60
|
+
result += value.toString(16).padStart(2, '0');
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Feeds a WHATWG byte stream into a hasher. Source errors propagate unchanged;
|
|
67
|
+
* a non-byte chunk cancels the source. The reader lock is always released.
|
|
68
|
+
*/
|
|
69
|
+
export const hashReadableStream = async (
|
|
70
|
+
streamArg: ReadableStream<Uint8Array>,
|
|
71
|
+
hasherArg: ISha256Hasher,
|
|
72
|
+
): Promise<string> => {
|
|
73
|
+
if (typeof streamArg?.getReader !== 'function') {
|
|
74
|
+
throw createSmartCryptoError('INVALID_ARGUMENT');
|
|
75
|
+
}
|
|
76
|
+
const reader = streamArg.getReader();
|
|
77
|
+
try {
|
|
78
|
+
while (true) {
|
|
79
|
+
const { value, done } = await reader.read();
|
|
80
|
+
if (done) {
|
|
81
|
+
return hasherArg.digest();
|
|
82
|
+
}
|
|
83
|
+
if (!(value instanceof Uint8Array)) {
|
|
84
|
+
const error = createSmartCryptoError('INVALID_ARGUMENT');
|
|
85
|
+
await reader.cancel(error);
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
hasherArg.update(value);
|
|
89
|
+
}
|
|
90
|
+
} finally {
|
|
91
|
+
reader.releaseLock();
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
38
95
|
export const toArrayBuffer = (valueArg: Uint8Array): ArrayBuffer => {
|
|
39
96
|
const result = new Uint8Array(valueArg.byteLength);
|
|
40
97
|
result.set(valueArg);
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import * as plugins from './smartcrypto.plugins.js';
|
|
2
|
+
import { createSmartCryptoError } from './smartcrypto.errors.js';
|
|
3
|
+
import { getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
|
|
4
|
+
|
|
5
|
+
type TAsn1 = plugins.nodeForge.asn1.Asn1;
|
|
6
|
+
|
|
7
|
+
const encryptedPemType = 'ENCRYPTED PRIVATE KEY';
|
|
8
|
+
const saltBytes = 16;
|
|
9
|
+
const aesCbcIvBytes = 16;
|
|
10
|
+
/** PBKDF2 iteration count written by `encryptPrivateKeyInfo()`. */
|
|
11
|
+
const pbkdf2Iterations = 600_000;
|
|
12
|
+
/** Upper bound accepted on import, so a crafted PEM cannot stall decryption. */
|
|
13
|
+
const maxPbkdf2Iterations = 10_000_000;
|
|
14
|
+
|
|
15
|
+
const pbes2Oid = '1.2.840.113549.1.5.13';
|
|
16
|
+
const pbkdf2Oid = '1.2.840.113549.1.5.12';
|
|
17
|
+
const hmacWithSha256Oid = '1.2.840.113549.2.9';
|
|
18
|
+
const aes256CbcOid = '2.16.840.1.101.3.4.1.42';
|
|
19
|
+
|
|
20
|
+
/** PBKDF2 PRFs accepted on import; absent PRF parameters mean HMAC-SHA1. */
|
|
21
|
+
const prfHashByOid = new Map<string, string>([
|
|
22
|
+
['1.2.840.113549.2.7', 'SHA-1'],
|
|
23
|
+
[hmacWithSha256Oid, 'SHA-256'],
|
|
24
|
+
['1.2.840.113549.2.10', 'SHA-384'],
|
|
25
|
+
['1.2.840.113549.2.11', 'SHA-512'],
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
/** AES-CBC key sizes accepted on import. */
|
|
29
|
+
const aesCbcKeyBitsByOid = new Map<string, number>([
|
|
30
|
+
['2.16.840.1.101.3.4.1.2', 128],
|
|
31
|
+
['2.16.840.1.101.3.4.1.22', 192],
|
|
32
|
+
[aes256CbcOid, 256],
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
const asn1 = plugins.nodeForge.asn1;
|
|
36
|
+
const rawBytes = plugins.nodeForge.util.binary.raw;
|
|
37
|
+
|
|
38
|
+
const invalidKey = () => createSmartCryptoError('INVALID_KEY');
|
|
39
|
+
const unsupportedProfile = () => createSmartCryptoError('UNSUPPORTED_PROFILE');
|
|
40
|
+
|
|
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
|
+
// ========================================
|
|
102
|
+
// PBES2
|
|
103
|
+
// ========================================
|
|
104
|
+
/**
|
|
105
|
+
* Validates a passphrase. Export requires a non-empty passphrase; import also
|
|
106
|
+
* accepts an empty one, because `@push.rocks/smartkey` stored keys encrypted
|
|
107
|
+
* under an empty passphrase by default.
|
|
108
|
+
*/
|
|
109
|
+
const assertPassphrase = (passphraseArg: string, optionsArg: { allowEmpty: boolean }): void => {
|
|
110
|
+
if (typeof passphraseArg !== 'string' || (!optionsArg.allowEmpty && passphraseArg.length < 1)) {
|
|
111
|
+
throw createSmartCryptoError('INVALID_ARGUMENT');
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const deriveAesCbcKey = async (optionsArg: {
|
|
116
|
+
passphrase: string;
|
|
117
|
+
salt: Uint8Array;
|
|
118
|
+
iterations: number;
|
|
119
|
+
hash: string;
|
|
120
|
+
keyBits: number;
|
|
121
|
+
usage: KeyUsage;
|
|
122
|
+
}): Promise<CryptoKey> => {
|
|
123
|
+
const subtle = getWebCrypto().subtle;
|
|
124
|
+
const passphraseBuffer = toArrayBuffer(new TextEncoder().encode(optionsArg.passphrase));
|
|
125
|
+
try {
|
|
126
|
+
const passphraseKey = await subtle.importKey('raw', passphraseBuffer, 'PBKDF2', false, [
|
|
127
|
+
'deriveKey',
|
|
128
|
+
]);
|
|
129
|
+
return await subtle.deriveKey(
|
|
130
|
+
{
|
|
131
|
+
name: 'PBKDF2',
|
|
132
|
+
salt: toArrayBuffer(optionsArg.salt),
|
|
133
|
+
iterations: optionsArg.iterations,
|
|
134
|
+
hash: optionsArg.hash,
|
|
135
|
+
},
|
|
136
|
+
passphraseKey,
|
|
137
|
+
{ name: 'AES-CBC', length: optionsArg.keyBits },
|
|
138
|
+
false,
|
|
139
|
+
[optionsArg.usage],
|
|
140
|
+
);
|
|
141
|
+
} catch {
|
|
142
|
+
throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
|
|
143
|
+
} finally {
|
|
144
|
+
new Uint8Array(passphraseBuffer).fill(0);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Encrypts a PKCS#8 PrivateKeyInfo into an `ENCRYPTED PRIVATE KEY` PEM using
|
|
150
|
+
* PBES2 with PBKDF2-HMAC-SHA256 (600,000 iterations, 16-byte salt) and AES-256-CBC.
|
|
151
|
+
*/
|
|
152
|
+
export const encryptPrivateKeyInfo = async (
|
|
153
|
+
privateKeyInfoArg: TAsn1,
|
|
154
|
+
passphraseArg: string,
|
|
155
|
+
): Promise<string> => {
|
|
156
|
+
assertPassphrase(passphraseArg, { allowEmpty: false });
|
|
157
|
+
const webCrypto = getWebCrypto();
|
|
158
|
+
const salt = webCrypto.getRandomValues(new Uint8Array(saltBytes));
|
|
159
|
+
const iv = webCrypto.getRandomValues(new Uint8Array(aesCbcIvBytes));
|
|
160
|
+
const key = await deriveAesCbcKey({
|
|
161
|
+
passphrase: passphraseArg,
|
|
162
|
+
salt,
|
|
163
|
+
iterations: pbkdf2Iterations,
|
|
164
|
+
hash: 'SHA-256',
|
|
165
|
+
keyBits: 256,
|
|
166
|
+
usage: 'encrypt',
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
const privateKeyInfoBuffer = toArrayBuffer(
|
|
170
|
+
rawBytes.decode(asn1.toDer(privateKeyInfoArg).getBytes()),
|
|
171
|
+
);
|
|
172
|
+
let encryptedData: Uint8Array;
|
|
173
|
+
try {
|
|
174
|
+
encryptedData = new Uint8Array(
|
|
175
|
+
await webCrypto.subtle.encrypt({ name: 'AES-CBC', iv: toArrayBuffer(iv) }, key, privateKeyInfoBuffer),
|
|
176
|
+
);
|
|
177
|
+
} catch {
|
|
178
|
+
throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
|
|
179
|
+
} finally {
|
|
180
|
+
new Uint8Array(privateKeyInfoBuffer).fill(0);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const encryptedPrivateKeyInfo = createSequence([
|
|
184
|
+
createSequence([
|
|
185
|
+
createOid(pbes2Oid),
|
|
186
|
+
createSequence([
|
|
187
|
+
createSequence([
|
|
188
|
+
createOid(pbkdf2Oid),
|
|
189
|
+
createSequence([
|
|
190
|
+
createOctetString(salt),
|
|
191
|
+
createInteger(pbkdf2Iterations),
|
|
192
|
+
createSequence([createOid(hmacWithSha256Oid), createNull()]),
|
|
193
|
+
]),
|
|
194
|
+
]),
|
|
195
|
+
createSequence([createOid(aes256CbcOid), createOctetString(iv)]),
|
|
196
|
+
]),
|
|
197
|
+
]),
|
|
198
|
+
createOctetString(encryptedData),
|
|
199
|
+
]);
|
|
200
|
+
return plugins.nodeForge.pem.encode({
|
|
201
|
+
type: encryptedPemType,
|
|
202
|
+
body: asn1.toDer(encryptedPrivateKeyInfo).getBytes(),
|
|
203
|
+
});
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Decrypts an `ENCRYPTED PRIVATE KEY` PEM (PKCS#8 PBES2 with PBKDF2 and
|
|
208
|
+
* AES-CBC, as written by OpenSSL, Node.js and `encryptPrivateKeyInfo()`) and
|
|
209
|
+
* returns the PrivateKeyInfo. An empty passphrase is accepted here only.
|
|
210
|
+
*/
|
|
211
|
+
export const decryptPrivateKeyInfo = async (
|
|
212
|
+
pemArg: string,
|
|
213
|
+
passphraseArg: string,
|
|
214
|
+
): Promise<TAsn1> => {
|
|
215
|
+
assertPassphrase(passphraseArg, { allowEmpty: true });
|
|
216
|
+
if (typeof pemArg !== 'string') {
|
|
217
|
+
throw invalidKey();
|
|
218
|
+
}
|
|
219
|
+
let encryptedPrivateKeyInfo: TAsn1;
|
|
220
|
+
try {
|
|
221
|
+
const pemMessages = plugins.nodeForge.pem.decode(pemArg);
|
|
222
|
+
if (
|
|
223
|
+
pemMessages.length !== 1
|
|
224
|
+
|| pemMessages[0].type !== encryptedPemType
|
|
225
|
+
|| pemMessages[0].procType
|
|
226
|
+
) {
|
|
227
|
+
throw invalidKey();
|
|
228
|
+
}
|
|
229
|
+
encryptedPrivateKeyInfo = asn1.fromDer(pemMessages[0].body, true);
|
|
230
|
+
} catch {
|
|
231
|
+
throw invalidKey();
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const [encryptionAlgorithm, encryptedDataNode] = readSequence(encryptedPrivateKeyInfo, 2, 2);
|
|
235
|
+
const [schemeOidNode, pbes2Params] = readSequence(encryptionAlgorithm, 2, 2);
|
|
236
|
+
if (readOid(schemeOidNode) !== pbes2Oid) {
|
|
237
|
+
throw unsupportedProfile();
|
|
238
|
+
}
|
|
239
|
+
const [keyDerivationFunc, encryptionScheme] = readSequence(pbes2Params, 2, 2);
|
|
240
|
+
const [kdfOidNode, kdfParamsNode] = readSequence(keyDerivationFunc, 2, 2);
|
|
241
|
+
if (readOid(kdfOidNode) !== pbkdf2Oid) {
|
|
242
|
+
throw unsupportedProfile();
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// PBKDF2-params ::= SEQUENCE { salt, iterationCount, keyLength OPTIONAL, prf DEFAULT hmacWithSHA1 }
|
|
246
|
+
const pbkdf2Params = readSequence(kdfParamsNode, 2, 4);
|
|
247
|
+
const salt = readOctetString(pbkdf2Params[0]);
|
|
248
|
+
const iterations = readSmallInteger(pbkdf2Params[1]);
|
|
249
|
+
let paramIndex = 2;
|
|
250
|
+
let keyLengthBytes: number | undefined;
|
|
251
|
+
if (pbkdf2Params[paramIndex]?.type === asn1.Type.INTEGER) {
|
|
252
|
+
keyLengthBytes = readSmallInteger(pbkdf2Params[paramIndex]);
|
|
253
|
+
paramIndex++;
|
|
254
|
+
}
|
|
255
|
+
let prfHash = 'SHA-1';
|
|
256
|
+
if (pbkdf2Params[paramIndex]) {
|
|
257
|
+
const [prfOidNode] = readSequence(pbkdf2Params[paramIndex], 1, 2);
|
|
258
|
+
const configuredPrfHash = prfHashByOid.get(readOid(prfOidNode));
|
|
259
|
+
if (!configuredPrfHash) {
|
|
260
|
+
throw unsupportedProfile();
|
|
261
|
+
}
|
|
262
|
+
prfHash = configuredPrfHash;
|
|
263
|
+
paramIndex++;
|
|
264
|
+
}
|
|
265
|
+
if (paramIndex !== pbkdf2Params.length) {
|
|
266
|
+
throw invalidKey();
|
|
267
|
+
}
|
|
268
|
+
if (iterations < 1 || iterations > maxPbkdf2Iterations) {
|
|
269
|
+
throw unsupportedProfile();
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const [cipherOidNode, ivNode] = readSequence(encryptionScheme, 2, 2);
|
|
273
|
+
const keyBits = aesCbcKeyBitsByOid.get(readOid(cipherOidNode));
|
|
274
|
+
if (!keyBits) {
|
|
275
|
+
throw unsupportedProfile();
|
|
276
|
+
}
|
|
277
|
+
const iv = readOctetString(ivNode);
|
|
278
|
+
if (iv.byteLength !== aesCbcIvBytes || (keyLengthBytes !== undefined && keyLengthBytes * 8 !== keyBits)) {
|
|
279
|
+
throw invalidKey();
|
|
280
|
+
}
|
|
281
|
+
const encryptedData = readOctetString(encryptedDataNode);
|
|
282
|
+
|
|
283
|
+
const key = await deriveAesCbcKey({
|
|
284
|
+
passphrase: passphraseArg,
|
|
285
|
+
salt,
|
|
286
|
+
iterations,
|
|
287
|
+
hash: prfHash,
|
|
288
|
+
keyBits,
|
|
289
|
+
usage: 'decrypt',
|
|
290
|
+
});
|
|
291
|
+
let privateKeyInfoBytes: Uint8Array;
|
|
292
|
+
try {
|
|
293
|
+
privateKeyInfoBytes = new Uint8Array(
|
|
294
|
+
await getWebCrypto().subtle.decrypt(
|
|
295
|
+
{ name: 'AES-CBC', iv: toArrayBuffer(iv) },
|
|
296
|
+
key,
|
|
297
|
+
toArrayBuffer(encryptedData),
|
|
298
|
+
),
|
|
299
|
+
);
|
|
300
|
+
} catch {
|
|
301
|
+
throw createSmartCryptoError('AUTHENTICATION_FAILED');
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
return asn1.fromDer(rawBytes.encode(privateKeyInfoBytes), true);
|
|
305
|
+
} catch {
|
|
306
|
+
// A wrong passphrase can yield valid CBC padding over undecodable plaintext.
|
|
307
|
+
throw createSmartCryptoError('AUTHENTICATION_FAILED');
|
|
308
|
+
} finally {
|
|
309
|
+
privateKeyInfoBytes.fill(0);
|
|
310
|
+
}
|
|
311
|
+
};
|
package/ts_node/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './smartcrypto.hash.js';
|