@push.rocks/smartcrypto 2.1.0 → 2.3.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 +6 -5
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/index.d.ts +4 -0
- package/dist_ts/index.js +4 -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 +17 -0
- package/dist_ts/smartcrypto.errors.js +27 -0
- package/dist_ts/smartcrypto.internal.d.ts +12 -0
- package/dist_ts/smartcrypto.internal.js +133 -0
- package/dist_ts/smartcrypto.pkcs8.d.ts +14 -0
- package/dist_ts/smartcrypto.pkcs8.js +252 -0
- package/dist_ts/smartcrypto.webcrypto.d.ts +49 -0
- package/dist_ts/smartcrypto.webcrypto.js +179 -0
- package/dist_ts/smartcrypto.x25519.d.ts +46 -0
- package/dist_ts/smartcrypto.x25519.js +339 -0
- package/{license → license.md} +2 -1
- package/package.json +14 -9
- package/readme.md +138 -55
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/index.ts +7 -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 +54 -0
- package/ts/smartcrypto.internal.ts +162 -0
- package/ts/smartcrypto.pkcs8.ts +311 -0
- package/ts/smartcrypto.webcrypto.ts +266 -0
- package/ts/smartcrypto.x25519.ts +493 -0
- package/readme.hints.md +0 -1
package/readme.md
CHANGED
|
@@ -1,102 +1,185 @@
|
|
|
1
1
|
# @push.rocks/smartcrypto
|
|
2
|
-
|
|
2
|
+
|
|
3
|
+
Cross-runtime cryptographic primitives for Node.js and browsers, including strict X25519 envelopes, AES-256-GCM authenticated encryption, DEK wrapping, and the existing RSA key APIs.
|
|
4
|
+
|
|
5
|
+
## Issue Reporting and Security
|
|
6
|
+
|
|
7
|
+
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
|
3
8
|
|
|
4
9
|
## Install
|
|
5
|
-
|
|
10
|
+
|
|
6
11
|
```bash
|
|
7
|
-
|
|
12
|
+
pnpm add @push.rocks/smartcrypto
|
|
8
13
|
```
|
|
9
|
-
This will add `@push.rocks/smartcrypto` to your project's dependencies.
|
|
10
14
|
|
|
11
|
-
##
|
|
12
|
-
This guide demonstrates how to use `@push.rocks/smartcrypto` effectively by covering its main functionalities. The module offers straightforward methods for handling cryptographic operations. We'll go through generating keys, encrypting and decrypting data, and converting keys to various formats.
|
|
15
|
+
## X25519 Envelope Profile
|
|
13
16
|
|
|
14
|
-
|
|
15
|
-
Firstly, ensure you have a TypeScript project configured to use ES Modules. Initialize `@push.rocks/smartcrypto` in your project as shown:
|
|
17
|
+
The fixed `x25519-hkdf-sha256-aes-256-gcm-v1` profile seals a `Uint8Array` to one recipient. It uses a fresh ephemeral X25519 key and random 12-byte AES-GCM nonce for every seal. The exact context bytes are mandatory AAD and are also bound into HKDF through their SHA-256 digest.
|
|
16
18
|
|
|
17
19
|
```typescript
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
-
|
|
20
|
+
import {
|
|
21
|
+
generateX25519KeyPair,
|
|
22
|
+
openX25519Envelope,
|
|
23
|
+
sealX25519Envelope,
|
|
24
|
+
} from '@push.rocks/smartcrypto';
|
|
25
|
+
|
|
26
|
+
const encoder = new TextEncoder();
|
|
27
|
+
const recipient = await generateX25519KeyPair();
|
|
28
|
+
const context = encoder.encode('tenant:example/secret:database-password');
|
|
29
|
+
|
|
30
|
+
const envelope = await sealX25519Envelope({
|
|
31
|
+
plaintext: encoder.encode('secret value'),
|
|
32
|
+
recipientPublicKey: recipient.publicKey,
|
|
33
|
+
recipientKeyId: 'recipient-key-2026-01',
|
|
34
|
+
context,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const plaintext = await openX25519Envelope({
|
|
38
|
+
envelope,
|
|
39
|
+
recipientPrivateKey: recipient.privateKey,
|
|
40
|
+
expectedRecipientKeyId: 'recipient-key-2026-01',
|
|
41
|
+
context,
|
|
42
|
+
});
|
|
21
43
|
```
|
|
22
44
|
|
|
23
|
-
|
|
24
|
-
|
|
45
|
+
`generateX25519KeyPair()` returns strict raw 32-byte public and private material. `importX25519PublicKey()`, `exportX25519PublicKey()`, `importX25519PrivateKey()`, and `exportX25519PrivateKey()` provide checked conversion to and from standard `CryptoKey` objects.
|
|
46
|
+
|
|
47
|
+
The envelope has exactly these fields:
|
|
25
48
|
|
|
26
49
|
```typescript
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
50
|
+
interface IX25519EnvelopeV1 {
|
|
51
|
+
schemaVersion: 1;
|
|
52
|
+
profile: 'x25519-hkdf-sha256-aes-256-gcm-v1';
|
|
53
|
+
recipientKeyId: string;
|
|
54
|
+
ephemeralPublicKey: string;
|
|
55
|
+
nonce: string;
|
|
56
|
+
ciphertext: string;
|
|
57
|
+
tag: string;
|
|
58
|
+
contextDigest: string;
|
|
59
|
+
}
|
|
32
60
|
```
|
|
33
61
|
|
|
34
|
-
|
|
62
|
+
All binary envelope fields use canonical unpadded base64url. `parseX25519Envelope()` rejects extra fields, unknown versions and profiles, noncanonical encodings, incorrect fixed lengths, malformed key IDs, and ciphertexts larger than `SMARTCRYPTO_MAX_CIPHERTEXT_BYTES`.
|
|
35
63
|
|
|
36
|
-
|
|
37
|
-
You can manipulate public and private keys using their respective classes. For instance, converting a private key to a PEM string for storage or transmission is straightforward:
|
|
64
|
+
## AES-GCM And DEK Wrapping
|
|
38
65
|
|
|
39
|
-
|
|
40
|
-
import { PrivateKey } from '@push.rocks/smartcrypto';
|
|
66
|
+
`aesGcmEncrypt()` and `aesGcmDecrypt()` accept only `Uint8Array` data and exact 32-byte AES keys. AAD is always required, although an explicitly supplied empty `Uint8Array` is valid. Encryption returns separate `nonce`, `ciphertext`, and 16-byte `tag` fields.
|
|
41
67
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
68
|
+
```typescript
|
|
69
|
+
import {
|
|
70
|
+
aesGcmDecrypt,
|
|
71
|
+
aesGcmEncrypt,
|
|
72
|
+
generateDek,
|
|
73
|
+
generateAes256GcmKey,
|
|
74
|
+
rewrapDek,
|
|
75
|
+
unwrapDek,
|
|
76
|
+
wrapDek,
|
|
77
|
+
} from '@push.rocks/smartcrypto';
|
|
78
|
+
|
|
79
|
+
const payloadAad = new TextEncoder().encode('payload binding');
|
|
80
|
+
const dek = generateDek();
|
|
81
|
+
const encryptedPayload = await aesGcmEncrypt({
|
|
82
|
+
key: dek,
|
|
83
|
+
plaintext: new TextEncoder().encode('payload'),
|
|
84
|
+
aad: payloadAad,
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const oldKek = generateAes256GcmKey();
|
|
88
|
+
const newKek = generateAes256GcmKey();
|
|
89
|
+
const oldWrapAad = new TextEncoder().encode('old KEK binding');
|
|
90
|
+
const newWrapAad = new TextEncoder().encode('new KEK binding');
|
|
91
|
+
const wrappedDek = await wrapDek({ dek, kek: oldKek, wrapAad: oldWrapAad });
|
|
92
|
+
|
|
93
|
+
const rewrappedDek = await rewrapDek({
|
|
94
|
+
wrappedDek,
|
|
95
|
+
currentKek: oldKek,
|
|
96
|
+
currentWrapAad: oldWrapAad,
|
|
97
|
+
newKek,
|
|
98
|
+
newWrapAad,
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const unwrappedDek = await unwrapDek({
|
|
102
|
+
wrappedDek: rewrappedDek,
|
|
103
|
+
kek: newKek,
|
|
104
|
+
wrapAad: newWrapAad,
|
|
105
|
+
});
|
|
106
|
+
const plaintext = await aesGcmDecrypt({
|
|
107
|
+
key: unwrappedDek,
|
|
108
|
+
encryptedData: encryptedPayload,
|
|
109
|
+
aad: payloadAad,
|
|
110
|
+
});
|
|
45
111
|
```
|
|
46
112
|
|
|
47
|
-
|
|
113
|
+
`rewrapDek()` only receives the wrapped DEK, so payload ciphertext, nonce, and tag remain unchanged during KEK rotation.
|
|
48
114
|
|
|
49
|
-
|
|
50
|
-
const privateKeyFromPem = PrivateKey.fromPemString(privateKeyPemString);
|
|
51
|
-
```
|
|
115
|
+
## Errors
|
|
52
116
|
|
|
53
|
-
|
|
117
|
+
Cryptographic and validation failures use `SmartCryptoError` with a stable `TSmartCryptoErrorCode`. Messages, JSON output, Node inspection, stack metadata, and `cause` do not retain plaintext, keys, shared secrets, or ciphertext details.
|
|
54
118
|
|
|
55
|
-
|
|
56
|
-
import { PublicKey } from '@push.rocks/smartcrypto';
|
|
119
|
+
## RSA APIs
|
|
57
120
|
|
|
58
|
-
|
|
59
|
-
console.log(publicKeyPemString);
|
|
121
|
+
The existing `Smartcrypto`, `KeyPair`, `PrivateKey`, and `PublicKey` APIs remain available. RSA key generation and PEM conversion continue to use the existing behavior:
|
|
60
122
|
|
|
61
|
-
|
|
123
|
+
```typescript
|
|
124
|
+
import { Smartcrypto } from '@push.rocks/smartcrypto';
|
|
125
|
+
|
|
126
|
+
const smartCrypto = new Smartcrypto();
|
|
127
|
+
const keyPair = await smartCrypto.createKeyPair();
|
|
128
|
+
const publicKeyPem = keyPair.publicKey.toPemString();
|
|
129
|
+
const privateKeyPem = keyPair.privateKey.toPemString();
|
|
62
130
|
```
|
|
63
131
|
|
|
64
|
-
|
|
65
|
-
|
|
132
|
+
`createKeyPair({ modulusLength })` accepts `2048` (default), `3072`, or `4096`. `PublicKey.toPemString()` writes SPKI (`-----BEGIN PUBLIC KEY-----`) and `PrivateKey.toPemString()` writes an unencrypted PKCS#1 key.
|
|
133
|
+
|
|
134
|
+
`PublicKey.fromCanonicalRsaPublicPemString()` parses one canonical SPKI or PKCS#1 RSA public key with a modulus of at least 2048 bits. `PublicKey.verifyRs256()` verifies exact RSASSA-PKCS1-v1_5/SHA-256 signatures.
|
|
135
|
+
|
|
136
|
+
### Passphrase-Encrypted Private Keys
|
|
137
|
+
|
|
138
|
+
`PrivateKey.toEncryptedPemString(passphrase)` writes a PKCS#8 `-----BEGIN ENCRYPTED PRIVATE KEY-----` PEM using PBES2 with PBKDF2-HMAC-SHA256 (600,000 iterations, 16-byte salt) and AES-256-CBC. `PrivateKey.fromEncryptedPemString(pem, passphrase)` reads PBES2 keys with PBKDF2 (HMAC-SHA1/256/384/512) and AES-128/192/256-CBC, which covers keys written by Node.js and OpenSSL. Both run on WebCrypto and are asynchronous.
|
|
66
139
|
|
|
67
140
|
```typescript
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
// Example: Verifying a signature with the corresponding public key
|
|
74
|
-
const isVerified = publicKey.verifyMessage(message, signedMessage);
|
|
75
|
-
console.log('Is the message verified?', isVerified);
|
|
141
|
+
import { Smartcrypto, PrivateKey } from '@push.rocks/smartcrypto';
|
|
142
|
+
|
|
143
|
+
const keyPair = await new Smartcrypto().createKeyPair({ modulusLength: 4096 });
|
|
144
|
+
const encryptedPem = await keyPair.privateKey.toEncryptedPemString('my passphrase');
|
|
145
|
+
const privateKey = await PrivateKey.fromEncryptedPemString(encryptedPem, 'my passphrase');
|
|
76
146
|
```
|
|
77
147
|
|
|
78
|
-
|
|
148
|
+
Passphrases are asymmetric between export and import: `toEncryptedPemString('')` fails with `INVALID_ARGUMENT`, while `fromEncryptedPemString(pem, '')` accepts an empty passphrase so that keys stored by `@push.rocks/smartkey` (encrypted under an empty passphrase by default) stay readable. A non-string passphrase fails with `INVALID_ARGUMENT`, a wrong passphrase with `AUTHENTICATION_FAILED`, a malformed or non-RSA key with `INVALID_KEY`, and other encryption schemes with `UNSUPPORTED_PROFILE`.
|
|
149
|
+
|
|
150
|
+
## Runtime Support
|
|
79
151
|
|
|
80
|
-
|
|
81
|
-
`@push.rocks/smartcrypto` provides an easy-to-use interface for cryptographic operations, significantly reducing the complexity of managing keys and performing secure data transmission. The examples above showcase a subset of what's possible, encouraging you to explore further and integrate cryptography seamlessly into your Node.js applications.
|
|
152
|
+
The WebCrypto APIs, including encrypted private-key PEMs, are tested with Node.js 22 and current Chromium. Browsers require a secure context for WebCrypto.
|
|
82
153
|
|
|
83
|
-
|
|
154
|
+
## Migration from @push.rocks/smartkey
|
|
155
|
+
|
|
156
|
+
`@push.rocks/smartkey` is deprecated; RSA key pairs and passphrase-encrypted private keys live in this package.
|
|
157
|
+
|
|
158
|
+
| `@push.rocks/smartkey` | `@push.rocks/smartcrypto` |
|
|
159
|
+
|---|---|
|
|
160
|
+
| `new SmartKey().getKeypair(passphrase)` | `await new Smartcrypto().createKeyPair({ modulusLength: 4096 })` |
|
|
161
|
+
| `keyPair.publicKey` (SPKI PEM string) | `keyPair.publicKey.toPemString()` |
|
|
162
|
+
| `keyPair.privateKey` (encrypted PKCS#8 PEM string) | `await keyPair.privateKey.toEncryptedPemString(passphrase)` |
|
|
163
|
+
| `keyPair.privateKey` from `getKeypair()` without a passphrase (an encrypted PKCS#8 PEM with an empty passphrase) | read it with `await PrivateKey.fromEncryptedPemString(pem, '')`, then re-export with `await privateKey.toEncryptedPemString(passphrase)` using a real passphrase, or `privateKey.toPemString()` (unencrypted PKCS#1) |
|
|
164
|
+
| reading the encrypted PEM with `crypto.createPrivateKey({ key, passphrase })` | `await PrivateKey.fromEncryptedPemString(pem, passphrase)` (Node.js can still read the PEM directly) |
|
|
84
165
|
|
|
85
166
|
## License and Legal Information
|
|
86
167
|
|
|
87
|
-
This repository contains open-source code
|
|
168
|
+
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](license.md) file.
|
|
88
169
|
|
|
89
170
|
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
|
90
171
|
|
|
91
172
|
### Trademarks
|
|
92
173
|
|
|
93
|
-
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein.
|
|
174
|
+
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
|
|
175
|
+
|
|
176
|
+
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
|
94
177
|
|
|
95
178
|
### Company Information
|
|
96
179
|
|
|
97
|
-
Task Venture Capital GmbH
|
|
98
|
-
Registered at District
|
|
180
|
+
Task Venture Capital GmbH<br>
|
|
181
|
+
Registered at District Court Bremen HRB 35230 HB, Germany
|
|
99
182
|
|
|
100
|
-
For any legal inquiries or
|
|
183
|
+
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
|
101
184
|
|
|
102
185
|
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
package/ts/00_commitinfo_data.ts
CHANGED
package/ts/index.ts
CHANGED
|
@@ -2,6 +2,13 @@ export * from './smartcrypto.classes.smartcrypto.js';
|
|
|
2
2
|
export * from './smartcrypto.classes.keypair.js';
|
|
3
3
|
export * from './smartcrypto.classes.privatekey.js';
|
|
4
4
|
export * from './smartcrypto.classes.publickey.js';
|
|
5
|
+
export { SmartCryptoError } from './smartcrypto.errors.js';
|
|
6
|
+
export type {
|
|
7
|
+
ISmartCryptoErrorJson,
|
|
8
|
+
TSmartCryptoErrorCode,
|
|
9
|
+
} from './smartcrypto.errors.js';
|
|
10
|
+
export * from './smartcrypto.webcrypto.js';
|
|
11
|
+
export * from './smartcrypto.x25519.js';
|
|
5
12
|
|
|
6
13
|
import { nodeForge } from './smartcrypto.plugins.js';
|
|
7
14
|
|
|
@@ -1,16 +1,30 @@
|
|
|
1
1
|
import * as plugins from './smartcrypto.plugins.js';
|
|
2
2
|
import { PublicKey } from './smartcrypto.classes.publickey.js';
|
|
3
3
|
import { PrivateKey } from './smartcrypto.classes.privatekey.js';
|
|
4
|
+
import { createSmartCryptoError } from './smartcrypto.errors.js';
|
|
5
|
+
|
|
6
|
+
export type TRsaModulusLength = 2048 | 3072 | 4096;
|
|
7
|
+
|
|
8
|
+
export interface IKeyPairOptions {
|
|
9
|
+
/** RSA modulus length in bits. Defaults to 2048. */
|
|
10
|
+
modulusLength?: TRsaModulusLength;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const rsaModulusLengths: readonly TRsaModulusLength[] = [2048, 3072, 4096];
|
|
4
14
|
|
|
5
15
|
export class KeyPair {
|
|
6
16
|
// STATIC
|
|
7
|
-
public static async createNewKeyPair(): Promise<KeyPair> {
|
|
17
|
+
public static async createNewKeyPair(optionsArg: IKeyPairOptions = {}): Promise<KeyPair> {
|
|
18
|
+
const modulusLength = optionsArg.modulusLength ?? 2048;
|
|
19
|
+
if (!rsaModulusLengths.includes(modulusLength)) {
|
|
20
|
+
throw createSmartCryptoError('INVALID_ARGUMENT');
|
|
21
|
+
}
|
|
8
22
|
const done = plugins.smartpromise.defer<KeyPair>();
|
|
9
23
|
const rsa = plugins.nodeForge.pki.rsa;
|
|
10
|
-
rsa.generateKeyPair({ bits:
|
|
24
|
+
rsa.generateKeyPair({ bits: modulusLength, workers: 2 }, (err, keypair) => {
|
|
11
25
|
if (err) {
|
|
12
|
-
|
|
13
|
-
|
|
26
|
+
done.reject(createSmartCryptoError('CRYPTO_OPERATION_FAILED'));
|
|
27
|
+
return;
|
|
14
28
|
}
|
|
15
29
|
|
|
16
30
|
done.resolve(
|
|
@@ -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
|
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export type TSmartCryptoErrorCode =
|
|
2
|
+
| 'AUTHENTICATION_FAILED'
|
|
3
|
+
| 'CONTEXT_MISMATCH'
|
|
4
|
+
| 'CRYPTO_OPERATION_FAILED'
|
|
5
|
+
| 'INVALID_ARGUMENT'
|
|
6
|
+
| 'INVALID_ENVELOPE'
|
|
7
|
+
| 'INVALID_KEY'
|
|
8
|
+
| 'INVALID_SHARED_SECRET'
|
|
9
|
+
| 'RECIPIENT_MISMATCH'
|
|
10
|
+
| 'SIZE_LIMIT_EXCEEDED'
|
|
11
|
+
| 'UNSUPPORTED_PROFILE'
|
|
12
|
+
| 'UNSUPPORTED_VERSION';
|
|
13
|
+
|
|
14
|
+
export interface ISmartCryptoErrorJson {
|
|
15
|
+
name: 'SmartCryptoError';
|
|
16
|
+
code: TSmartCryptoErrorCode;
|
|
17
|
+
message: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const inspectSymbol = Symbol.for('nodejs.util.inspect.custom');
|
|
21
|
+
|
|
22
|
+
/** A stable error that intentionally retains no sensitive operation details. */
|
|
23
|
+
export class SmartCryptoError extends Error {
|
|
24
|
+
public readonly code: TSmartCryptoErrorCode;
|
|
25
|
+
public readonly cause: undefined;
|
|
26
|
+
|
|
27
|
+
constructor(codeArg: TSmartCryptoErrorCode) {
|
|
28
|
+
super(`SmartCrypto operation failed (${codeArg}).`);
|
|
29
|
+
this.name = 'SmartCryptoError';
|
|
30
|
+
this.code = codeArg;
|
|
31
|
+
Object.defineProperty(this, 'cause', {
|
|
32
|
+
configurable: false,
|
|
33
|
+
enumerable: false,
|
|
34
|
+
value: undefined,
|
|
35
|
+
writable: false,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
public toJSON(): ISmartCryptoErrorJson {
|
|
40
|
+
return {
|
|
41
|
+
name: 'SmartCryptoError',
|
|
42
|
+
code: this.code,
|
|
43
|
+
message: this.message,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
public [inspectSymbol](): ISmartCryptoErrorJson {
|
|
48
|
+
return this.toJSON();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export const createSmartCryptoError = (
|
|
53
|
+
codeArg: TSmartCryptoErrorCode,
|
|
54
|
+
): SmartCryptoError => new SmartCryptoError(codeArg);
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SmartCryptoError,
|
|
3
|
+
createSmartCryptoError,
|
|
4
|
+
type TSmartCryptoErrorCode,
|
|
5
|
+
} from './smartcrypto.errors.js';
|
|
6
|
+
|
|
7
|
+
const base64UrlPattern = /^[A-Za-z0-9_-]*$/;
|
|
8
|
+
|
|
9
|
+
export const getWebCrypto = (): Crypto => {
|
|
10
|
+
if (!globalThis.crypto?.subtle || typeof globalThis.crypto.getRandomValues !== 'function') {
|
|
11
|
+
throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
|
|
12
|
+
}
|
|
13
|
+
return globalThis.crypto;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export const requireUint8Array = (
|
|
17
|
+
valueArg: unknown,
|
|
18
|
+
codeArg: TSmartCryptoErrorCode = 'INVALID_ARGUMENT',
|
|
19
|
+
): Uint8Array => {
|
|
20
|
+
if (!(valueArg instanceof Uint8Array)) {
|
|
21
|
+
throw createSmartCryptoError(codeArg);
|
|
22
|
+
}
|
|
23
|
+
return new Uint8Array(valueArg);
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export const requireLength = (
|
|
27
|
+
valueArg: Uint8Array,
|
|
28
|
+
lengthArg: number,
|
|
29
|
+
codeArg: TSmartCryptoErrorCode,
|
|
30
|
+
): Uint8Array => {
|
|
31
|
+
if (valueArg.byteLength !== lengthArg) {
|
|
32
|
+
valueArg.fill(0);
|
|
33
|
+
throw createSmartCryptoError(codeArg);
|
|
34
|
+
}
|
|
35
|
+
return valueArg;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export const toArrayBuffer = (valueArg: Uint8Array): ArrayBuffer => {
|
|
39
|
+
const result = new Uint8Array(valueArg.byteLength);
|
|
40
|
+
result.set(valueArg);
|
|
41
|
+
return result.buffer;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export const concatBytes = (...valuesArg: Uint8Array[]): Uint8Array => {
|
|
45
|
+
const byteLength = valuesArg.reduce((sumArg, valueArg) => sumArg + valueArg.byteLength, 0);
|
|
46
|
+
const result = new Uint8Array(byteLength);
|
|
47
|
+
let offset = 0;
|
|
48
|
+
for (const value of valuesArg) {
|
|
49
|
+
result.set(value, offset);
|
|
50
|
+
offset += value.byteLength;
|
|
51
|
+
}
|
|
52
|
+
return result;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export const sha256 = async (valueArg: Uint8Array): Promise<Uint8Array> => {
|
|
56
|
+
const valueBuffer = toArrayBuffer(valueArg);
|
|
57
|
+
try {
|
|
58
|
+
return new Uint8Array(await getWebCrypto().subtle.digest('SHA-256', valueBuffer));
|
|
59
|
+
} finally {
|
|
60
|
+
new Uint8Array(valueBuffer).fill(0);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export const bytesEqual = (leftArg: Uint8Array, rightArg: Uint8Array): boolean => {
|
|
65
|
+
if (leftArg.byteLength !== rightArg.byteLength) {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
let difference = 0;
|
|
69
|
+
for (let index = 0; index < leftArg.byteLength; index++) {
|
|
70
|
+
difference |= leftArg[index] ^ rightArg[index];
|
|
71
|
+
}
|
|
72
|
+
return difference === 0;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export const isAllZero = (valueArg: Uint8Array): boolean => {
|
|
76
|
+
let combined = 0;
|
|
77
|
+
for (const value of valueArg) {
|
|
78
|
+
combined |= value;
|
|
79
|
+
}
|
|
80
|
+
return combined === 0;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export const encodeBase64Url = (valueArg: Uint8Array): string => {
|
|
84
|
+
let binary = '';
|
|
85
|
+
const chunkSize = 0x8000;
|
|
86
|
+
for (let offset = 0; offset < valueArg.byteLength; offset += chunkSize) {
|
|
87
|
+
binary += String.fromCharCode(...valueArg.subarray(offset, offset + chunkSize));
|
|
88
|
+
}
|
|
89
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export const decodeCanonicalBase64Url = (
|
|
93
|
+
valueArg: unknown,
|
|
94
|
+
maximumBytesArg: number,
|
|
95
|
+
exactBytesArg?: number,
|
|
96
|
+
): Uint8Array => {
|
|
97
|
+
if (typeof valueArg !== 'string') {
|
|
98
|
+
throw createSmartCryptoError('INVALID_ENVELOPE');
|
|
99
|
+
}
|
|
100
|
+
const maximumEncodedLength = Math.ceil(maximumBytesArg * 4 / 3);
|
|
101
|
+
if (valueArg.length > maximumEncodedLength) {
|
|
102
|
+
throw createSmartCryptoError('SIZE_LIMIT_EXCEEDED');
|
|
103
|
+
}
|
|
104
|
+
if (!base64UrlPattern.test(valueArg) || valueArg.length % 4 === 1) {
|
|
105
|
+
throw createSmartCryptoError('INVALID_ENVELOPE');
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
const paddingLength = (4 - valueArg.length % 4) % 4;
|
|
109
|
+
const base64 = valueArg.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat(paddingLength);
|
|
110
|
+
const binary = atob(base64);
|
|
111
|
+
if (binary.length > maximumBytesArg) {
|
|
112
|
+
throw createSmartCryptoError('SIZE_LIMIT_EXCEEDED');
|
|
113
|
+
}
|
|
114
|
+
if (exactBytesArg !== undefined && binary.length !== exactBytesArg) {
|
|
115
|
+
throw createSmartCryptoError('INVALID_ENVELOPE');
|
|
116
|
+
}
|
|
117
|
+
const result = new Uint8Array(binary.length);
|
|
118
|
+
for (let index = 0; index < binary.length; index++) {
|
|
119
|
+
result[index] = binary.charCodeAt(index);
|
|
120
|
+
}
|
|
121
|
+
if (encodeBase64Url(result) !== valueArg) {
|
|
122
|
+
throw createSmartCryptoError('INVALID_ENVELOPE');
|
|
123
|
+
}
|
|
124
|
+
return result;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (error instanceof SmartCryptoError) {
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
throw createSmartCryptoError('INVALID_ENVELOPE');
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
export const requirePlainDataObject = (
|
|
134
|
+
valueArg: unknown,
|
|
135
|
+
expectedKeysArg: readonly string[],
|
|
136
|
+
): Record<string, unknown> => {
|
|
137
|
+
if (valueArg === null || typeof valueArg !== 'object' || Array.isArray(valueArg)) {
|
|
138
|
+
throw createSmartCryptoError('INVALID_ENVELOPE');
|
|
139
|
+
}
|
|
140
|
+
const prototype = Object.getPrototypeOf(valueArg);
|
|
141
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
142
|
+
throw createSmartCryptoError('INVALID_ENVELOPE');
|
|
143
|
+
}
|
|
144
|
+
const ownKeys = Reflect.ownKeys(valueArg);
|
|
145
|
+
if (ownKeys.some((keyArg) => typeof keyArg !== 'string')) {
|
|
146
|
+
throw createSmartCryptoError('INVALID_ENVELOPE');
|
|
147
|
+
}
|
|
148
|
+
const keys = ownKeys as string[];
|
|
149
|
+
if (
|
|
150
|
+
keys.length !== expectedKeysArg.length
|
|
151
|
+
|| [...keys].sort().some((keyArg, indexArg) => keyArg !== [...expectedKeysArg].sort()[indexArg])
|
|
152
|
+
) {
|
|
153
|
+
throw createSmartCryptoError('INVALID_ENVELOPE');
|
|
154
|
+
}
|
|
155
|
+
for (const key of keys) {
|
|
156
|
+
const descriptor = Object.getOwnPropertyDescriptor(valueArg, key);
|
|
157
|
+
if (!descriptor?.enumerable || !('value' in descriptor)) {
|
|
158
|
+
throw createSmartCryptoError('INVALID_ENVELOPE');
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return valueArg as Record<string, unknown>;
|
|
162
|
+
};
|