@push.rocks/smartcrypto 2.0.5 → 2.2.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 +66 -0
- package/dist_ts/00_commitinfo_data.d.ts +1 -1
- package/dist_ts/00_commitinfo_data.js +4 -4
- package/dist_ts/index.d.ts +4 -0
- package/dist_ts/index.js +4 -1
- package/dist_ts/smartcrypto.classes.privatekey.d.ts +2 -3
- package/dist_ts/smartcrypto.classes.privatekey.js +1 -1
- package/dist_ts/smartcrypto.classes.publickey.d.ts +13 -3
- package/dist_ts/smartcrypto.classes.publickey.js +81 -1
- 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.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 +2 -1
- package/package.json +28 -9
- package/readme.hints.md +1 -0
- package/readme.md +146 -28
- package/ts/00_commitinfo_data.ts +3 -3
- package/ts/index.ts +7 -0
- package/ts/smartcrypto.classes.privatekey.ts +2 -2
- package/ts/smartcrypto.classes.publickey.ts +128 -2
- package/ts/smartcrypto.errors.ts +54 -0
- package/ts/smartcrypto.internal.ts +162 -0
- package/ts/smartcrypto.webcrypto.ts +266 -0
- package/ts/smartcrypto.x25519.ts +493 -0
- package/npmextra.json +0 -18
package/package.json
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@push.rocks/smartcrypto",
|
|
3
|
-
"version": "2.0
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"private": false,
|
|
5
|
-
"description": "easy
|
|
5
|
+
"description": "A library providing easy methods for cryptographic operations, including key pair generation.",
|
|
6
6
|
"main": "dist_ts/index.js",
|
|
7
7
|
"typings": "dist_ts/index.d.ts",
|
|
8
|
-
"author": "
|
|
8
|
+
"author": "Task Venture Capital GmbH",
|
|
9
9
|
"license": "MIT",
|
|
10
10
|
"devDependencies": {
|
|
11
|
-
"@git.zone/tsbuild": "^
|
|
12
|
-
"@git.zone/tsrun": "^
|
|
13
|
-
"@git.zone/tstest": "^
|
|
14
|
-
"@
|
|
15
|
-
"@types/node": "^20.11.17"
|
|
11
|
+
"@git.zone/tsbuild": "^4.4.2",
|
|
12
|
+
"@git.zone/tsrun": "^2.0.6",
|
|
13
|
+
"@git.zone/tstest": "^3.6.7",
|
|
14
|
+
"@types/node": "^26.1.1"
|
|
16
15
|
},
|
|
17
16
|
"dependencies": {
|
|
18
17
|
"@push.rocks/smartpromise": "^4.0.3",
|
|
@@ -28,13 +27,33 @@
|
|
|
28
27
|
"dist_ts_web/**/*",
|
|
29
28
|
"assets/**/*",
|
|
30
29
|
"cli.js",
|
|
31
|
-
"
|
|
30
|
+
".smartconfig.json",
|
|
32
31
|
"readme.md"
|
|
33
32
|
],
|
|
34
33
|
"browserslist": [
|
|
35
34
|
"last 1 chrome versions"
|
|
36
35
|
],
|
|
37
36
|
"type": "module",
|
|
37
|
+
"keywords": [
|
|
38
|
+
"cryptography",
|
|
39
|
+
"encryption",
|
|
40
|
+
"security",
|
|
41
|
+
"public key",
|
|
42
|
+
"private key",
|
|
43
|
+
"RSA",
|
|
44
|
+
"key pair generation",
|
|
45
|
+
"node-forge",
|
|
46
|
+
"typescript",
|
|
47
|
+
"WebCrypto",
|
|
48
|
+
"X25519",
|
|
49
|
+
"AES-GCM",
|
|
50
|
+
"HKDF"
|
|
51
|
+
],
|
|
52
|
+
"homepage": "https://code.foss.global/push.rocks/smartcrypto",
|
|
53
|
+
"repository": {
|
|
54
|
+
"type": "git",
|
|
55
|
+
"url": "https://code.foss.global/push.rocks/smartcrypto.git"
|
|
56
|
+
},
|
|
38
57
|
"scripts": {
|
|
39
58
|
"test": "(tstest test/ --web)",
|
|
40
59
|
"build": "(tsbuild --web)",
|
package/readme.hints.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
package/readme.md
CHANGED
|
@@ -1,39 +1,157 @@
|
|
|
1
1
|
# @push.rocks/smartcrypto
|
|
2
|
-
easy crypto methods
|
|
3
2
|
|
|
4
|
-
|
|
5
|
-
* [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/smartcrypto)
|
|
6
|
-
* [gitlab.com (source)](https://gitlab.com/push.rocks/smartcrypto)
|
|
7
|
-
* [github.com (source mirror)](https://github.com/push.rocks/smartcrypto)
|
|
8
|
-
* [docs (typedoc)](https://push.rocks.gitlab.io/smartcrypto/)
|
|
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.
|
|
9
4
|
|
|
10
|
-
##
|
|
5
|
+
## Issue Reporting and Security
|
|
11
6
|
|
|
12
|
-
|
|
13
|
-
-- | --
|
|
14
|
-
GitLab Pipelines | [](https://lossless.cloud)
|
|
15
|
-
GitLab Pipline Test Coverage | [](https://lossless.cloud)
|
|
16
|
-
npm | [](https://lossless.cloud)
|
|
17
|
-
Snyk | [](https://lossless.cloud)
|
|
18
|
-
TypeScript Support | [](https://lossless.cloud)
|
|
19
|
-
node Support | [](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
|
20
|
-
Code Style | [](https://lossless.cloud)
|
|
21
|
-
PackagePhobia (total standalone install weight) | [](https://lossless.cloud)
|
|
22
|
-
PackagePhobia (package size on registry) | [](https://lossless.cloud)
|
|
23
|
-
BundlePhobia (total size when bundled) | [](https://lossless.cloud)
|
|
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.
|
|
24
8
|
|
|
25
|
-
##
|
|
9
|
+
## Install
|
|
26
10
|
|
|
27
|
-
|
|
11
|
+
```bash
|
|
12
|
+
pnpm add @push.rocks/smartcrypto
|
|
13
|
+
```
|
|
28
14
|
|
|
29
|
-
|
|
15
|
+
## X25519 Envelope Profile
|
|
30
16
|
|
|
31
|
-
|
|
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.
|
|
32
18
|
|
|
33
|
-
|
|
19
|
+
```typescript
|
|
20
|
+
import {
|
|
21
|
+
generateX25519KeyPair,
|
|
22
|
+
openX25519Envelope,
|
|
23
|
+
sealX25519Envelope,
|
|
24
|
+
} from '@push.rocks/smartcrypto';
|
|
34
25
|
|
|
35
|
-
|
|
26
|
+
const encoder = new TextEncoder();
|
|
27
|
+
const recipient = await generateX25519KeyPair();
|
|
28
|
+
const context = encoder.encode('tenant:example/secret:database-password');
|
|
36
29
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
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:
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
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
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
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`.
|
|
63
|
+
|
|
64
|
+
## AES-GCM And DEK Wrapping
|
|
65
|
+
|
|
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.
|
|
67
|
+
|
|
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
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`rewrapDek()` only receives the wrapped DEK, so payload ciphertext, nonce, and tag remain unchanged during KEK rotation.
|
|
114
|
+
|
|
115
|
+
## Errors
|
|
116
|
+
|
|
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.
|
|
118
|
+
|
|
119
|
+
## RSA APIs
|
|
120
|
+
|
|
121
|
+
The existing `Smartcrypto`, `KeyPair`, `PrivateKey`, and `PublicKey` APIs remain available. RSA key generation and PEM conversion continue to use the existing behavior:
|
|
122
|
+
|
|
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();
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`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.
|
|
133
|
+
|
|
134
|
+
## Runtime Support
|
|
135
|
+
|
|
136
|
+
The WebCrypto APIs are tested with Node.js 22 and current Chromium. Browsers require a secure context for WebCrypto.
|
|
137
|
+
|
|
138
|
+
## License and Legal Information
|
|
139
|
+
|
|
140
|
+
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](license) file.
|
|
141
|
+
|
|
142
|
+
**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.
|
|
143
|
+
|
|
144
|
+
### Trademarks
|
|
145
|
+
|
|
146
|
+
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.
|
|
147
|
+
|
|
148
|
+
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.
|
|
149
|
+
|
|
150
|
+
### Company Information
|
|
151
|
+
|
|
152
|
+
Task Venture Capital GmbH<br>
|
|
153
|
+
Registered at District Court Bremen HRB 35230 HB, Germany
|
|
154
|
+
|
|
155
|
+
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
|
156
|
+
|
|
157
|
+
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
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* autocreated commitinfo by @
|
|
2
|
+
* autocreated commitinfo by @push.rocks/commitinfo
|
|
3
3
|
*/
|
|
4
4
|
export const commitinfo = {
|
|
5
5
|
name: '@push.rocks/smartcrypto',
|
|
6
|
-
version: '2.0
|
|
7
|
-
description: 'easy
|
|
6
|
+
version: '2.2.0',
|
|
7
|
+
description: 'A library providing easy methods for cryptographic operations, including key pair generation.'
|
|
8
8
|
}
|
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
|
|
|
@@ -12,9 +12,9 @@ export class PrivateKey {
|
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
// INSTANCE
|
|
15
|
-
public forgePrivateKey: plugins.nodeForge.pki.PrivateKey;
|
|
15
|
+
public forgePrivateKey: plugins.nodeForge.pki.rsa.PrivateKey;
|
|
16
16
|
|
|
17
|
-
constructor(privateKeyArg: plugins.nodeForge.pki.PrivateKey) {
|
|
17
|
+
constructor(privateKeyArg: plugins.nodeForge.pki.rsa.PrivateKey) {
|
|
18
18
|
this.forgePrivateKey = privateKeyArg;
|
|
19
19
|
}
|
|
20
20
|
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import * as plugins from './smartcrypto.plugins.js';
|
|
2
2
|
|
|
3
|
+
const canonicalPublicKeyError = (messageArg: string): Error =>
|
|
4
|
+
new Error(`Invalid canonical RSA public key: ${messageArg}`);
|
|
5
|
+
|
|
3
6
|
export class PublicKey {
|
|
4
7
|
// STATIC
|
|
5
8
|
public static createFromPrivateKey(pemString: string) {
|
|
@@ -11,10 +14,71 @@ export class PublicKey {
|
|
|
11
14
|
return new PublicKey(plugins.nodeForge.pki.publicKeyFromPem(pemString));
|
|
12
15
|
}
|
|
13
16
|
|
|
17
|
+
/**
|
|
18
|
+
* Parses exactly one canonical SPKI or PKCS#1 RSA public-key PEM block and
|
|
19
|
+
* requires a modulus of at least 2048 bits.
|
|
20
|
+
*/
|
|
21
|
+
public static fromCanonicalRsaPublicPemString(pemString: string) {
|
|
22
|
+
if (typeof pemString !== 'string' || pemString.length < 1 || pemString.length > 32_768) {
|
|
23
|
+
throw canonicalPublicKeyError('expected one bounded PEM block');
|
|
24
|
+
}
|
|
25
|
+
const normalizedPem = pemString.trim();
|
|
26
|
+
const spkiMatch =
|
|
27
|
+
/^-----BEGIN PUBLIC KEY-----\r?\n([A-Za-z0-9+/=\r\n]+)\r?\n-----END PUBLIC KEY-----$/.exec(
|
|
28
|
+
normalizedPem,
|
|
29
|
+
);
|
|
30
|
+
const pkcs1Match =
|
|
31
|
+
/^-----BEGIN RSA PUBLIC KEY-----\r?\n([A-Za-z0-9+/=\r\n]+)\r?\n-----END RSA PUBLIC KEY-----$/.exec(
|
|
32
|
+
normalizedPem,
|
|
33
|
+
);
|
|
34
|
+
const publicKeyMatch = spkiMatch || pkcs1Match;
|
|
35
|
+
if (!publicKeyMatch) {
|
|
36
|
+
throw canonicalPublicKeyError('expected one public-key PEM block');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const flattenedBase64 = publicKeyMatch[1].replace(/[\r\n]/g, '');
|
|
40
|
+
if (
|
|
41
|
+
flattenedBase64.length < 1
|
|
42
|
+
|| flattenedBase64.length % 4 !== 0
|
|
43
|
+
|| !/^[A-Za-z0-9+/]+={0,2}$/.test(flattenedBase64)
|
|
44
|
+
) {
|
|
45
|
+
throw canonicalPublicKeyError('PEM body is malformed');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
const pemMessages = plugins.nodeForge.pem.decode(normalizedPem);
|
|
50
|
+
if (pemMessages.length !== 1) {
|
|
51
|
+
throw canonicalPublicKeyError('expected exactly one decoded PEM block');
|
|
52
|
+
}
|
|
53
|
+
const pemMessage = pemMessages[0];
|
|
54
|
+
if (plugins.nodeForge.util.encode64(pemMessage.body) !== flattenedBase64) {
|
|
55
|
+
throw canonicalPublicKeyError('PEM body is not canonical base64');
|
|
56
|
+
}
|
|
57
|
+
const publicKeyAsn1 = plugins.nodeForge.asn1.fromDer(pemMessage.body, true);
|
|
58
|
+
const publicKey = plugins.nodeForge.pki.publicKeyFromAsn1(publicKeyAsn1);
|
|
59
|
+
if (publicKey.n.bitLength() < 2_048) {
|
|
60
|
+
throw canonicalPublicKeyError('RSA modulus must contain at least 2048 bits');
|
|
61
|
+
}
|
|
62
|
+
const canonicalAsn1 = spkiMatch
|
|
63
|
+
? plugins.nodeForge.pki.publicKeyToAsn1(publicKey)
|
|
64
|
+
: plugins.nodeForge.pki.publicKeyToRSAPublicKey(publicKey);
|
|
65
|
+
const canonicalDer = plugins.nodeForge.asn1.toDer(canonicalAsn1).getBytes();
|
|
66
|
+
if (canonicalDer !== pemMessage.body) {
|
|
67
|
+
throw canonicalPublicKeyError('public-key DER is not canonical');
|
|
68
|
+
}
|
|
69
|
+
return new PublicKey(publicKey);
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error instanceof Error && error.message.startsWith('Invalid canonical RSA public key:')) {
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
throw canonicalPublicKeyError('PEM does not encode a valid RSA public key');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
14
78
|
// INSTANCE
|
|
15
|
-
public forgePublicKey: plugins.nodeForge.pki.PublicKey;
|
|
79
|
+
public forgePublicKey: plugins.nodeForge.pki.rsa.PublicKey;
|
|
16
80
|
|
|
17
|
-
constructor(publicKeyArg: plugins.nodeForge.pki.PublicKey) {
|
|
81
|
+
constructor(publicKeyArg: plugins.nodeForge.pki.rsa.PublicKey) {
|
|
18
82
|
this.forgePublicKey = publicKeyArg;
|
|
19
83
|
}
|
|
20
84
|
|
|
@@ -22,6 +86,68 @@ export class PublicKey {
|
|
|
22
86
|
return plugins.nodeForge.pki.publicKeyToPem(this.forgePublicKey);
|
|
23
87
|
}
|
|
24
88
|
|
|
89
|
+
/**
|
|
90
|
+
* Verifies RSASSA-PKCS1-v1_5 with an exact SHA-256 DigestInfo. The exact
|
|
91
|
+
* encoding check prevents accepting signatures that label the digest with a
|
|
92
|
+
* different algorithm identifier.
|
|
93
|
+
*/
|
|
94
|
+
public verifyRs256(dataArg: Uint8Array, signatureArg: Uint8Array): boolean {
|
|
95
|
+
if (!(dataArg instanceof Uint8Array) || !(signatureArg instanceof Uint8Array)) {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
if (signatureArg.byteLength !== Math.ceil(this.forgePublicKey.n.bitLength() / 8)) {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
const messageDigest = plugins.nodeForge.md.sha256.create();
|
|
103
|
+
messageDigest.update(
|
|
104
|
+
plugins.nodeForge.util.createBuffer(dataArg.slice()).getBytes(),
|
|
105
|
+
'raw',
|
|
106
|
+
);
|
|
107
|
+
const digestInfo = plugins.nodeForge.asn1.create(
|
|
108
|
+
plugins.nodeForge.asn1.Class.UNIVERSAL,
|
|
109
|
+
plugins.nodeForge.asn1.Type.SEQUENCE,
|
|
110
|
+
true,
|
|
111
|
+
[
|
|
112
|
+
plugins.nodeForge.asn1.create(
|
|
113
|
+
plugins.nodeForge.asn1.Class.UNIVERSAL,
|
|
114
|
+
plugins.nodeForge.asn1.Type.SEQUENCE,
|
|
115
|
+
true,
|
|
116
|
+
[
|
|
117
|
+
plugins.nodeForge.asn1.create(
|
|
118
|
+
plugins.nodeForge.asn1.Class.UNIVERSAL,
|
|
119
|
+
plugins.nodeForge.asn1.Type.OID,
|
|
120
|
+
false,
|
|
121
|
+
plugins.nodeForge.asn1.oidToDer(
|
|
122
|
+
plugins.nodeForge.pki.oids.sha256,
|
|
123
|
+
).getBytes(),
|
|
124
|
+
),
|
|
125
|
+
plugins.nodeForge.asn1.create(
|
|
126
|
+
plugins.nodeForge.asn1.Class.UNIVERSAL,
|
|
127
|
+
plugins.nodeForge.asn1.Type.NULL,
|
|
128
|
+
false,
|
|
129
|
+
'',
|
|
130
|
+
),
|
|
131
|
+
],
|
|
132
|
+
),
|
|
133
|
+
plugins.nodeForge.asn1.create(
|
|
134
|
+
plugins.nodeForge.asn1.Class.UNIVERSAL,
|
|
135
|
+
plugins.nodeForge.asn1.Type.OCTETSTRING,
|
|
136
|
+
false,
|
|
137
|
+
messageDigest.digest().getBytes(),
|
|
138
|
+
),
|
|
139
|
+
],
|
|
140
|
+
);
|
|
141
|
+
return this.forgePublicKey.verify(
|
|
142
|
+
plugins.nodeForge.asn1.toDer(digestInfo).getBytes(),
|
|
143
|
+
plugins.nodeForge.util.createBuffer(signatureArg.slice()).getBytes(),
|
|
144
|
+
'NONE',
|
|
145
|
+
);
|
|
146
|
+
} catch {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
25
151
|
public toOpenSSH(): string {
|
|
26
152
|
return plugins.nodeForge.ssh.publicKeyToOpenSSH(this.forgePublicKey, 'user@host');
|
|
27
153
|
}
|
|
@@ -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
|
+
};
|