@substrate-system/keys 0.2.33 → 0.2.36
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/README.md +256 -36
- package/dist/_base.cjs.map +1 -1
- package/dist/_base.d.ts +1 -1
- package/dist/_base.js.map +1 -1
- package/dist/_base.min.cjs +1 -1
- package/dist/_base.min.cjs.map +1 -1
- package/dist/_base.min.js +2 -2
- package/dist/_base.min.js.map +3 -3
- package/dist/aes/index.cjs +15 -9
- package/dist/aes/index.cjs.map +2 -2
- package/dist/aes/index.d.ts +12 -1
- package/dist/aes/index.d.ts.map +1 -1
- package/dist/aes/index.js +12 -5
- package/dist/aes/index.js.map +2 -2
- package/dist/aes/index.min.cjs +1 -1
- package/dist/aes/index.min.cjs.map +3 -3
- package/dist/aes/index.min.js +2 -2
- package/dist/aes/index.min.js.map +3 -3
- package/dist/browser/index.js +151 -35
- package/dist/browser/index.min.js +2 -2
- package/dist/constants.cjs +4 -8
- package/dist/constants.cjs.map +2 -2
- package/dist/constants.d.ts +2 -4
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +4 -8
- package/dist/constants.js.map +2 -2
- package/dist/constants.min.cjs +1 -1
- package/dist/constants.min.cjs.map +3 -3
- package/dist/constants.min.js +1 -1
- package/dist/constants.min.js.map +3 -3
- package/dist/crypto.min.js +2 -2
- package/dist/crypto.min.js.map +3 -3
- package/dist/ecc/index.cjs +113 -8
- package/dist/ecc/index.cjs.map +2 -2
- package/dist/ecc/index.d.ts +44 -4
- package/dist/ecc/index.d.ts.map +1 -1
- package/dist/ecc/index.js +115 -12
- package/dist/ecc/index.js.map +2 -2
- package/dist/ecc/index.min.cjs +1 -1
- package/dist/ecc/index.min.cjs.map +3 -3
- package/dist/ecc/index.min.js +2 -2
- package/dist/ecc/index.min.js.map +3 -3
- package/dist/errors.min.js +1 -1
- package/dist/index.min.js +2 -2
- package/dist/index.min.js.map +3 -3
- package/dist/meta.json +20 -22
- package/dist/rsa/index.cjs +9 -0
- package/dist/rsa/index.cjs.map +2 -2
- package/dist/rsa/index.d.ts +10 -4
- package/dist/rsa/index.d.ts.map +1 -1
- package/dist/rsa/index.js +9 -0
- package/dist/rsa/index.js.map +2 -2
- package/dist/rsa/index.min.cjs +1 -1
- package/dist/rsa/index.min.cjs.map +2 -2
- package/dist/rsa/index.min.js +2 -2
- package/dist/rsa/index.min.js.map +3 -3
- package/dist/types.cjs.map +2 -2
- package/dist/types.d.ts +10 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +2 -2
- package/dist/types.min.cjs +1 -1
- package/dist/types.min.cjs.map +2 -2
- package/dist/types.min.js +1 -1
- package/dist/types.min.js.map +2 -2
- package/dist/util.min.js +1 -1
- package/dist/util.min.js.map +3 -3
- package/package.json +4 -10
package/README.md
CHANGED
|
@@ -5,7 +5,6 @@
|
|
|
5
5
|
[](https://semver.org/)
|
|
6
6
|
[](./CHANGELOG.md)
|
|
7
7
|
[](https://packagephobia.com/result?p=@substrate-system/keys)
|
|
8
|
-
[](https://bundlephobia.com/package/@substrate-system/keys)
|
|
9
8
|
[](LICENSE)
|
|
10
9
|
|
|
11
10
|
|
|
@@ -14,7 +13,8 @@ Create and store keypairs in the browser with the [web crypto API](https://devel
|
|
|
14
13
|
Use [`indexedDB`](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API)
|
|
15
14
|
to store [non-extractable keypairs](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey#extractable)
|
|
16
15
|
in the browser. "Non-extractable" means that the browser prevents you from ever
|
|
17
|
-
reading the private key, but the keys can be persisted and
|
|
16
|
+
reading the private key, but the keys can still be persisted and
|
|
17
|
+
re-used indefinitely.
|
|
18
18
|
|
|
19
19
|
>
|
|
20
20
|
> [!TIP]
|
|
@@ -32,39 +32,77 @@ See also, [the API docs generated from typescript](https://substrate-system.gith
|
|
|
32
32
|
<!-- toc -->
|
|
33
33
|
|
|
34
34
|
- [Install](#install)
|
|
35
|
-
- [
|
|
36
|
-
* [`exports`](#exports)
|
|
35
|
+
- [Exports](#exports)
|
|
37
36
|
* [ESM](#esm)
|
|
38
37
|
* [Common JS](#common-js)
|
|
39
|
-
* [pre-
|
|
38
|
+
* [pre-bundled JS](#pre-bundled-js)
|
|
39
|
+
+ [copy](#copy)
|
|
40
|
+
+ [HTML](#html)
|
|
41
|
+
* [`@substrate-system/keys`](#substrate-systemkeys)
|
|
42
|
+
* [`ecc`](#ecc)
|
|
43
|
+
* [`rsa`](#rsa)
|
|
44
|
+
* [import `aes`](#import-aes)
|
|
45
|
+
* [`crypto`](#crypto)
|
|
46
|
+
+ [`crypto.verify`](#cryptoverify)
|
|
47
|
+
+ [`crypto.keyTypeFromDid`](#cryptokeytypefromdid)
|
|
40
48
|
- [Get started](#get-started)
|
|
41
49
|
* [Verify a signature](#verify-a-signature)
|
|
42
|
-
* [ECC](#ecc)
|
|
50
|
+
* [ECC keys](#ecc-keys)
|
|
51
|
+
+ [Create a keypair](#create-a-keypair)
|
|
52
|
+
+ ["Add a device"](#add-a-device)
|
|
43
53
|
* [some notes about the `keys` instance](#some-notes-about-the-keys-instance)
|
|
54
|
+
+ [`keys.DID`](#keysdid)
|
|
55
|
+
+ [`keys.getDeviceName` / `keys.deviceName`](#keysgetdevicename--keysdevicename)
|
|
56
|
+
+ [`keys.hasPersisted`](#keyshaspersisted)
|
|
57
|
+
+ [`keys.publicExchangeKey`](#keyspublicexchangekey)
|
|
58
|
+
+ [`keys.publicExchangeKeyAsString()`](#keyspublicexchangekeyasstring)
|
|
59
|
+
+ [`keys.publicWriteKey`](#keyspublicwritekey)
|
|
60
|
+
+ [`keys.publicWriteKeyAsString()`](#keyspublicwritekeyasstring)
|
|
44
61
|
* [Delete a keypair](#delete-a-keypair)
|
|
45
62
|
* [Sign and Verify Something](#sign-and-verify-something)
|
|
46
63
|
* [encrypt something](#encrypt-something)
|
|
64
|
+
+ [`keys.encrypt` methods](#keysencrypt-methods)
|
|
65
|
+
+ [`keys.encryptAsString` methods](#keysencryptasstring-methods)
|
|
47
66
|
* [decrypt something](#decrypt-something)
|
|
48
|
-
- [
|
|
67
|
+
- [Examples](#examples)
|
|
49
68
|
* [Create a new `Keys` instance](#create-a-new-keys-instance)
|
|
69
|
+
+ [Parameters](#parameters)
|
|
70
|
+
+ [`.create()` example](#create-example)
|
|
50
71
|
* [Get a hash of the DID](#get-a-hash-of-the-did)
|
|
72
|
+
+ [Static `deviceName` method](#static-devicename-method)
|
|
73
|
+
+ [Instance `getdeviceName` method](#instance-getdevicename-method)
|
|
51
74
|
* [Persist the keys](#persist-the-keys)
|
|
75
|
+
+ [`.persist`](#persist)
|
|
76
|
+
+ [`.persist` example](#persist-example)
|
|
52
77
|
* [Restore from indexedDB](#restore-from-indexeddb)
|
|
78
|
+
+ [`static .load`](#static-load)
|
|
79
|
+
+ [Parameters](#parameters-1)
|
|
80
|
+
+ [example](#example)
|
|
53
81
|
* [Sign something](#sign-something)
|
|
82
|
+
+ [example](#example-1)
|
|
54
83
|
* [Get a signature as a string](#get-a-signature-as-a-string)
|
|
84
|
+
+ [`keys.signAsString(msg)`](#keyssignasstringmsg)
|
|
85
|
+
+ [Backward compatibility: `keys.sign.asString(msg)`](#backward-compatibility-keyssignasstringmsg)
|
|
55
86
|
* [Verify a signature](#verify-a-signature-1)
|
|
56
87
|
* [Encrypt a key](#encrypt-a-key)
|
|
88
|
+
+ [example](#example-2)
|
|
89
|
+
+ [encrypt a key, return a string](#encrypt-a-key-return-a-string)
|
|
90
|
+
+ [format](#format)
|
|
57
91
|
* [Asymmetrically encrypt some arbitrary data](#asymmetrically-encrypt-some-arbitrary-data)
|
|
92
|
+
+ [example](#example-3)
|
|
58
93
|
* [Asymmetrically encrypt a string, return a new string](#asymmetrically-encrypt-a-string-return-a-new-string)
|
|
94
|
+
+ [`keys.decryptAsString`](#keysdecryptasstring)
|
|
59
95
|
* [Decrypt a message](#decrypt-a-message)
|
|
60
|
-
* [Backward compatibility: `.decrypt.asString`](#backward-compatibility-decryptasstring)
|
|
61
96
|
* [In memory only](#in-memory-only)
|
|
62
97
|
- [AES](#aes)
|
|
63
98
|
* [`create`](#create)
|
|
64
99
|
* [`export`](#export)
|
|
65
|
-
|
|
100
|
+
+ [`aes.export` example](#aesexport-example)
|
|
101
|
+
* [`export.asString`](#exportasstring)
|
|
102
|
+
+ [`export.asString` example](#exportasstring-example)
|
|
66
103
|
* [`AES.encrypt`](#aesencrypt)
|
|
67
104
|
* [`AES.decrypt`](#aesdecrypt)
|
|
105
|
+
- [See also](#see-also)
|
|
68
106
|
|
|
69
107
|
<!-- tocstop -->
|
|
70
108
|
|
|
@@ -77,13 +115,14 @@ See also, [the API docs generated from typescript](https://substrate-system.gith
|
|
|
77
115
|
npm i -S @substrate-system/keys
|
|
78
116
|
```
|
|
79
117
|
|
|
80
|
-
##
|
|
118
|
+
## Exports
|
|
81
119
|
|
|
82
|
-
|
|
120
|
+
This exposes ESM and common JS via
|
|
121
|
+
[package.json `exports` field](https://nodejs.org/api/packages.html#exports).
|
|
83
122
|
|
|
84
|
-
This exposes ESM and common JS via [package.json `exports` field](https://nodejs.org/api/packages.html#exports).
|
|
85
123
|
|
|
86
124
|
### ESM
|
|
125
|
+
|
|
87
126
|
```js
|
|
88
127
|
import { EccKeys, verify } from '@substrate-system/keys/ecc'
|
|
89
128
|
import { RsaKeys, verify } from '@substrate-system/keys/rsa'
|
|
@@ -91,13 +130,15 @@ import { AES } from '@substrate-system/keys/aes'
|
|
|
91
130
|
```
|
|
92
131
|
|
|
93
132
|
### Common JS
|
|
133
|
+
|
|
94
134
|
```js
|
|
95
135
|
const { EccKeys, verify } = require('@substrate-system/keys/ecc')
|
|
96
136
|
const { RsaKeys, verify } = require('@substrate-system/keys/rsa')
|
|
97
137
|
const { AES } = require('@substrate-system/keys/aes')
|
|
98
138
|
```
|
|
99
139
|
|
|
100
|
-
### pre-
|
|
140
|
+
### pre-bundled JS
|
|
141
|
+
|
|
101
142
|
This package exposes minified JS files too. Copy them to a location that is
|
|
102
143
|
accessible to your web server, then link to them in HTML.
|
|
103
144
|
|
|
@@ -111,6 +152,89 @@ cp ./node_modules/@substrate-system/keys/dist/index.min.js ./public/keys.min.js
|
|
|
111
152
|
<script type="module" src="./keys.min.js"></script>
|
|
112
153
|
```
|
|
113
154
|
|
|
155
|
+
|
|
156
|
+
### `@substrate-system/keys`
|
|
157
|
+
|
|
158
|
+
Import everything.
|
|
159
|
+
|
|
160
|
+
```js
|
|
161
|
+
import * as keys from '@substrate-system/keys'
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### `ecc`
|
|
165
|
+
|
|
166
|
+
Import functions for Ed25519 signatures and X25519 encryption.
|
|
167
|
+
|
|
168
|
+
```js
|
|
169
|
+
import {
|
|
170
|
+
EccKeys,
|
|
171
|
+
exportPublicKey,
|
|
172
|
+
importPublicKey,
|
|
173
|
+
verify
|
|
174
|
+
} from '@substrate-system/keys/ecc'
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### `rsa`
|
|
178
|
+
|
|
179
|
+
Import RSA functions.
|
|
180
|
+
|
|
181
|
+
```js
|
|
182
|
+
import {
|
|
183
|
+
RsaKeys,
|
|
184
|
+
encryptKeyTo,
|
|
185
|
+
encryptTo,
|
|
186
|
+
verify,
|
|
187
|
+
publicKeyToDid,
|
|
188
|
+
getPublicKeyAsUint8Array
|
|
189
|
+
} from '@substrate-system/keys/rsa'
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### [import `aes`](#aes)
|
|
193
|
+
|
|
194
|
+
Import AES (symmetric) encryption only.
|
|
195
|
+
|
|
196
|
+
```js
|
|
197
|
+
import {
|
|
198
|
+
AES,
|
|
199
|
+
importAesKey
|
|
200
|
+
} from '@substrate-system/keys/aes'
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### `crypto`
|
|
204
|
+
|
|
205
|
+
Some miscellaneous functions.
|
|
206
|
+
|
|
207
|
+
```js
|
|
208
|
+
import {
|
|
209
|
+
verify,
|
|
210
|
+
keyTypeFromDid,
|
|
211
|
+
publicKeyToDid
|
|
212
|
+
} from '@substrate-system/keys/crypto'
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
#### `crypto.verify`
|
|
216
|
+
|
|
217
|
+
The `verify` function exposed here will work with either RSA or Ed25519
|
|
218
|
+
signatures.
|
|
219
|
+
|
|
220
|
+
```js
|
|
221
|
+
const eccOk = await verify({ message, did: ecc.DID, signature: eccSig })
|
|
222
|
+
const rsaOk = await verify({ message, did: rsa.DID, signature: rsaSig })
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
#### `crypto.keyTypeFromDid`
|
|
226
|
+
|
|
227
|
+
Return a string either 'rsa' or 'ed25519' given a DID.
|
|
228
|
+
|
|
229
|
+
```js
|
|
230
|
+
const type = keyTypeFromDid(eccKeys.DID)
|
|
231
|
+
// 'ed25519'
|
|
232
|
+
|
|
233
|
+
const rsaType = keyTypeFromDid(rsaKeys.DID)
|
|
234
|
+
// 'rsa'
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
|
|
114
238
|
------------------------------------------------------
|
|
115
239
|
|
|
116
240
|
|
|
@@ -118,7 +242,9 @@ cp ./node_modules/@substrate-system/keys/dist/index.min.js ./public/keys.min.js
|
|
|
118
242
|
|
|
119
243
|
### Verify a signature
|
|
120
244
|
|
|
121
|
-
This function takes either an Ed25519 key or an RSA key.
|
|
245
|
+
This function takes either an Ed25519 key or an RSA key. This is exposed as
|
|
246
|
+
a separate function so that you do not need to bundle all of `keys` just to
|
|
247
|
+
verify something.
|
|
122
248
|
|
|
123
249
|
```js
|
|
124
250
|
import { verify } from '@substrate-system/keys/crypto'
|
|
@@ -130,9 +256,10 @@ const isOk = await verify({ message, publicKey: ecc.DID, signature })
|
|
|
130
256
|
const isOk = await verify({ message, publicKey: rsa.DID, signature })
|
|
131
257
|
```
|
|
132
258
|
|
|
133
|
-
### ECC
|
|
259
|
+
### ECC keys
|
|
134
260
|
|
|
135
261
|
#### Create a keypair
|
|
262
|
+
|
|
136
263
|
Create a new keypair, then save it in `indexedDB`.
|
|
137
264
|
|
|
138
265
|
ECC is now supported in all major browsers.
|
|
@@ -152,6 +279,67 @@ const keysAgain = await EccKeys.load()
|
|
|
152
279
|
console.assert(keys.DID === keysAgain.DID) // true
|
|
153
280
|
```
|
|
154
281
|
|
|
282
|
+
#### "Add a device"
|
|
283
|
+
|
|
284
|
+
Take an existing AES key, and encrypt it to a new ECC keypair.
|
|
285
|
+
See [asymmetric docs](./docs-asymmetric/README.md) for more about how
|
|
286
|
+
this works.
|
|
287
|
+
|
|
288
|
+
- Use `wrap()` to encrypt an AES key for a new device's public key
|
|
289
|
+
- Use `unwrap()` on the new device to recover the AES key
|
|
290
|
+
- Add devices without re-encrypting the entire dataset
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
import { EccKeys } from '@substrate-system/keys/ecc'
|
|
295
|
+
import { AES } from '@substrate-system/keys/aes'
|
|
296
|
+
|
|
297
|
+
// Device 1 has a symmetric key for encrypting data
|
|
298
|
+
const device1 = await EccKeys.create()
|
|
299
|
+
const contentKey = await AES.create({ length: 256 })
|
|
300
|
+
|
|
301
|
+
// Encrypt some data.
|
|
302
|
+
// (AES.encrypt automatically prepends iv to ciphertext).
|
|
303
|
+
const message = 'secret data for all devices'
|
|
304
|
+
const encrypted = await AES.encrypt(
|
|
305
|
+
new TextEncoder().encode(message),
|
|
306
|
+
contentKey
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
// ... device 1 needs to obtain device 2's public exchange key ...
|
|
310
|
+
|
|
311
|
+
// wrap the content key for device 2
|
|
312
|
+
const wrapped = await device1.wrap(contentKey, device2.publicExchangeKey)
|
|
313
|
+
|
|
314
|
+
console.log(wrapped)
|
|
315
|
+
// {
|
|
316
|
+
// enc: 'base64-encoded-ephemeral-public-key...',
|
|
317
|
+
// wrappedKey: 'base64-encoded-wrapped-content-key...'
|
|
318
|
+
// }
|
|
319
|
+
|
|
320
|
+
// Store encrypted data + wrapped key entries for each device
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
// -----------------------------------------
|
|
324
|
+
// device 2
|
|
325
|
+
// -----------------------------------------
|
|
326
|
+
|
|
327
|
+
// ... device 2 needs to obtain the wrapped key ...
|
|
328
|
+
|
|
329
|
+
const device2 = await EccKeys.create()
|
|
330
|
+
|
|
331
|
+
// Device 2 unwraps the content key
|
|
332
|
+
const device2ContentKey = await device2.unwrap(wrapped.enc, wrapped.wrappedKey)
|
|
333
|
+
|
|
334
|
+
// Device 2 decrypts the data with the unwrapped key
|
|
335
|
+
// (AES.decrypt automatically extracts iv from the encrypted data)
|
|
336
|
+
const decrypted = await AES.decrypt(encrypted, device2ContentKey)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
console.log(new TextDecoder().decode(decrypted))
|
|
340
|
+
// => 'secret data for all devices'
|
|
341
|
+
```
|
|
342
|
+
|
|
155
343
|
### some notes about the `keys` instance
|
|
156
344
|
|
|
157
345
|
#### `keys.DID`
|
|
@@ -352,7 +540,7 @@ const decrypted = await keys.decrypt(encryptedMsg)
|
|
|
352
540
|
|
|
353
541
|
----------------------------------------------------------------------
|
|
354
542
|
|
|
355
|
-
##
|
|
543
|
+
## Examples
|
|
356
544
|
|
|
357
545
|
### Create a new `Keys` instance
|
|
358
546
|
|
|
@@ -398,7 +586,12 @@ class RsaKeys {
|
|
|
398
586
|
- `session` (optional, boolean): If `true`, keys are created in memory only and won't be saved to `indexedDB` even if `persist()` is called.
|
|
399
587
|
- `extractable` (optional, boolean): If `true`, creates extractable keys that can be exported/read. Defaults to `false` for security.
|
|
400
588
|
|
|
401
|
-
>
|
|
589
|
+
>
|
|
590
|
+
> [!WARNING]
|
|
591
|
+
> Set `extractable: true` only when you need to export private keys.
|
|
592
|
+
> Non-extractable keys (default) are better for security.
|
|
593
|
+
>
|
|
594
|
+
|
|
402
595
|
|
|
403
596
|
#### `.create()` example
|
|
404
597
|
|
|
@@ -416,6 +609,8 @@ const extractableKeys = await EccKeys.create(false, true)
|
|
|
416
609
|
|
|
417
610
|
// Create session-only, extractable keys
|
|
418
611
|
const sessionKeys = await EccKeys.create(true, true)
|
|
612
|
+
|
|
613
|
+
// Session-only keys are not persisted.
|
|
419
614
|
```
|
|
420
615
|
|
|
421
616
|
### Get a hash of the DID
|
|
@@ -425,7 +620,7 @@ this will use the `DID` assigned to the given `Keys` instance.
|
|
|
425
620
|
|
|
426
621
|
The static method requires a `DID` string to be passed in.
|
|
427
622
|
|
|
428
|
-
####
|
|
623
|
+
#### Static `deviceName` method
|
|
429
624
|
|
|
430
625
|
```ts
|
|
431
626
|
class EccKeys { // or RsaKeys
|
|
@@ -433,7 +628,7 @@ class EccKeys { // or RsaKeys
|
|
|
433
628
|
}
|
|
434
629
|
```
|
|
435
630
|
|
|
436
|
-
####
|
|
631
|
+
#### Instance `getdeviceName` method
|
|
437
632
|
|
|
438
633
|
If used as an instance method, this will use the `DID` assigned to the instance.
|
|
439
634
|
|
|
@@ -765,17 +960,11 @@ const decrypted = await keys.decrypt(encrypted)
|
|
|
765
960
|
// => ArrayBuffer (ECC) or Uint8Array (RSA)
|
|
766
961
|
```
|
|
767
962
|
|
|
768
|
-
### Backward compatibility: `.decrypt.asString`
|
|
769
|
-
Decrypt a message, and stringify the result.
|
|
770
|
-
|
|
771
|
-
```js
|
|
772
|
-
await keys.decrypt.asString(encryptedString)
|
|
773
|
-
// => 'hello encryption'
|
|
774
|
-
```
|
|
775
|
-
|
|
776
963
|
### In memory only
|
|
964
|
+
|
|
777
965
|
Create a keypair, but do not save it in `indexedDB`, even if you call `persist`.
|
|
778
|
-
Pass `true` as the session parameter to `.create` or
|
|
966
|
+
Pass `true` as the session parameter to `.create` or
|
|
967
|
+
pass `{ session: true }` to `.load`.
|
|
779
968
|
|
|
780
969
|
```js
|
|
781
970
|
import { EccKeys } from '@substrate-system/keys/ecc'
|
|
@@ -790,11 +979,13 @@ const keysTwo = await EccKeys.load({ session: true })
|
|
|
790
979
|
```
|
|
791
980
|
|
|
792
981
|
## AES
|
|
793
|
-
|
|
982
|
+
|
|
983
|
+
Expose several AES functions, use nice defaults.
|
|
794
984
|
|
|
795
985
|
* algorithm: `AES-GCM`
|
|
796
986
|
* key size: `256`
|
|
797
|
-
* `iv` size: [`12` bytes](https://crypto.stackexchange.com/questions/41601/aes-gcm-recommended-iv-size-why-12-bytes)
|
|
987
|
+
* `iv` size: [`12` bytes (96 bits)](https://crypto.stackexchange.com/questions/41601/aes-gcm-recommended-iv-size-why-12-bytes)
|
|
988
|
+
|
|
798
989
|
|
|
799
990
|
```js
|
|
800
991
|
import { AES } from '@substrate-system/keys/aes'
|
|
@@ -806,6 +997,11 @@ const key = await AES.create(/* ... optional arguments ... */)
|
|
|
806
997
|
Create a new AES key. By default uses 256 bits & GCM algorithm.
|
|
807
998
|
|
|
808
999
|
```ts
|
|
1000
|
+
import {
|
|
1001
|
+
DEFAULT_SYMM_ALGORITHM,
|
|
1002
|
+
DEFAULT_SYMM_LENGTH
|
|
1003
|
+
} from '@substrate-system/keys/constants'
|
|
1004
|
+
|
|
809
1005
|
function create (opts:{ alg:string, length:number } = {
|
|
810
1006
|
alg: DEFAULT_SYMM_ALGORITHM, // AES-GCM
|
|
811
1007
|
length: DEFAULT_SYMM_LENGTH // 256
|
|
@@ -818,19 +1014,26 @@ const aesKey = await AES.create()
|
|
|
818
1014
|
```
|
|
819
1015
|
|
|
820
1016
|
### `export`
|
|
1017
|
+
|
|
821
1018
|
Get the AES key as a `Uint8Array`.
|
|
822
1019
|
|
|
823
1020
|
```ts
|
|
824
|
-
|
|
1021
|
+
export const AES = {
|
|
1022
|
+
async export (key:CryptoKey):Promise<Uint8Array>
|
|
1023
|
+
}
|
|
825
1024
|
```
|
|
826
1025
|
|
|
1026
|
+
#### `aes.export` example
|
|
1027
|
+
|
|
827
1028
|
```js
|
|
828
1029
|
import { AES } from '@substrate-system/keys/aes'
|
|
829
|
-
|
|
1030
|
+
|
|
1031
|
+
const exported = await AES.export(myAesKey)
|
|
830
1032
|
```
|
|
831
1033
|
|
|
832
|
-
### `
|
|
833
|
-
|
|
1034
|
+
### `export.asString`
|
|
1035
|
+
|
|
1036
|
+
Get the key as a string, `base64` encoded by default.
|
|
834
1037
|
|
|
835
1038
|
```ts
|
|
836
1039
|
async function asString (
|
|
@@ -839,9 +1042,16 @@ async function asString (
|
|
|
839
1042
|
):Promise<string>
|
|
840
1043
|
```
|
|
841
1044
|
|
|
1045
|
+
#### `export.asString` example
|
|
1046
|
+
|
|
842
1047
|
```js
|
|
843
1048
|
import { AES } from '@substrate-system/keys/aes'
|
|
844
|
-
|
|
1049
|
+
|
|
1050
|
+
const exported = await AES.export.asString(myAesKey)
|
|
1051
|
+
// => QlfjZKzzgtNMVC4fPY7S537r/PFstifTyYqcsbsCjHQ=
|
|
1052
|
+
|
|
1053
|
+
const base32 = await AES.export.asString(myAesKey, 'base32')
|
|
1054
|
+
// => ijl6gzfm6obngtcufypt3dws457ox7hrns3cpu6jrkoldoycrr2a
|
|
845
1055
|
```
|
|
846
1056
|
|
|
847
1057
|
### `AES.encrypt`
|
|
@@ -864,6 +1074,7 @@ const encryptedText = await AES.encrypt(fromString('hello AES'), aesKey)
|
|
|
864
1074
|
```
|
|
865
1075
|
|
|
866
1076
|
### `AES.decrypt`
|
|
1077
|
+
|
|
867
1078
|
```ts
|
|
868
1079
|
async function decrypt (
|
|
869
1080
|
encryptedData:Uint8Array|string,
|
|
@@ -873,7 +1084,16 @@ async function decrypt (
|
|
|
873
1084
|
```
|
|
874
1085
|
|
|
875
1086
|
```js
|
|
1087
|
+
import { toString } from 'uint8arrays'
|
|
876
1088
|
import { AES } from '@substrate-system/keys/aes'
|
|
877
1089
|
|
|
878
|
-
const
|
|
1090
|
+
const decryped = await AES.decrypt(encryptedText, aesKey)
|
|
1091
|
+
const decryptedText = toString(decrypted)
|
|
1092
|
+
// => 'hello AES'
|
|
879
1093
|
```
|
|
1094
|
+
|
|
1095
|
+
## See also
|
|
1096
|
+
|
|
1097
|
+
* [KEM Trails – Understanding Key Encapsulation Mechanisms](https://soatok.blog/2024/02/26/kem-trails-understanding-key-encapsulation-mechanisms/)
|
|
1098
|
+
> the primary motivation for KEMs comes from post-quantum cryptography, not RSA.
|
|
1099
|
+
* [Understanding HKDF](https://soatok.blog/2021/11/17/understanding-hkdf/)
|
package/dist/_base.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/_base.ts"],
|
|
4
|
-
"sourcesContent": ["import { fromString, type SupportedEncodings, toString } from 'uint8arrays'\nimport { get, set, delMany } from 'idb-keyval'\nimport type {\n CharSize,\n Msg,\n SymmKeyLength,\n DID,\n SymmKey,\n} from './types.js'\nimport { AES } from './aes/index.js'\nimport {\n toBase64,\n joinBufs,\n sha256,\n} from './util.js'\nimport {\n rsaOperations,\n publicKeyToDid,\n getPublicKeyAsArrayBuffer,\n} from './crypto.js'\n\nexport { publicKeyToDid, getPublicKeyAsArrayBuffer }\nexport * from './constants.js'\nexport type { DID }\nexport { getPublicKeyAsUint8Array } from './crypto.js'\nexport type SerializedKeys = {\n DID:DID;\n publicEncryptKey:string;\n}\n\nexport interface RsaEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface EccEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface RsaEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\nexport interface EccEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\n// Type helpers to constrain implementations\nexport type RsaKeysType = AbstractKeys & {\n encrypt: RsaEncryptor;\n encryptAsString: RsaEncryptorAsString;\n}\n\nexport type EccKeysType = AbstractKeys & {\n encrypt: EccEncryptor;\n encryptAsString: EccEncryptorAsString;\n}\n\n/**\n * Args to constructor.\n */\nexport type KeyArgs = {\n keys:{ exchange:CryptoKeyPair, write:CryptoKeyPair };\n did:DID;\n hasPersisted:boolean;\n isSessionOnly?:boolean; // in memory only?\n exchangeKeyName?:string;\n writeKeyName?:string;\n}\n\n/**\n * The class that extends AbstractKeys\n */\ninterface ChildKeys<T extends AbstractKeys = AbstractKeys> {\n new (opts:KeyArgs):T;\n _instance:T;\n TYPE:'ecc'|'rsa';\n INFO:string;\n _createExchangeKeys(extractable?:boolean):Promise<CryptoKeyPair>\n _createWriteKeys(extractable?:boolean):Promise<CryptoKeyPair>\n}\n\n/**\n * The parent key. Doesn't implement the encrypt/sign functions.\n */\nexport abstract class AbstractKeys {\n DID:DID\n exchangeKey:CryptoKeyPair\n writeKey:CryptoKeyPair\n hasPersisted:boolean\n isSessionOnly:boolean\n // type:'ecc'|'rsa'\n static EXCHANGE_KEY_NAME:string // needs to be defined by child class\n static WRITE_KEY_NAME:string\n static _instance // a cache for indexedDB\n\n constructor (opts:KeyArgs) {\n const { keys } = opts\n this.DID = opts.did\n this.exchangeKey = keys.exchange\n this.writeKey = keys.write\n this.hasPersisted = opts.hasPersisted\n this.isSessionOnly = !!opts.isSessionOnly\n }\n\n /**\n * By default, encrypt the given data to yourself, as a \"note to self\".\n */\n abstract encrypt (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKeyOrInfo?:SymmKey|Uint8Array|string,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n\n abstract encryptAsString (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKeyOrInfo?:SymmKey|Uint8Array|string,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n\n abstract decrypt(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength,\n aesAlgorithm?:string,\n ):Promise<ArrayBuffer|Uint8Array>\n\n abstract decryptAsString(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength,\n aesAlgorithm?:string,\n ):Promise<string>\n\n abstract sign(msg:Msg, charsize?:CharSize):Promise<Uint8Array>\n abstract signAsString(msg:string, charsize?:CharSize):Promise<string>\n\n publicExchangeKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicExchangeKey.asString(format)\n }\n\n publicWriteKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicWriteKey.asString(format)\n }\n\n get publicWriteKey () {\n const publicKey = this.writeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?:SupportedEncodings):Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.writeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get publicExchangeKey () {\n const publicKey = this.exchangeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?: SupportedEncodings): Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.exchangeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get privateWriteKey ():CryptoKey {\n return this.writeKey.privateKey\n }\n\n get privateExchangeKey ():CryptoKey {\n return this.exchangeKey.privateKey\n }\n\n /**\n * The machine-readable name for this keypair.\n */\n get deviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n /**\n * Return a 32-character, DNS-friendly hash of the given DID.\n *\n * @param {DID} did A DID format string\n * @returns {string} 32 character, base32 hash of the DID\n */\n static deviceName (did:DID):Promise<string> {\n return getDeviceName(did)\n }\n\n /**\n * Get the relevant AES key.\n * - if this is an ECC keypair, then use DHKE with the given public key\n * - if this is RSA, use your private key to decrypt the given AES key\n */\n abstract getAesKey (\n publicKey?:CryptoKey|string|null,\n info?:string|null\n ):Promise<CryptoKey>\n\n /**\n * Save this keys instance to `indexedDB`.\n */\n async persist ():Promise<void> {\n if (this.isSessionOnly) return\n\n const exchange = (this.constructor as typeof AbstractKeys).EXCHANGE_KEY_NAME\n const write = (this.constructor as typeof AbstractKeys).WRITE_KEY_NAME\n\n await Promise.all([\n set(exchange, this.exchangeKey),\n set(write, this.writeKey)\n ])\n\n this.hasPersisted = true\n }\n\n /**\n * Delete the keys stored in indexedDB.\n */\n async delete ():Promise<void> {\n await delMany([\n (this.constructor as typeof AbstractKeys).EXCHANGE_KEY_NAME,\n (this.constructor as typeof AbstractKeys).WRITE_KEY_NAME,\n ])\n this.hasPersisted = false\n }\n\n abstract toJson (format?:SupportedEncodings):Promise<{\n DID:DID;\n publicExchangeKey:string;\n }>\n\n /**\n * Return a 32-character, DNS friendly hash of the public signing key.\n *\n * @returns {Promise<string>}\n */\n async getDeviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n static _createExchangeKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static _createWriteKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static async create<T extends AbstractKeys> (\n this:ChildKeys,\n session?:boolean,\n extractable?:boolean,\n keys?:{\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n }\n ):Promise<T> {\n // encryption\n const exchange = keys?.exchangeKeys || await this._createExchangeKeys(\n extractable\n )\n // signatures\n const write = keys?.writeKeys || await this._createWriteKeys(extractable)\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(write)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keysInstance = new this({\n keys: { exchange, write },\n did,\n hasPersisted: false,\n isSessionOnly: !!session\n })\n\n this._instance = keysInstance\n\n return keysInstance as T\n }\n\n /**\n * Restore some keys from indexedDB, or create a new keypair if it doesn't\n * exist yet.\n *\n * @param {{ encryptionKeyName, signingKeyName, session }} opts Strings to\n * use as keys in indexedDB, and a session boolean, is this in memory\n * only? Or can it be persisted.\n * @returns {Promise<AbstractKeys>}\n */\n static async load<T extends AbstractKeys = AbstractKeys> (\n this:ChildKeys & typeof AbstractKeys,\n opts:Partial<{\n encryptionKeyName:string,\n writeKeyName:string,\n session:boolean,\n extractable:boolean,\n }> = {\n session: false,\n }\n ):Promise<T> {\n if (this._instance) return this._instance // cache\n\n let hasPersisted = true\n let exchangeKeys:CryptoKeyPair|undefined = await get(\n opts.encryptionKeyName || this.EXCHANGE_KEY_NAME\n )\n let writeKeys:CryptoKeyPair|undefined = await get(\n opts.writeKeyName || this.WRITE_KEY_NAME\n )\n\n if (!exchangeKeys) {\n hasPersisted = false\n exchangeKeys = await this._createExchangeKeys(opts.extractable)\n }\n if (!writeKeys) {\n hasPersisted = false\n writeKeys = await this._createWriteKeys(opts.extractable)\n }\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(writeKeys)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keys = new this({\n keys: { exchange: exchangeKeys, write: writeKeys },\n did,\n hasPersisted,\n isSessionOnly: !!opts.session\n }) as T\n\n this._instance = keys\n return keys\n }\n}\n\n/**\n * Encrypt the given message to the given public key. If an AES key is not\n * provided, one will be created. Use an AES key to encrypt the given\n * content, then we encrypt the AES key to the given public key.\n *\n * @param {{ content, publicKey }} opts The content to encrypt and\n * public key to encrypt to\n * @param {SymmKey|Uint8Array|string} [aesKey] An optional AES key to encrypt\n * to the given public key\n * @returns {Promise<ArrayBuffer>} The encrypted AES key, concattenated with\n * the encrypted content.\n */\nexport async function encryptTo (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string; },\n aesKey?:SymmKey|Uint8Array|string,\n):Promise<ArrayBuffer> {\n const { content, publicKey } = opts\n const key = aesKey || await AES.create()\n const encryptedContent = await AES.encrypt(\n typeof content === 'string' ? fromString(content) : content,\n typeof key === 'string' ? await AES.import(key) : key,\n )\n const encryptedKey = await encryptKeyTo({ key, publicKey })\n\n return joinBufs(encryptedKey, encryptedContent)\n}\n\n/**\n * Encrypt the given AES key to the given public key. Return the encrypted AES\n * key concattenated with the cipher text.\n *\n * @param { content, publicKey } opts The content to encrypt and key to\n * encrypt to.\n * @param {SymmKey|Uint8Array|string} [aesKey] Optional -- the AES key. One will\n * be created if not passed in.\n * @returns {Promise<string>} The encrypted AES key concattenated with the\n * cipher text.\n */\nencryptTo.asString = async function (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string },\n aesKey?:SymmKey|Uint8Array|string\n):Promise<string> {\n const joined = await encryptTo(opts, aesKey)\n return toString(new Uint8Array(joined), 'base64pad')\n}\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'arraybuffer'):Promise<ArrayBuffer>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'uint8array'):Promise<Uint8Array>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:undefined):Promise<Uint8Array>\n\n/**\n * Encrypt the given content to the given public key. This is RSA encryption,\n * and should be used only to encrypt AES keys.\n *\n * @param {{ content, publicKey }} params The content to encrypt, and public key\n * to encrypt it to.\n * @returns {Promise<Uint8Array>}\n */\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:'uint8array'|'arraybuffer'):Promise<Uint8Array|ArrayBuffer> {\n let _key:Uint8Array|string\n if (key instanceof CryptoKey) {\n _key = await AES.export(key)\n } else {\n _key = key\n }\n\n const buf = await rsaOperations.encrypt(_key, publicKey)\n if (format && format === 'arraybuffer') return buf\n return new Uint8Array(buf)\n}\n\nencryptKeyTo.asString = async function ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|string|Uint8Array;\n}, format?:SupportedEncodings):Promise<string> {\n const asArr = await encryptKeyTo({ key, publicKey })\n return format ? toString(asArr, format) : toBase64(asArr)\n}\n\n// /**\n// * Decrypt the given message with the given key. We expect the `iv` to be\n// * prefixed to the encrypted message.\n// * @param msg The message to decrypt\n// * @param key The key to decrypt with\n// * @param opts Optional args for algorithm and stuff\n// * @returns {Promise<ArrayBuffer>}\n// */\n// async function decryptBytes (\n// msg:Msg,\n// key:CryptoKey|string,\n// opts?:Partial<{\n// alg:SymmAlgorithm;\n// length: SymmKeyLength;\n// iv: ArrayBuffer;\n// }>\n// ):Promise<ArrayBuffer> {\n// const cipherText = normalizeBase64ToBuf(msg)\n// const importedKey = typeof key === 'string' ?\n// await importKey(key, opts) :\n// key\n// // `iv` is prefixed to the cypher text\n// const iv = cipherText.slice(0, IV_LENGTH)\n// const cipherBytes = cipherText.slice(IV_LENGTH)\n// const msgBuff = await webcrypto.subtle.decrypt({\n// name: DEFAULT_SYMM_ALGORITHM,\n// iv\n// }, importedKey, cipherBytes)\n\n// return msgBuff\n// }\n\nexport async function getDeviceName (did:DID|string) {\n const hashedUsername = await sha256(\n new TextEncoder().encode(did.normalize('NFD'))\n )\n\n return toString(hashedUsername, 'base32').slice(0, 32)\n}\n"],
|
|
4
|
+
"sourcesContent": ["import { fromString, type SupportedEncodings, toString } from 'uint8arrays'\nimport { get, set, delMany } from 'idb-keyval'\nimport type {\n CharSize,\n Msg,\n SymmKeyLength,\n DID,\n SymmKey,\n} from './types.js'\nimport { AES } from './aes/index.js'\nimport {\n toBase64,\n joinBufs,\n sha256,\n} from './util.js'\nimport {\n rsaOperations,\n publicKeyToDid,\n getPublicKeyAsArrayBuffer,\n} from './crypto.js'\n\nexport { publicKeyToDid, getPublicKeyAsArrayBuffer }\nexport * from './constants.js'\nexport type { DID }\nexport { getPublicKeyAsUint8Array } from './crypto.js'\nexport type SerializedKeys = {\n DID:DID;\n pulicExchangeKey:string;\n}\n\nexport interface RsaEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface EccEncryptor {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n}\n\nexport interface RsaEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\nexport interface EccEncryptorAsString {\n (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n}\n\n// Type helpers to constrain implementations\nexport type RsaKeysType = AbstractKeys & {\n encrypt: RsaEncryptor;\n encryptAsString: RsaEncryptorAsString;\n}\n\nexport type EccKeysType = AbstractKeys & {\n encrypt: EccEncryptor;\n encryptAsString: EccEncryptorAsString;\n}\n\n/**\n * Args to constructor.\n */\nexport type KeyArgs = {\n keys:{ exchange:CryptoKeyPair, write:CryptoKeyPair };\n did:DID;\n hasPersisted:boolean;\n isSessionOnly?:boolean; // in memory only?\n exchangeKeyName?:string;\n writeKeyName?:string;\n}\n\n/**\n * The class that extends AbstractKeys\n */\ninterface ChildKeys<T extends AbstractKeys = AbstractKeys> {\n new (opts:KeyArgs):T;\n _instance:T;\n TYPE:'ecc'|'rsa';\n INFO:string;\n _createExchangeKeys(extractable?:boolean):Promise<CryptoKeyPair>\n _createWriteKeys(extractable?:boolean):Promise<CryptoKeyPair>\n}\n\n/**\n * The parent key. Doesn't implement the encrypt/sign functions.\n */\nexport abstract class AbstractKeys {\n DID:DID\n exchangeKey:CryptoKeyPair\n writeKey:CryptoKeyPair\n hasPersisted:boolean\n isSessionOnly:boolean\n // type:'ecc'|'rsa'\n static EXCHANGE_KEY_NAME:string // needs to be defined by child class\n static WRITE_KEY_NAME:string\n static _instance // a cache for indexedDB\n\n constructor (opts:KeyArgs) {\n const { keys } = opts\n this.DID = opts.did\n this.exchangeKey = keys.exchange\n this.writeKey = keys.write\n this.hasPersisted = opts.hasPersisted\n this.isSessionOnly = !!opts.isSessionOnly\n }\n\n /**\n * By default, encrypt the given data to yourself, as a \"note to self\".\n */\n abstract encrypt (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKeyOrInfo?:SymmKey|Uint8Array|string,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array>\n\n abstract encryptAsString (\n content:string|Uint8Array,\n recipient?:CryptoKey|string,\n aesKeyOrInfo?:SymmKey|Uint8Array|string,\n keysizeOrAesKey?:SymmKeyLength|SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<string>\n\n abstract decrypt(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength,\n aesAlgorithm?:string,\n ):Promise<ArrayBuffer|Uint8Array>\n\n abstract decryptAsString(\n msg:string|Uint8Array|ArrayBuffer,\n publicKeyOrKeysize?:CryptoKey|string|SymmKeyLength,\n aesAlgorithm?:string,\n ):Promise<string>\n\n abstract sign(msg:Msg, charsize?:CharSize):Promise<Uint8Array>\n abstract signAsString(msg:string, charsize?:CharSize):Promise<string>\n\n publicExchangeKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicExchangeKey.asString(format)\n }\n\n publicWriteKeyAsString (format?:SupportedEncodings):Promise<string> {\n return this.publicWriteKey.asString(format)\n }\n\n get publicWriteKey () {\n const publicKey = this.writeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?:SupportedEncodings):Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.writeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get publicExchangeKey () {\n const publicKey = this.exchangeKey.publicKey\n return Object.assign(publicKey, {\n asString: async (format?: SupportedEncodings): Promise<string> => {\n const arrayBuffer = await getPublicKeyAsArrayBuffer(this.exchangeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(uint8Array)\n }\n })\n }\n\n get privateWriteKey ():CryptoKey {\n return this.writeKey.privateKey\n }\n\n get privateExchangeKey ():CryptoKey {\n return this.exchangeKey.privateKey\n }\n\n /**\n * The machine-readable name for this keypair.\n */\n get deviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n /**\n * Return a 32-character, DNS-friendly hash of the given DID.\n *\n * @param {DID} did A DID format string\n * @returns {string} 32 character, base32 hash of the DID\n */\n static deviceName (did:DID):Promise<string> {\n return getDeviceName(did)\n }\n\n /**\n * Get the relevant AES key.\n * - if this is an ECC keypair, then use DHKE with the given public key\n * - if this is RSA, use your private key to decrypt the given AES key\n */\n abstract getAesKey (\n publicKey?:CryptoKey|string|null,\n info?:string|null\n ):Promise<CryptoKey>\n\n /**\n * Save this keys instance to `indexedDB`.\n */\n async persist ():Promise<void> {\n if (this.isSessionOnly) return\n\n const exchange = (this.constructor as typeof AbstractKeys).EXCHANGE_KEY_NAME\n const write = (this.constructor as typeof AbstractKeys).WRITE_KEY_NAME\n\n await Promise.all([\n set(exchange, this.exchangeKey),\n set(write, this.writeKey)\n ])\n\n this.hasPersisted = true\n }\n\n /**\n * Delete the keys stored in indexedDB.\n */\n async delete ():Promise<void> {\n await delMany([\n (this.constructor as typeof AbstractKeys).EXCHANGE_KEY_NAME,\n (this.constructor as typeof AbstractKeys).WRITE_KEY_NAME,\n ])\n this.hasPersisted = false\n }\n\n abstract toJson (format?:SupportedEncodings):Promise<{\n DID:DID;\n publicExchangeKey:string;\n }>\n\n /**\n * Return a 32-character, DNS friendly hash of the public signing key.\n *\n * @returns {Promise<string>}\n */\n async getDeviceName ():Promise<string> {\n return AbstractKeys.deviceName(this.DID)\n }\n\n static _createExchangeKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static _createWriteKeys (_extractable?:boolean):Promise<CryptoKeyPair> {\n throw new Error('The child should implement this')\n }\n\n static async create<T extends AbstractKeys> (\n this:ChildKeys,\n session?:boolean,\n extractable?:boolean,\n keys?:{\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n }\n ):Promise<T> {\n // encryption\n const exchange = keys?.exchangeKeys || await this._createExchangeKeys(\n extractable\n )\n // signatures\n const write = keys?.writeKeys || await this._createWriteKeys(extractable)\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(write)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keysInstance = new this({\n keys: { exchange, write },\n did,\n hasPersisted: false,\n isSessionOnly: !!session\n })\n\n this._instance = keysInstance\n\n return keysInstance as T\n }\n\n /**\n * Restore some keys from indexedDB, or create a new keypair if it doesn't\n * exist yet.\n *\n * @param {{ encryptionKeyName, signingKeyName, session }} opts Strings to\n * use as keys in indexedDB, and a session boolean, is this in memory\n * only? Or can it be persisted.\n * @returns {Promise<AbstractKeys>}\n */\n static async load<T extends AbstractKeys = AbstractKeys> (\n this:ChildKeys & typeof AbstractKeys,\n opts:Partial<{\n encryptionKeyName:string,\n writeKeyName:string,\n session:boolean,\n extractable:boolean,\n }> = {\n session: false,\n }\n ):Promise<T> {\n if (this._instance) return this._instance // cache\n\n let hasPersisted = true\n let exchangeKeys:CryptoKeyPair|undefined = await get(\n opts.encryptionKeyName || this.EXCHANGE_KEY_NAME\n )\n let writeKeys:CryptoKeyPair|undefined = await get(\n opts.writeKeyName || this.WRITE_KEY_NAME\n )\n\n if (!exchangeKeys) {\n hasPersisted = false\n exchangeKeys = await this._createExchangeKeys(opts.extractable)\n }\n if (!writeKeys) {\n hasPersisted = false\n writeKeys = await this._createWriteKeys(opts.extractable)\n }\n\n const publicSigningKey = await getPublicKeyAsArrayBuffer(writeKeys)\n const did = await publicKeyToDid(\n new Uint8Array(publicSigningKey),\n this.TYPE === 'ecc' ? 'ed25519' : 'rsa'\n )\n\n const keys = new this({\n keys: { exchange: exchangeKeys, write: writeKeys },\n did,\n hasPersisted,\n isSessionOnly: !!opts.session\n }) as T\n\n this._instance = keys\n return keys\n }\n}\n\n/**\n * Encrypt the given message to the given public key. If an AES key is not\n * provided, one will be created. Use an AES key to encrypt the given\n * content, then we encrypt the AES key to the given public key.\n *\n * @param {{ content, publicKey }} opts The content to encrypt and\n * public key to encrypt to\n * @param {SymmKey|Uint8Array|string} [aesKey] An optional AES key to encrypt\n * to the given public key\n * @returns {Promise<ArrayBuffer>} The encrypted AES key, concattenated with\n * the encrypted content.\n */\nexport async function encryptTo (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string; },\n aesKey?:SymmKey|Uint8Array|string,\n):Promise<ArrayBuffer> {\n const { content, publicKey } = opts\n const key = aesKey || await AES.create()\n const encryptedContent = await AES.encrypt(\n typeof content === 'string' ? fromString(content) : content,\n typeof key === 'string' ? await AES.import(key) : key,\n )\n const encryptedKey = await encryptKeyTo({ key, publicKey })\n\n return joinBufs(encryptedKey, encryptedContent)\n}\n\n/**\n * Encrypt the given AES key to the given public key. Return the encrypted AES\n * key concattenated with the cipher text.\n *\n * @param { content, publicKey } opts The content to encrypt and key to\n * encrypt to.\n * @param {SymmKey|Uint8Array|string} [aesKey] Optional -- the AES key. One will\n * be created if not passed in.\n * @returns {Promise<string>} The encrypted AES key concattenated with the\n * cipher text.\n */\nencryptTo.asString = async function (\n opts:{ content:string|Uint8Array; publicKey:CryptoKey|string },\n aesKey?:SymmKey|Uint8Array|string\n):Promise<string> {\n const joined = await encryptTo(opts, aesKey)\n return toString(new Uint8Array(joined), 'base64pad')\n}\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'arraybuffer'):Promise<ArrayBuffer>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format:'uint8array'):Promise<Uint8Array>\n\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:undefined):Promise<Uint8Array>\n\n/**\n * Encrypt the given content to the given public key. This is RSA encryption,\n * and should be used only to encrypt AES keys.\n *\n * @param {{ content, publicKey }} params The content to encrypt, and public key\n * to encrypt it to.\n * @returns {Promise<Uint8Array>}\n */\nexport async function encryptKeyTo ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|Uint8Array|string;\n}, format?:'uint8array'|'arraybuffer'):Promise<Uint8Array|ArrayBuffer> {\n let _key:Uint8Array|string\n if (key instanceof CryptoKey) {\n _key = await AES.export(key)\n } else {\n _key = key\n }\n\n const buf = await rsaOperations.encrypt(_key, publicKey)\n if (format && format === 'arraybuffer') return buf\n return new Uint8Array(buf)\n}\n\nencryptKeyTo.asString = async function ({ key, publicKey }:{\n key:string|Uint8Array|CryptoKey;\n publicKey:CryptoKey|string|Uint8Array;\n}, format?:SupportedEncodings):Promise<string> {\n const asArr = await encryptKeyTo({ key, publicKey })\n return format ? toString(asArr, format) : toBase64(asArr)\n}\n\n// /**\n// * Decrypt the given message with the given key. We expect the `iv` to be\n// * prefixed to the encrypted message.\n// * @param msg The message to decrypt\n// * @param key The key to decrypt with\n// * @param opts Optional args for algorithm and stuff\n// * @returns {Promise<ArrayBuffer>}\n// */\n// async function decryptBytes (\n// msg:Msg,\n// key:CryptoKey|string,\n// opts?:Partial<{\n// alg:SymmAlgorithm;\n// length: SymmKeyLength;\n// iv: ArrayBuffer;\n// }>\n// ):Promise<ArrayBuffer> {\n// const cipherText = normalizeBase64ToBuf(msg)\n// const importedKey = typeof key === 'string' ?\n// await importKey(key, opts) :\n// key\n// // `iv` is prefixed to the cypher text\n// const iv = cipherText.slice(0, IV_LENGTH)\n// const cipherBytes = cipherText.slice(IV_LENGTH)\n// const msgBuff = await webcrypto.subtle.decrypt({\n// name: DEFAULT_SYMM_ALGORITHM,\n// iv\n// }, importedKey, cipherBytes)\n\n// return msgBuff\n// }\n\nexport async function getDeviceName (did:DID|string) {\n const hashedUsername = await sha256(\n new TextEncoder().encode(did.normalize('NFD'))\n )\n\n return toString(hashedUsername, 'base32').slice(0, 32)\n}\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAA8D;AAC9D,wBAAkC;AAQlC,iBAAoB;AACpB,kBAIO;AACP,oBAIO;AAGP,yBAAc,2BAtBd;AAwBA,IAAAA,iBAAyC;AAkFlC,MAAe,gBAAf,MAAe,cAAa;AAAA;AAAA,EAW/B,YAAa,MAAc;AAV3B;AACA;AACA;AACA;AACA;AAOI,UAAM,EAAE,KAAK,IAAI;AACjB,SAAK,MAAM,KAAK;AAChB,SAAK,cAAc,KAAK;AACxB,SAAK,WAAW,KAAK;AACrB,SAAK,eAAe,KAAK;AACzB,SAAK,gBAAgB,CAAC,CAAC,KAAK;AAAA,EAChC;AAAA,EAoCA,0BAA2B,QAA4C;AACnE,WAAO,KAAK,kBAAkB,SAAS,MAAM;AAAA,EACjD;AAAA,EAEA,uBAAwB,QAA4C;AAChE,WAAO,KAAK,eAAe,SAAS,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B,WAAO,MAAM,eAAI,OAAO,GAAG;AAAA,EAC/B,OAAO;AACH,WAAO;AAAA,EACX;AAEA,QAAM,MAAM,MAAM,4BAAc,QAAQ,MAAM,SAAS;AACvD,MAAI,UAAU,WAAW,cAAe,QAAO;AAC/C,SAAO,IAAI,WAAW,GAAG;AAC7B;AAdsB;AAgBtB,aAAa,WAAW,eAAgB,EAAE,KAAK,UAAU,GAGtD,QAA4C;AAC3C,QAAM,QAAQ,MAAM,aAAa,EAAE,KAAK,UAAU,CAAC;AACnD,SAAO,aAAS,6BAAS,OAAO,MAAM,QAAI,sBAAS,KAAK;AAC5D;AAkCA,eAAsB,cAAe,KAAgB;AACjD,QAAM,iBAAiB,UAAM;AAAA,IACzB,IAAI,YAAY,EAAE,OAAO,IAAI,UAAU,KAAK,CAAC;AAAA,EACjD;AAEA,aAAO,6BAAS,gBAAgB,QAAQ,EAAE,MAAM,GAAG,EAAE;AACzD;AANsB;",
|
|
6
6
|
"names": ["import_crypto"]
|
|
7
7
|
}
|
package/dist/_base.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export type { DID };
|
|
|
7
7
|
export { getPublicKeyAsUint8Array } from './crypto.js';
|
|
8
8
|
export type SerializedKeys = {
|
|
9
9
|
DID: DID;
|
|
10
|
-
|
|
10
|
+
pulicExchangeKey: string;
|
|
11
11
|
};
|
|
12
12
|
export interface RsaEncryptor {
|
|
13
13
|
(content: string | Uint8Array, recipient?: CryptoKey | string, aesKey?: SymmKey | Uint8Array | string, keysize?: SymmKeyLength): Promise<Uint8Array>;
|