@substrate-system/keys 0.2.36 → 0.2.37

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.
Files changed (50) hide show
  1. package/README.md +63 -8
  2. package/dist/_base.cjs.map +1 -1
  3. package/dist/_base.d.ts +4 -4
  4. package/dist/_base.d.ts.map +1 -1
  5. package/dist/_base.js.map +1 -1
  6. package/dist/_base.min.cjs +1 -1
  7. package/dist/_base.min.cjs.map +1 -1
  8. package/dist/_base.min.js +2 -2
  9. package/dist/_base.min.js.map +3 -3
  10. package/dist/aes/index.cjs +10 -7
  11. package/dist/aes/index.cjs.map +2 -2
  12. package/dist/aes/index.d.ts.map +1 -1
  13. package/dist/aes/index.js +10 -7
  14. package/dist/aes/index.js.map +2 -2
  15. package/dist/aes/index.min.cjs +1 -1
  16. package/dist/aes/index.min.cjs.map +2 -2
  17. package/dist/aes/index.min.js +2 -2
  18. package/dist/aes/index.min.js.map +2 -2
  19. package/dist/browser/index.js +79 -45
  20. package/dist/browser/index.min.js +2 -2
  21. package/dist/constants.cjs +3 -1
  22. package/dist/constants.cjs.map +2 -2
  23. package/dist/constants.d.ts +1 -0
  24. package/dist/constants.d.ts.map +1 -1
  25. package/dist/constants.js +3 -1
  26. package/dist/constants.js.map +2 -2
  27. package/dist/constants.min.cjs +1 -1
  28. package/dist/constants.min.cjs.map +3 -3
  29. package/dist/constants.min.js +1 -1
  30. package/dist/constants.min.js.map +3 -3
  31. package/dist/crypto.min.js +1 -1
  32. package/dist/crypto.min.js.map +2 -2
  33. package/dist/ecc/index.cjs +67 -38
  34. package/dist/ecc/index.cjs.map +2 -2
  35. package/dist/ecc/index.d.ts +33 -24
  36. package/dist/ecc/index.d.ts.map +1 -1
  37. package/dist/ecc/index.js +70 -40
  38. package/dist/ecc/index.js.map +2 -2
  39. package/dist/ecc/index.min.cjs +1 -1
  40. package/dist/ecc/index.min.cjs.map +3 -3
  41. package/dist/ecc/index.min.js +2 -2
  42. package/dist/ecc/index.min.js.map +3 -3
  43. package/dist/index.min.js +2 -2
  44. package/dist/index.min.js.map +3 -3
  45. package/dist/meta.json +16 -15
  46. package/dist/rsa/index.min.js +2 -2
  47. package/dist/rsa/index.min.js.map +3 -3
  48. package/dist/util.min.js +1 -1
  49. package/dist/util.min.js.map +2 -2
  50. package/package.json +1 -1
package/dist/ecc/index.js CHANGED
@@ -3,7 +3,7 @@ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { en
3
3
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
4
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
5
  import { webcrypto } from "@substrate-system/one-webcrypto";
6
- import { toString } from "uint8arrays";
6
+ import { toString, fromString } from "uint8arrays";
7
7
  import {
8
8
  DEFAULT_ECC_EXCHANGE,
9
9
  DEFAULT_ECC_WRITE,
@@ -12,7 +12,8 @@ import {
12
12
  IV_LENGTH,
13
13
  DEFAULT_SYMM_LENGTH,
14
14
  ECC_WRITE_ALGORITHM,
15
- ECC_EXCHANGE_ALGORITHM
15
+ ECC_EXCHANGE_ALGORITHM,
16
+ X25519_PUBLIC_KEY_LENGTH
16
17
  } from "../constants.js";
17
18
  import {
18
19
  EccCurve,
@@ -126,14 +127,16 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
126
127
  * 1. Generate ephemeral X25519 keypair
127
128
  * 2. Do ECDH with recipient's public key -> shared secret
128
129
  * 3. Use HKDF to derive a KEK (key encryption key)
129
- * 4. AES-GCM encrypt the content key under the KEK
130
+ * 4. AES-GCM encrypt the content
130
131
  * 5. Return the ephemeral public key (encapsulation) + wrapped key
131
132
  *
132
- * @param contentKey The existing AES key used to encrypt the content.
133
- * @param newPublicKey The new device's public X25519 key.
134
- * @param info Optional info parameter for HKDF. Defaults to 'key-wrap'.
133
+ * @param {SymmKey|Uint8Array|string} contentKey The existing AES key used
134
+ * to encrypt the content. Can be a base64 encoded string.
135
+ * @param {CryptoKey} newPublicKey The new device's public X25519 key.
136
+ * @param {string} [info] Optional info parameter for HKDF.
137
+ * Defaults to 'key-wrap'.
135
138
  * @returns {Promise<WrappedKey>} The ephemeral public key (base64) and
136
- * the wrapped content key (base64).
139
+ * the wrapped AES key (base64).
137
140
  */
138
141
  async wrap(contentKey, newPublicKey, info) {
139
142
  const ephemeralKeypair = await _EccKeys._createExchangeKeys(true);
@@ -149,7 +152,7 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
149
152
  const exported = await crypto.subtle.exportKey("raw", contentKey);
150
153
  contentKeyBytes = new Uint8Array(exported);
151
154
  } else if (typeof contentKey === "string") {
152
- contentKeyBytes = new Uint8Array(base64ToArrBuf(contentKey));
155
+ contentKeyBytes = fromString(contentKey, "base64pad");
153
156
  } else {
154
157
  contentKeyBytes = contentKey;
155
158
  }
@@ -218,17 +221,22 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
218
221
  * Encrypt the given content to the given public key, or encrypt to
219
222
  * our own public key if a key is not passed in.
220
223
  *
224
+ * This does ECIES style encryption -- a new ephemeral keypair is generated
225
+ * and used to encrypt the message with ephemeral private + recipient public.
226
+ * The public key from the ephemeral keypair is prefixed to the cipher text.
227
+ *
221
228
  * @param {string|Uint8Array} content Content to encrypt
222
229
  * @param {CryptoKey|string} [recipient] Their public key. Optional b/c we
223
- * will use our own public key if not passed in.
230
+ * will use our own public key if not passed in. Can be a CryptoKey
231
+ * or a base64 encoded string.
224
232
  * @param {string} [info] info tag for HKDF. Default is the class property.
225
- * @param {SymmKey|Uint8Array|string} aesKey This is not relevant for most
233
+ * @param {SymmKey|Uint8Array|string} [aesKey] This is not relevant for most
226
234
  * use cases.
227
235
  * @param {SymmKeyLength} [keysize] Default is 256
228
- * @returns {Promise<ArrayBuffer>} Buffer of salt + iv + cipher text
236
+ * @returns {Promise<ArrayBuffer>} Buffer of ephemeral-public-key + salt +
237
+ * iv + cipher text
229
238
  */
230
239
  async encrypt(content, recipient, info, aesKey, keysize) {
231
- const encoder = new TextEncoder();
232
240
  const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
233
241
  const _publicKey = recipient || this.exchangeKey.publicKey;
234
242
  let publicKey;
@@ -241,8 +249,10 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
241
249
  } else {
242
250
  publicKey = _publicKey;
243
251
  }
252
+ const ephemeralKeypair = await _EccKeys._createExchangeKeys(true);
244
253
  let key = aesKey || await deriveKey(
245
- this.exchangeKey.privateKey,
254
+ ephemeralKeypair.privateKey,
255
+ // use ephemeral private key
246
256
  publicKey,
247
257
  salt,
248
258
  info || _EccKeys.INFO,
@@ -250,27 +260,32 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
250
260
  );
251
261
  if (!(key instanceof CryptoKey)) {
252
262
  key = await deriveKey(
253
- this.exchangeKey.privateKey,
263
+ ephemeralKeypair.privateKey,
264
+ // use ephemeral private key
254
265
  publicKey,
255
266
  salt,
256
267
  info || _EccKeys.INFO
257
268
  );
258
269
  }
259
270
  const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
260
- const plaintext = typeof content === "string" ? encoder.encode(content) : content;
271
+ const plaintext = typeof content === "string" ? new TextEncoder().encode(content) : content;
261
272
  const ciphertext = await crypto.subtle.encrypt(
262
273
  { name: DEFAULT_SYMM_ALGORITHM, iv },
263
274
  key,
264
275
  toArrayBuffer(plaintext)
265
276
  );
277
+ const ephemeralPubKeyBuf = new Uint8Array(
278
+ await exportPublicKey(ephemeralKeypair)
279
+ );
266
280
  const saltBuffer = new Uint8Array(salt);
267
281
  const ivBuffer = new Uint8Array(iv);
268
282
  const cipherBuf = new Uint8Array(ciphertext);
269
- const size = saltBuffer.length + ivBuffer.length + cipherBuf.length;
283
+ const size = ephemeralPubKeyBuf.length + saltBuffer.length + ivBuffer.length + cipherBuf.length;
270
284
  const result = new Uint8Array(size);
271
- result.set(saltBuffer, 0);
272
- result.set(ivBuffer, saltBuffer.length);
273
- result.set(cipherBuf, saltBuffer.length + ivBuffer.length);
285
+ result.set(ephemeralPubKeyBuf, 0);
286
+ result.set(saltBuffer, ephemeralPubKeyBuf.length);
287
+ result.set(ivBuffer, ephemeralPubKeyBuf.length + saltBuffer.length);
288
+ result.set(cipherBuf, ephemeralPubKeyBuf.length + saltBuffer.length + ivBuffer.length);
274
289
  return result;
275
290
  }
276
291
  /**
@@ -288,26 +303,41 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
288
303
  }
289
304
  /**
290
305
  * Decrypt the given message. The encrypted message should be
291
- * salt + iv + cipher text.
306
+ * ephemeral public key + salt + iv + cipher text.
307
+ *
308
+ * The ephemeral public key is extracted from the beginning of the message
309
+ * and used with our private key to derive the AES decryption key.
310
+ *
292
311
  * @param msg The encrypted content
293
- * @param {CryptoKey|string} [publicKey] The public key used to generate
294
- * the AES key used on this message. If omitted, decrypt with our own
295
- * public key.
296
312
  * @param {string} aesAlgorithm The algorithm. Default is AES-GCM.
297
313
  * @param {string} info Custom "info" parameter
298
314
  * @returns {Promise<ArrayBuffer>} The decrypted content.
299
315
  */
300
- async decrypt(msg, publicKey, aesAlgorithm, info) {
301
- let pub = typeof publicKey === "string" ? await importPublicKey(publicKey, EccCurve.X25519, KeyUse.Write) : publicKey;
302
- if (!pub) pub = this.publicExchangeKey;
316
+ async decrypt(msg, aesAlgorithm, info) {
303
317
  const encrypted = normalizeToBuf(msg, base64ToArrBuf);
304
- const salt = encrypted.slice(0, SALT_LENGTH);
305
- const iv = encrypted.slice(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
306
- const ciphertext = encrypted.slice(SALT_LENGTH + IV_LENGTH);
318
+ const ephemeralPubKeyBuf = encrypted.slice(0, X25519_PUBLIC_KEY_LENGTH);
319
+ const ephemeralPublicKey = await webcrypto.subtle.importKey(
320
+ "raw",
321
+ ephemeralPubKeyBuf,
322
+ { name: ECC_EXCHANGE_ALGORITHM },
323
+ true,
324
+ []
325
+ );
326
+ const salt = encrypted.slice(
327
+ X25519_PUBLIC_KEY_LENGTH,
328
+ X25519_PUBLIC_KEY_LENGTH + SALT_LENGTH
329
+ );
330
+ const iv = encrypted.slice(
331
+ X25519_PUBLIC_KEY_LENGTH + SALT_LENGTH,
332
+ X25519_PUBLIC_KEY_LENGTH + SALT_LENGTH + IV_LENGTH
333
+ );
334
+ const ciphertext = encrypted.slice(
335
+ X25519_PUBLIC_KEY_LENGTH + SALT_LENGTH + IV_LENGTH
336
+ );
307
337
  const { privateKey } = this.exchangeKey;
308
338
  const key = await deriveKey(
309
339
  privateKey,
310
- pub,
340
+ ephemeralPublicKey,
311
341
  salt,
312
342
  info || _EccKeys.INFO
313
343
  );
@@ -322,19 +352,19 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
322
352
  return decrypted;
323
353
  }
324
354
  /**
325
- * Decrypt and return as string.
326
- * The encrypted message should be salt + iv + cipher text.
355
+ * Decrypt and return as string using ECIES. The encrypted message should be
356
+ * ephemeral public key + salt + iv + cipher text.
357
+ *
358
+ * The ephemeral public key is extracted from the beginning of the message
359
+ * and used with our private key to derive the AES decryption key.
327
360
  *
328
361
  * @param msg The encrypted content
329
- * @param {CryptoKey|string} [publicKey] The public key used to generate
330
- * the AES key used on this message. If omitted, decrypt with our own
331
- * public key.
332
362
  * @param {string} aesAlgorithm The algorithm. Default is AES-GCM.
333
363
  * @param {string} info Custom "info" parameter
334
- * @returns {Promise<ArrayBuffer>} The decrypted content.
364
+ * @returns {Promise<string>} The decrypted content as a string.
335
365
  */
336
- async decryptAsString(msg, publicKey, aesAlgorithm, info) {
337
- const dec = await this.decrypt(msg, publicKey, aesAlgorithm, info);
366
+ async decryptAsString(msg, aesAlgorithm, info) {
367
+ const dec = await this.decrypt(msg, aesAlgorithm, info);
338
368
  return toString(new Uint8Array(dec));
339
369
  }
340
370
  /**
@@ -438,8 +468,8 @@ Object.assign(EccKeys.prototype.encrypt, {
438
468
  }, "asString")
439
469
  });
440
470
  Object.assign(EccKeys.prototype.decrypt, {
441
- asString: /* @__PURE__ */ __name(async function(msg, publicKey, aesAlgorithm) {
442
- return this.decryptAsString(msg, publicKey, aesAlgorithm);
471
+ asString: /* @__PURE__ */ __name(async function(msg, aesAlgorithm) {
472
+ return this.decryptAsString(msg, aesAlgorithm);
443
473
  }, "asString")
444
474
  });
445
475
  Object.assign(EccKeys.prototype.sign, {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/ecc/index.ts"],
4
- "sourcesContent": ["import { webcrypto } from '@substrate-system/one-webcrypto'\nimport { type SupportedEncodings, toString } from 'uint8arrays'\nimport {\n DEFAULT_ECC_EXCHANGE,\n DEFAULT_ECC_WRITE,\n DEFAULT_SYMM_ALGORITHM,\n SALT_LENGTH,\n IV_LENGTH,\n DEFAULT_SYMM_LENGTH,\n ECC_WRITE_ALGORITHM,\n ECC_EXCHANGE_ALGORITHM\n} from '../constants.js'\nimport {\n EccCurve,\n KeyUse,\n type PublicKey,\n type SymmKeyLength,\n type SymmKey,\n type Msg,\n type CharSize,\n type DID,\n type WrappedKey,\n} from '../types.js'\nimport {\n base64ToArrBuf,\n normalizeToBuf,\n toBase64,\n didToPublicKey\n} from '../util.js'\nimport { checkValidKeyUse } from '../errors.js'\nimport { AbstractKeys, type KeyArgs } from '../_base.js'\n\n// Helper function to ensure proper ArrayBuffer type\nfunction toArrayBuffer (data:Uint8Array):ArrayBuffer {\n return new Uint8Array(data).buffer\n}\n\n/**\n * Class for ECC keys\n */\nexport class EccKeys extends AbstractKeys {\n static TYPE:'ecc'|'rsa' = 'ecc' as const\n static EXCHANGE_KEY_NAME:string = DEFAULT_ECC_EXCHANGE\n static WRITE_KEY_NAME:string = DEFAULT_ECC_WRITE\n static INFO = 'keys'\n\n /**\n * Factory function.\n * @param {boolean} [session] Session only? i.e., not saved in indexedDB.\n * Default `false`.\n * @param {boolean} [extractable] Can we extract the private keys? Default\n * `false`.\n * @param {{ exchangeKeys, writeKeys }} [keys] A set of keys to use here.\n * @returns {Promise<EccKeys>} A new class instance.\n */\n static async create<T extends AbstractKeys = EccKeys> (\n session?:boolean,\n extractable?:boolean,\n keys?:{\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n }\n ):Promise<T> {\n return await super.create<T>(session, extractable, keys)\n }\n\n constructor (opts:KeyArgs) {\n super(opts)\n EccKeys.EXCHANGE_KEY_NAME = opts.exchangeKeyName || DEFAULT_ECC_EXCHANGE\n EccKeys.WRITE_KEY_NAME = opts.writeKeyName || DEFAULT_ECC_WRITE\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 exportPublicKey(this.exchangeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(arrayBuffer)\n }\n })\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 exportPublicKey(this.writeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(arrayBuffer)\n }\n })\n }\n\n static async _createExchangeKeys (\n extractable:boolean = false\n ):Promise<CryptoKeyPair> {\n /**\n * don't use `{ name: ECDH, namedCurve: 'X25519' }`, use\n * `{ name: 'X25519' }`.\n *\n * X25519/Ed25519 don't use `namedCurve`.\n */\n return await webcrypto.subtle.generateKey(\n {\n name: ECC_EXCHANGE_ALGORITHM\n // namedCurve: EccCurve.X25519\n },\n extractable,\n ['deriveKey', 'deriveBits']\n ) as CryptoKeyPair\n }\n\n static async _createWriteKeys (extractable:boolean = false):Promise<CryptoKeyPair> {\n return await webcrypto.subtle.generateKey(\n {\n name: ECC_WRITE_ALGORITHM\n },\n extractable,\n ['sign', 'verify']\n )\n }\n\n /**\n * Restore some keys from indexedDB, or create a new keypair if it doesn't\n * exist yet. Overrides base class to use ECC-specific key names.\n */\n static async load<T extends AbstractKeys = EccKeys> (\n this:typeof EccKeys,\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 as T // cache\n\n // Use ECC-specific key names as defaults\n const exchangeKeyName = opts.encryptionKeyName || DEFAULT_ECC_EXCHANGE\n const writeKeyName = opts.writeKeyName || DEFAULT_ECC_WRITE\n\n return super.load({\n ...opts,\n encryptionKeyName: exchangeKeyName,\n writeKeyName\n }) as Promise<T>\n }\n\n /**\n * Serialize this keys instance. Will return an object of\n * { DID, publicExchangeKey }, where DID is the public write key,\n * and `publicExchangeKey` is the encryption key, `base64` encoded.\n * @returns {Promise<{ DID:DID, publicExchangeKey:string }>}\n */\n async toJson (\n format?:SupportedEncodings\n ):Promise<{ DID:DID; publicExchangeKey:string; }> {\n const did = this.DID\n\n const rawKey = await exportPublicKey(this.exchangeKey)\n\n const keyString = (format ?\n toString(new Uint8Array(rawKey), format) :\n toBase64(rawKey))\n\n return {\n publicExchangeKey: keyString,\n DID: did\n }\n }\n\n /**\n * \"Add a device,\" meaning, take an existing AES key and add the ability\n * for a new keypair to decrypt/use the AES key.\n *\n * This implements HPKE-style key wrapping:\n * 1. Generate ephemeral X25519 keypair\n * 2. Do ECDH with recipient's public key -> shared secret\n * 3. Use HKDF to derive a KEK (key encryption key)\n * 4. AES-GCM encrypt the content key under the KEK\n * 5. Return the ephemeral public key (encapsulation) + wrapped key\n *\n * @param contentKey The existing AES key used to encrypt the content.\n * @param newPublicKey The new device's public X25519 key.\n * @param info Optional info parameter for HKDF. Defaults to 'key-wrap'.\n * @returns {Promise<WrappedKey>} The ephemeral public key (base64) and\n * the wrapped content key (base64).\n */\n async wrap (\n contentKey:SymmKey|Uint8Array|string,\n newPublicKey:CryptoKey, // the new device's public key\n info?:string\n ):Promise<WrappedKey> {\n // 1. Generate ephemeral X25519 keypair\n const ephemeralKeypair = await EccKeys._createExchangeKeys(true)\n\n // 2. Generate random salt for HKDF\n const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH))\n\n // 3. Derive KEK using ECDH + HKDF with ephemeral private key and\n // recipient's public key\n const kek = await deriveKey(\n ephemeralKeypair.privateKey,\n newPublicKey,\n salt,\n info || 'key-wrap'\n )\n\n // 4. Prepare the content key for encryption\n let contentKeyBytes:Uint8Array\n if (contentKey instanceof CryptoKey) {\n // Export the AES key to raw format\n const exported = await crypto.subtle.exportKey('raw', contentKey)\n contentKeyBytes = new Uint8Array(exported)\n } else if (typeof contentKey === 'string') {\n contentKeyBytes = new Uint8Array(base64ToArrBuf(contentKey))\n } else {\n contentKeyBytes = contentKey\n }\n\n // 5. Generate IV for AES-GCM encryption\n const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH))\n\n // 6. Encrypt the content key with the KEK\n const wrappedKeyBuffer = await crypto.subtle.encrypt(\n { name: DEFAULT_SYMM_ALGORITHM, iv },\n kek,\n toArrayBuffer(contentKeyBytes)\n )\n\n // 7. Export ephemeral public key\n const ephemeralPubKeyBuffer = await exportPublicKey(ephemeralKeypair)\n\n // 8. Combine salt + iv + wrapped key for the final wrapped key blob\n const saltBuf = new Uint8Array(salt)\n const ivBuf = new Uint8Array(iv)\n const wrappedBuf = new Uint8Array(wrappedKeyBuffer)\n const combinedSize = saltBuf.length + ivBuf.length + wrappedBuf.length\n const combined = new Uint8Array(combinedSize)\n combined.set(saltBuf, 0)\n combined.set(ivBuf, saltBuf.length)\n combined.set(wrappedBuf, saltBuf.length + ivBuf.length)\n\n // 9. Return base64-encoded results\n return {\n enc: toBase64(new Uint8Array(ephemeralPubKeyBuffer)),\n wrappedKey: toBase64(combined)\n }\n }\n\n /**\n * Unwrap a content key that was wrapped for this device using the `add` method.\n *\n * The recipient device uses its private key + the ephemeral public key\n * to rederive the KEK and decrypt the wrapped content key.\n *\n * @param enc The ephemeral public key (base64) from the sender.\n * @param wrappedKey The wrapped content key (base64) - contains salt + iv + ciphertext.\n * @param info Optional info parameter for HKDF. Must match what was used in `add`. Defaults to 'key-wrap'.\n * @returns {Promise<CryptoKey>} The unwrapped AES content key.\n */\n async unwrap (\n enc:string,\n wrappedKey:string,\n info?:string\n ):Promise<CryptoKey> {\n // 1. Import the ephemeral public key\n const ephemeralPubKey = await importPublicKey(\n enc,\n EccCurve.X25519,\n KeyUse.Exchange\n )\n\n // 2. Decode the wrapped key blob and extract salt, iv, and ciphertext\n const wrappedBuf = new Uint8Array(base64ToArrBuf(wrappedKey))\n const salt = wrappedBuf.slice(0, SALT_LENGTH)\n const iv = wrappedBuf.slice(SALT_LENGTH, SALT_LENGTH + IV_LENGTH)\n const ciphertext = wrappedBuf.slice(SALT_LENGTH + IV_LENGTH)\n\n // 3. Derive the same KEK using our private key and the ephemeral public key\n const kek = await deriveKey(\n this.exchangeKey.privateKey,\n ephemeralPubKey,\n salt,\n info || 'key-wrap'\n )\n\n // 4. Decrypt the wrapped key\n const contentKeyBytes = await crypto.subtle.decrypt(\n { name: DEFAULT_SYMM_ALGORITHM, iv },\n kek,\n toArrayBuffer(ciphertext)\n )\n\n // 5. Import the content key back as a CryptoKey\n const contentKey = await crypto.subtle.importKey(\n 'raw',\n contentKeyBytes,\n { name: DEFAULT_SYMM_ALGORITHM },\n true,\n ['encrypt', 'decrypt']\n )\n\n return contentKey\n }\n\n /**\n * Encrypt the given content to the given public key, or encrypt to\n * our own public key if a key is not passed in.\n *\n * @param {string|Uint8Array} content Content to encrypt\n * @param {CryptoKey|string} [recipient] Their public key. Optional b/c we\n * will use our own public key if not passed in.\n * @param {string} [info] info tag for HKDF. Default is the class property.\n * @param {SymmKey|Uint8Array|string} aesKey This is not relevant for most\n * use cases.\n * @param {SymmKeyLength} [keysize] Default is 256\n * @returns {Promise<ArrayBuffer>} Buffer of salt + iv + cipher text\n */\n async encrypt (\n content:string|Uint8Array,\n recipient?:CryptoKey|string, // their public key\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength\n ):Promise<Uint8Array> {\n const encoder = new TextEncoder()\n const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH))\n\n // publicKey is either passed in or we use our own for note to self\n const _publicKey = (recipient || this.exchangeKey.publicKey)\n let publicKey:CryptoKey\n if (typeof _publicKey === 'string') {\n publicKey = await importPublicKey(\n _publicKey,\n EccCurve.X25519,\n KeyUse.Exchange\n )\n } else {\n publicKey = _publicKey\n }\n\n // key is passed in or derived\n let key = aesKey || (await deriveKey(\n this.exchangeKey.privateKey,\n publicKey,\n salt,\n info || EccKeys.INFO,\n keysize\n ))\n\n // if a key was passed in, but it is not a CryptoKey instance\n if (!(key instanceof CryptoKey)) {\n key = await deriveKey(\n this.exchangeKey.privateKey,\n publicKey,\n salt,\n info || EccKeys.INFO\n )\n }\n const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH))\n const plaintext:Uint8Array = (typeof content === 'string' ?\n encoder.encode(content) :\n content)\n\n const ciphertext = await crypto.subtle.encrypt(\n { name: DEFAULT_SYMM_ALGORITHM, iv },\n key,\n toArrayBuffer(plaintext)\n )\n\n // Prepend salt and IV to the ciphertext for decryption\n const saltBuffer = new Uint8Array(salt)\n const ivBuffer = new Uint8Array(iv)\n const cipherBuf = new Uint8Array(ciphertext)\n const size = saltBuffer.length + ivBuffer.length + cipherBuf.length\n const result = new Uint8Array(size)\n result.set(saltBuffer, 0)\n result.set(ivBuffer, saltBuffer.length)\n result.set(cipherBuf, saltBuffer.length + ivBuffer.length)\n\n return result\n }\n\n /**\n * Encrypt and return as base64 string.\n */\n async encryptAsString (\n content:string|Uint8Array,\n recipient?:CryptoKey|string, // their public key\n info?:string,\n aesKey?:SymmKey|Uint8Array|string,\n keysize?:SymmKeyLength,\n ):Promise<string> {\n const encrypted = await this.encrypt(\n content,\n recipient,\n info || EccKeys.INFO,\n aesKey,\n keysize\n )\n\n return toString(new Uint8Array(encrypted), 'base64pad')\n }\n\n /**\n * Decrypt the given message. The encrypted message should be\n * salt + iv + cipher text.\n * @param msg The encrypted content\n * @param {CryptoKey|string} [publicKey] The public key used to generate\n * the AES key used on this message. If omitted, decrypt with our own\n * public key.\n * @param {string} aesAlgorithm The algorithm. Default is AES-GCM.\n * @param {string} info Custom \"info\" parameter\n * @returns {Promise<ArrayBuffer>} The decrypted content.\n */\n async decrypt (\n msg:string|Uint8Array|ArrayBuffer,\n publicKey?:CryptoKey|string,\n aesAlgorithm?:string,\n info?:string,\n ):Promise<ArrayBuffer|Uint8Array> {\n let pub = (typeof publicKey === 'string' ?\n await importPublicKey(publicKey, EccCurve.X25519, KeyUse.Write) :\n publicKey)\n\n if (!pub) pub = this.publicExchangeKey\n\n // first get the salt & iv from the cipher text\n const encrypted = normalizeToBuf(msg, base64ToArrBuf)\n const salt = encrypted.slice(0, SALT_LENGTH)\n const iv = encrypted.slice(SALT_LENGTH, SALT_LENGTH + IV_LENGTH)\n const ciphertext = encrypted.slice(SALT_LENGTH + IV_LENGTH)\n const { privateKey } = this.exchangeKey\n const key = await deriveKey(\n privateKey,\n pub,\n salt,\n info || EccKeys.INFO\n )\n\n // we have the key, now decrypt the message\n const decrypted = await crypto.subtle.decrypt(\n {\n name: aesAlgorithm || DEFAULT_SYMM_ALGORITHM,\n iv,\n },\n key,\n ciphertext\n )\n\n return decrypted\n }\n\n /**\n * Decrypt and return as string.\n * The encrypted message should be salt + iv + cipher text.\n *\n * @param msg The encrypted content\n * @param {CryptoKey|string} [publicKey] The public key used to generate\n * the AES key used on this message. If omitted, decrypt with our own\n * public key.\n * @param {string} aesAlgorithm The algorithm. Default is AES-GCM.\n * @param {string} info Custom \"info\" parameter\n * @returns {Promise<ArrayBuffer>} The decrypted content.\n */\n async decryptAsString (\n msg:string|Uint8Array|ArrayBuffer,\n publicKey?:CryptoKey|string,\n aesAlgorithm?:string,\n info?:string,\n ):Promise<string> {\n const dec = await this.decrypt(msg, publicKey, aesAlgorithm, info)\n return toString(new Uint8Array(dec))\n }\n\n /**\n * Do DHKE, create a new AES-GCM key.\n *\n * @param {CryptoKey|string|null} [publicKey] Public key to use in DHKE.\n * Will use our public key if it is not passed in.\n * @param {string} info The info parameter for DHKE. Will use the class\n * property `INFO` if it is not passed in.\n * @returns {CryptoKey} New AES key\n */\n async getAesKey (\n publicKey?:CryptoKey|string|null,\n info?:string|null,\n ):Promise<CryptoKey> {\n if (!publicKey) {\n publicKey = this.publicExchangeKey\n }\n\n let pub:CryptoKey\n if (typeof publicKey === 'string') {\n pub = await importPublicKey(\n publicKey,\n EccCurve.X25519,\n KeyUse.Exchange\n )\n } else {\n pub = publicKey\n }\n\n // Generate a random salt for HKDF\n const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH))\n\n // Derive AES key using ECDH + HKDF\n const aesKey = await deriveKey(\n this.exchangeKey.privateKey,\n pub,\n salt,\n info || EccKeys.INFO\n )\n\n return aesKey\n }\n\n /**\n * Sign the given content using our private write key.\n */\n async sign (msg:Msg, _charsize?:CharSize):Promise<Uint8Array> {\n const encoder = new TextEncoder()\n let data:Uint8Array\n\n if (typeof msg === 'string') {\n data = encoder.encode(msg)\n } else if (msg instanceof ArrayBuffer) {\n data = new Uint8Array(msg)\n } else {\n data = msg\n }\n\n const signature = await webcrypto.subtle.sign(\n { name: ECC_WRITE_ALGORITHM },\n this.writeKey.privateKey,\n toArrayBuffer(data)\n )\n\n return new Uint8Array(signature)\n }\n\n /**\n * Sign the given content and return as base64 string.\n */\n async signAsString (msg:string, _charsize?:CharSize):Promise<string> {\n const signature = await this.sign(msg, _charsize)\n return toString(signature, 'base64pad')\n }\n}\n\n// Attach asString to the prototype method for backward compatibility\nObject.assign(EccKeys.prototype.sign, {\n asString: async function (\n this:EccKeys,\n msg:string,\n _charsize?:CharSize\n ):Promise<string> {\n const signature = await this.sign(msg, _charsize)\n return toString(signature, 'base64pad')\n }\n})\n\n/**\n * Get the public key from a given keypair.\n *\n * @param {CryptoKeyPair} keypair The keypair to get the public side from.\n * @returns {Promise<ArrayBuffer>} ArrayBuffer of public key material\n */\nexport async function exportPublicKey(\n keypair:CryptoKeyPair,\n format:'jwk'\n):Promise<JsonWebKey>\n\nexport async function exportPublicKey(\n keypair:CryptoKeyPair,\n format?:'raw'|'spki'|'pkcs8'\n):Promise<ArrayBuffer>\n\nexport async function exportPublicKey (\n keypair:CryptoKeyPair,\n format:KeyFormat = 'raw'\n):Promise<JsonWebKey|ArrayBuffer> {\n return await crypto.subtle.exportKey(format, keypair.publicKey)\n}\n\nexport async function importPublicKey (\n base64Key:string,\n curve:EccCurve,\n use:KeyUse\n):Promise<PublicKey> {\n checkValidKeyUse(use)\n const alg = use === KeyUse.Exchange ? ECC_EXCHANGE_ALGORITHM : ECC_WRITE_ALGORITHM\n const uses:KeyUsage[] = use === KeyUse.Exchange ? [] : ['verify']\n const buf = base64ToArrBuf(base64Key)\n\n // X25519 doesn't use namedCurve in the algorithm parameter\n const algorithm = (curve === EccCurve.X25519) ?\n { name: alg } :\n { name: alg, namedCurve: curve }\n\n return webcrypto.subtle.importKey(\n 'raw',\n buf,\n algorithm,\n true,\n uses\n )\n}\n\nexport default {\n EccKeys,\n importPublicKey\n}\n\n// Add backward compatibility by attaching asString methods to prototypes\nObject.assign(EccKeys.prototype.encrypt, {\n asString: async function (\n this: EccKeys,\n content: string | Uint8Array,\n recipient?: CryptoKey | string,\n info?: string,\n aesKey?: SymmKey | Uint8Array | string,\n keysize?: SymmKeyLength\n ): Promise<string> {\n return this.encryptAsString(content, recipient, info, aesKey, keysize)\n }\n})\n\nObject.assign(EccKeys.prototype.decrypt, {\n asString: async function (\n this: EccKeys,\n msg: string | Uint8Array | ArrayBuffer,\n publicKey?: CryptoKey | string,\n aesAlgorithm?: string\n ): Promise<string> {\n return this.decryptAsString(msg, publicKey, aesAlgorithm)\n }\n})\n\nObject.assign(EccKeys.prototype.sign, {\n asString: async function (\n this: EccKeys,\n msg: string,\n _charsize?: CharSize\n ): Promise<string> {\n return this.signAsString(msg, _charsize)\n }\n})\n\n/**\n * Check that the given signature is valid with the given message.\n * This uses Ed25519 verification.\n */\nexport async function verify (\n msg:string|Uint8Array,\n sig:string|Uint8Array,\n signingDid:DID\n):Promise<boolean> {\n try {\n const _key = didToPublicKey(signingDid)\n\n // Verify it's an Ed25519 key\n if (_key.type !== 'ed25519') {\n throw new Error(`Expected Ed25519 key for ECC verification, got ${_key.type}`)\n }\n\n // Extract raw Ed25519 key from DER encoding\n // DER format has 12-byte header, then 32-byte raw key\n const rawKeyBytes = _key.publicKey.slice(-32)\n\n // Import the public key for verification\n const publicKey = await webcrypto.subtle.importKey(\n 'raw',\n rawKeyBytes,\n { name: ECC_WRITE_ALGORITHM },\n true,\n ['verify']\n )\n\n // Prepare the message using the same encoding as the sign function\n const encoder = new TextEncoder()\n let data:Uint8Array\n\n if (typeof msg === 'string') {\n data = encoder.encode(msg)\n } else if (msg instanceof ArrayBuffer) {\n data = new Uint8Array(msg)\n } else {\n data = msg\n }\n\n // Prepare the signature - handle both string and Uint8Array\n let signature:Uint8Array\n if (typeof sig === 'string') {\n signature = new Uint8Array(base64ToArrBuf(sig))\n } else {\n signature = sig\n }\n\n // Verify the signature\n const isValid = await webcrypto.subtle.verify(\n { name: ECC_WRITE_ALGORITHM },\n publicKey,\n toArrayBuffer(signature),\n toArrayBuffer(data)\n )\n\n return isValid\n } catch (_err) {\n return false\n }\n}\n\n/**\n * Derive an AES key from X25519 keypair via ECDH + HKDF\n */\nasync function deriveKey (\n privateKey:CryptoKey,\n publicKey:CryptoKey,\n salt:Uint8Array|ArrayBuffer,\n info:string,\n keysize?:number\n):Promise<CryptoKey> {\n const encoder = new TextEncoder()\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'X25519', public: publicKey },\n privateKey,\n 256\n )\n\n const hkdfBaseKey = await crypto.subtle.importKey(\n 'raw',\n sharedSecret,\n 'HKDF',\n false,\n ['deriveKey']\n )\n\n return crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: salt instanceof Uint8Array ? toArrayBuffer(salt) : salt,\n info: encoder.encode(info)\n },\n hkdfBaseKey,\n { name: 'AES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,UAAM,UAAU,MAAM,UAAU,OAAO;AAAA,MACnC,EAAE,MAAM,oBAAoB;AAAA,MAC5B;AAAA,MACA,cAAc,SAAS;AAAA,MACvB,cAAc,IAAI;AAAA,IACtB;AAEA,WAAO;AAAA,EACX,SAAS,MAAM;AACX,WAAO;AAAA,EACX;AACJ;AA1DsB;AA+DtB,eAAe,UACX,YACA,WACA,MACA,MACA,SACiB;AACjB,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,eAAe,MAAM,OAAO,OAAO;AAAA,IACrC,EAAE,MAAM,UAAU,QAAQ,UAAU;AAAA,IACpC;AAAA,IACA;AAAA,EACJ;AAEA,QAAM,cAAc,MAAM,OAAO,OAAO;AAAA,IACpC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,CAAC,WAAW;AAAA,EAChB;AAEA,SAAO,OAAO,OAAO;AAAA,IACjB;AAAA,MACI,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM,gBAAgB,aAAa,cAAc,IAAI,IAAI;AAAA,MACzD,MAAM,QAAQ,OAAO,IAAI;AAAA,IAC7B;AAAA,IACA;AAAA,IACA,EAAE,MAAM,WAAW,QAAQ,WAAW,oBAAoB;AAAA,IAC1D;AAAA,IACA,CAAC,WAAW,SAAS;AAAA,EACzB;AACJ;AAlCe;",
4
+ "sourcesContent": ["import { webcrypto } from '@substrate-system/one-webcrypto'\nimport { type SupportedEncodings, toString, fromString } from 'uint8arrays'\nimport {\n DEFAULT_ECC_EXCHANGE,\n DEFAULT_ECC_WRITE,\n DEFAULT_SYMM_ALGORITHM,\n SALT_LENGTH,\n IV_LENGTH,\n DEFAULT_SYMM_LENGTH,\n ECC_WRITE_ALGORITHM,\n ECC_EXCHANGE_ALGORITHM,\n X25519_PUBLIC_KEY_LENGTH\n} from '../constants.js'\nimport {\n EccCurve,\n KeyUse,\n type PublicKey,\n type SymmKeyLength,\n type SymmKey,\n type Msg,\n type CharSize,\n type DID,\n type WrappedKey,\n} from '../types.js'\nimport {\n base64ToArrBuf,\n normalizeToBuf,\n toBase64,\n didToPublicKey\n} from '../util.js'\nimport { checkValidKeyUse } from '../errors.js'\nimport { AbstractKeys, type KeyArgs } from '../_base.js'\n\n// Helper function to ensure proper ArrayBuffer type\nfunction toArrayBuffer (data:Uint8Array):ArrayBuffer {\n return new Uint8Array(data).buffer\n}\n\n/**\n * Class for ECC keys\n */\nexport class EccKeys extends AbstractKeys {\n static TYPE:'ecc'|'rsa' = 'ecc' as const\n static EXCHANGE_KEY_NAME:string = DEFAULT_ECC_EXCHANGE\n static WRITE_KEY_NAME:string = DEFAULT_ECC_WRITE\n static INFO = 'keys'\n\n /**\n * Factory function.\n * @param {boolean} [session] Session only? i.e., not saved in indexedDB.\n * Default `false`.\n * @param {boolean} [extractable] Can we extract the private keys? Default\n * `false`.\n * @param {{ exchangeKeys, writeKeys }} [keys] A set of keys to use here.\n * @returns {Promise<EccKeys>} A new class instance.\n */\n static async create<T extends AbstractKeys = EccKeys> (\n session?:boolean,\n extractable?:boolean,\n keys?:{\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n }\n ):Promise<T> {\n return await super.create<T>(session, extractable, keys)\n }\n\n constructor (opts:KeyArgs) {\n super(opts)\n EccKeys.EXCHANGE_KEY_NAME = opts.exchangeKeyName || DEFAULT_ECC_EXCHANGE\n EccKeys.WRITE_KEY_NAME = opts.writeKeyName || DEFAULT_ECC_WRITE\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 exportPublicKey(this.exchangeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(arrayBuffer)\n }\n })\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 exportPublicKey(this.writeKey)\n const uint8Array = new Uint8Array(arrayBuffer)\n return format ? toString(uint8Array, format) : toBase64(arrayBuffer)\n }\n })\n }\n\n static async _createExchangeKeys (\n extractable:boolean = false\n ):Promise<CryptoKeyPair> {\n /**\n * don't use `{ name: ECDH, namedCurve: 'X25519' }`, use\n * `{ name: 'X25519' }`.\n *\n * X25519/Ed25519 don't use `namedCurve`.\n */\n return await webcrypto.subtle.generateKey(\n {\n name: ECC_EXCHANGE_ALGORITHM\n // namedCurve: EccCurve.X25519\n },\n extractable,\n ['deriveKey', 'deriveBits']\n ) as CryptoKeyPair\n }\n\n static async _createWriteKeys (extractable:boolean = false):Promise<CryptoKeyPair> {\n return await webcrypto.subtle.generateKey(\n {\n name: ECC_WRITE_ALGORITHM\n },\n extractable,\n ['sign', 'verify']\n )\n }\n\n /**\n * Restore some keys from indexedDB, or create a new keypair if it doesn't\n * exist yet. Overrides base class to use ECC-specific key names.\n */\n static async load<T extends AbstractKeys = EccKeys> (\n this:typeof EccKeys,\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 as T // cache\n\n // Use ECC-specific key names as defaults\n const exchangeKeyName = opts.encryptionKeyName || DEFAULT_ECC_EXCHANGE\n const writeKeyName = opts.writeKeyName || DEFAULT_ECC_WRITE\n\n return super.load({\n ...opts,\n encryptionKeyName: exchangeKeyName,\n writeKeyName\n }) as Promise<T>\n }\n\n /**\n * Serialize this keys instance. Will return an object of\n * { DID, publicExchangeKey }, where DID is the public write key,\n * and `publicExchangeKey` is the encryption key, `base64` encoded.\n * @returns {Promise<{ DID:DID, publicExchangeKey:string }>}\n */\n async toJson (\n format?:SupportedEncodings\n ):Promise<{ DID:DID; publicExchangeKey:string; }> {\n const did = this.DID\n\n const rawKey = await exportPublicKey(this.exchangeKey)\n\n const keyString = (format ?\n toString(new Uint8Array(rawKey), format) :\n toBase64(rawKey))\n\n return {\n publicExchangeKey: keyString,\n DID: did\n }\n }\n\n /**\n * \"Add a device,\" meaning, take an existing AES key and add the ability\n * for a new keypair to decrypt/use the AES key.\n *\n * This implements HPKE-style key wrapping:\n * 1. Generate ephemeral X25519 keypair\n * 2. Do ECDH with recipient's public key -> shared secret\n * 3. Use HKDF to derive a KEK (key encryption key)\n * 4. AES-GCM encrypt the content\n * 5. Return the ephemeral public key (encapsulation) + wrapped key\n *\n * @param {SymmKey|Uint8Array|string} contentKey The existing AES key used\n * to encrypt the content. Can be a base64 encoded string.\n * @param {CryptoKey} newPublicKey The new device's public X25519 key.\n * @param {string} [info] Optional info parameter for HKDF.\n * Defaults to 'key-wrap'.\n * @returns {Promise<WrappedKey>} The ephemeral public key (base64) and\n * the wrapped AES key (base64).\n */\n async wrap (\n contentKey:SymmKey|Uint8Array|string,\n newPublicKey:CryptoKey, // the new device's public key\n info?:string\n ):Promise<WrappedKey> {\n // 1. Generate ephemeral X25519 keypair\n const ephemeralKeypair = await EccKeys._createExchangeKeys(true)\n\n // 2. Generate random salt for HKDF\n const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH))\n\n // 3. Derive KEK using ECDH + HKDF with ephemeral private key and\n // recipient's public key\n const kek = await deriveKey(\n ephemeralKeypair.privateKey,\n newPublicKey,\n salt,\n info || 'key-wrap'\n )\n\n // 4. Prepare the content key for encryption\n let contentKeyBytes:Uint8Array\n if (contentKey instanceof CryptoKey) {\n // Export the AES key to raw format\n const exported = await crypto.subtle.exportKey('raw', contentKey)\n contentKeyBytes = new Uint8Array(exported)\n } else if (typeof contentKey === 'string') {\n contentKeyBytes = fromString(contentKey, 'base64pad')\n } else {\n contentKeyBytes = contentKey\n }\n\n // 5. Generate IV for AES-GCM encryption\n const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH))\n\n // 6. Encrypt the content key with the KEK\n const wrappedKeyBuffer = await crypto.subtle.encrypt(\n { name: DEFAULT_SYMM_ALGORITHM, iv },\n kek,\n toArrayBuffer(contentKeyBytes)\n )\n\n // 7. Export ephemeral public key\n const ephemeralPubKeyBuffer = await exportPublicKey(ephemeralKeypair)\n\n // 8. Combine salt + iv + wrapped key for the final wrapped key blob\n const saltBuf = new Uint8Array(salt)\n const ivBuf = new Uint8Array(iv)\n const wrappedBuf = new Uint8Array(wrappedKeyBuffer)\n const combinedSize = saltBuf.length + ivBuf.length + wrappedBuf.length\n const combined = new Uint8Array(combinedSize)\n combined.set(saltBuf, 0)\n combined.set(ivBuf, saltBuf.length)\n combined.set(wrappedBuf, saltBuf.length + ivBuf.length)\n\n // 9. Return base64-encoded results\n return {\n enc: toBase64(new Uint8Array(ephemeralPubKeyBuffer)),\n wrappedKey: toBase64(combined)\n }\n }\n\n /**\n * Unwrap a content key that was wrapped for this device using the `add` method.\n *\n * The recipient device uses its private key + the ephemeral public key\n * to rederive the KEK and decrypt the wrapped content key.\n *\n * @param enc The ephemeral public key (base64) from the sender.\n * @param wrappedKey The wrapped content key (base64) - contains salt + iv + ciphertext.\n * @param info Optional info parameter for HKDF. Must match what was used in `add`. Defaults to 'key-wrap'.\n * @returns {Promise<CryptoKey>} The unwrapped AES content key.\n */\n async unwrap (\n enc:string,\n wrappedKey:string,\n info?:string\n ):Promise<CryptoKey> {\n // 1. Import the ephemeral public key\n const ephemeralPubKey = await importPublicKey(\n enc,\n EccCurve.X25519,\n KeyUse.Exchange\n )\n\n // 2. Decode the wrapped key blob and extract salt, iv, and ciphertext\n const wrappedBuf = new Uint8Array(base64ToArrBuf(wrappedKey))\n const salt = wrappedBuf.slice(0, SALT_LENGTH)\n const iv = wrappedBuf.slice(SALT_LENGTH, SALT_LENGTH + IV_LENGTH)\n const ciphertext = wrappedBuf.slice(SALT_LENGTH + IV_LENGTH)\n\n // 3. Derive the same KEK using our private key and the ephemeral public key\n const kek = await deriveKey(\n this.exchangeKey.privateKey,\n ephemeralPubKey,\n salt,\n info || 'key-wrap'\n )\n\n // 4. Decrypt the wrapped key\n const contentKeyBytes = await crypto.subtle.decrypt(\n { name: DEFAULT_SYMM_ALGORITHM, iv },\n kek,\n toArrayBuffer(ciphertext)\n )\n\n // 5. Import the content key back as a CryptoKey\n const contentKey = await crypto.subtle.importKey(\n 'raw',\n contentKeyBytes,\n { name: DEFAULT_SYMM_ALGORITHM },\n true,\n ['encrypt', 'decrypt']\n )\n\n return contentKey\n }\n\n /**\n * Encrypt the given content to the given public key, or encrypt to\n * our own public key if a key is not passed in.\n *\n * This does ECIES style encryption -- a new ephemeral keypair is generated\n * and used to encrypt the message with ephemeral private + recipient public.\n * The public key from the ephemeral keypair is prefixed to the cipher text.\n *\n * @param {string|Uint8Array} content Content to encrypt\n * @param {CryptoKey|string} [recipient] Their public key. Optional b/c we\n * will use our own public key if not passed in. Can be a CryptoKey\n * or a base64 encoded string.\n * @param {string} [info] info tag for HKDF. Default is the class property.\n * @param {SymmKey|Uint8Array|string} [aesKey] This is not relevant for most\n * use cases.\n * @param {SymmKeyLength} [keysize] Default is 256\n * @returns {Promise<ArrayBuffer>} Buffer of ephemeral-public-key + salt +\n * iv + cipher text\n */\n async encrypt (\n content:string|Uint8Array,\n recipient?:CryptoKey|string|null, // their public key\n info?:string|null,\n aesKey?:SymmKey|Uint8Array|string|null,\n keysize?:SymmKeyLength|null\n ):Promise<Uint8Array> {\n const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH))\n\n // publicKey is either passed in or we use our own for note to self\n const _publicKey = (recipient || this.exchangeKey.publicKey)\n let publicKey:CryptoKey\n if (typeof _publicKey === 'string') {\n publicKey = await importPublicKey(\n _publicKey,\n EccCurve.X25519,\n KeyUse.Exchange\n )\n } else {\n publicKey = _publicKey\n }\n\n // ECIES: Generate ephemeral keypair for this encryption\n const ephemeralKeypair = await EccKeys._createExchangeKeys(true)\n\n // key is passed in or derived using ephemeral private key\n let key = aesKey || (await deriveKey(\n ephemeralKeypair.privateKey, // use ephemeral private key\n publicKey,\n salt,\n info || EccKeys.INFO,\n keysize\n ))\n\n // if a key was passed in, but it is not a CryptoKey instance\n if (!(key instanceof CryptoKey)) {\n key = await deriveKey(\n ephemeralKeypair.privateKey, // use ephemeral private key\n publicKey,\n salt,\n info || EccKeys.INFO\n )\n }\n\n const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH))\n const plaintext:Uint8Array = (typeof content === 'string' ?\n new TextEncoder().encode(content) :\n content)\n\n const ciphertext = await crypto.subtle.encrypt(\n { name: DEFAULT_SYMM_ALGORITHM, iv },\n key,\n toArrayBuffer(plaintext)\n )\n\n // Export ephemeral public key to prepend to ciphertext\n const ephemeralPubKeyBuf = new Uint8Array(\n await exportPublicKey(ephemeralKeypair)\n )\n\n // Prepend ephemeral public key, salt and IV to the ciphertext\n const saltBuffer = new Uint8Array(salt)\n const ivBuffer = new Uint8Array(iv)\n const cipherBuf = new Uint8Array(ciphertext)\n const size = ephemeralPubKeyBuf.length + saltBuffer.length +\n ivBuffer.length + cipherBuf.length\n const result = new Uint8Array(size)\n result.set(ephemeralPubKeyBuf, 0)\n result.set(saltBuffer, ephemeralPubKeyBuf.length)\n result.set(ivBuffer, ephemeralPubKeyBuf.length + saltBuffer.length)\n result.set(cipherBuf, ephemeralPubKeyBuf.length + saltBuffer.length +\n ivBuffer.length)\n\n return result\n }\n\n /**\n * Encrypt and return as base64 string.\n */\n async encryptAsString (\n content:string|Uint8Array,\n recipient?:CryptoKey|string|null, // their public key\n info?:string|null,\n aesKey?:SymmKey|Uint8Array|string|null,\n keysize?:SymmKeyLength|null,\n ):Promise<string> {\n const encrypted = await this.encrypt(\n content,\n recipient,\n info || EccKeys.INFO,\n aesKey,\n keysize\n )\n\n return toString(new Uint8Array(encrypted), 'base64pad')\n }\n\n /**\n * Decrypt the given message. The encrypted message should be\n * ephemeral public key + salt + iv + cipher text.\n *\n * The ephemeral public key is extracted from the beginning of the message\n * and used with our private key to derive the AES decryption key.\n *\n * @param msg The encrypted content\n * @param {string} aesAlgorithm The algorithm. Default is AES-GCM.\n * @param {string} info Custom \"info\" parameter\n * @returns {Promise<ArrayBuffer>} The decrypted content.\n */\n async decrypt (\n msg:string|Uint8Array|ArrayBuffer,\n aesAlgorithm?:string|null,\n info?:string|null,\n ):Promise<ArrayBuffer|Uint8Array> {\n // ECIES: Extract ephemeral public key from the beginning of the message\n const encrypted = normalizeToBuf(msg, base64ToArrBuf)\n const ephemeralPubKeyBuf = encrypted.slice(0, X25519_PUBLIC_KEY_LENGTH)\n\n // ephemeral public key should be prepended to the data\n const ephemeralPublicKey = await webcrypto.subtle.importKey(\n 'raw',\n ephemeralPubKeyBuf,\n { name: ECC_EXCHANGE_ALGORITHM },\n true,\n []\n )\n\n // Extract salt, iv, and ciphertext after the ephemeral public key\n const salt = encrypted.slice(\n X25519_PUBLIC_KEY_LENGTH,\n X25519_PUBLIC_KEY_LENGTH + SALT_LENGTH\n )\n const iv = encrypted.slice(\n X25519_PUBLIC_KEY_LENGTH + SALT_LENGTH,\n X25519_PUBLIC_KEY_LENGTH + SALT_LENGTH + IV_LENGTH\n )\n const ciphertext = encrypted.slice(\n X25519_PUBLIC_KEY_LENGTH + SALT_LENGTH + IV_LENGTH\n )\n\n // Derive an AES key with our private key + ephemeral-public-key\n const { privateKey } = this.exchangeKey\n const key = await deriveKey(\n privateKey,\n ephemeralPublicKey,\n salt,\n info || EccKeys.INFO\n )\n\n // we have the key, now decrypt the message\n const decrypted = await crypto.subtle.decrypt(\n {\n name: aesAlgorithm || DEFAULT_SYMM_ALGORITHM,\n iv,\n },\n key,\n ciphertext\n )\n\n return decrypted\n }\n\n /**\n * Decrypt and return as string using ECIES. The encrypted message should be\n * ephemeral public key + salt + iv + cipher text.\n *\n * The ephemeral public key is extracted from the beginning of the message\n * and used with our private key to derive the AES decryption key.\n *\n * @param msg The encrypted content\n * @param {string} aesAlgorithm The algorithm. Default is AES-GCM.\n * @param {string} info Custom \"info\" parameter\n * @returns {Promise<string>} The decrypted content as a string.\n */\n async decryptAsString (\n msg:string|Uint8Array|ArrayBuffer,\n aesAlgorithm?:string|null,\n info?:string|null,\n ):Promise<string> {\n const dec = await this.decrypt(msg, aesAlgorithm, info)\n return toString(new Uint8Array(dec))\n }\n\n /**\n * Do DHKE, create a new AES-GCM key.\n *\n * @param {CryptoKey|string|null} [publicKey] Public key to use in DHKE.\n * Will use our public key if it is not passed in.\n * @param {string} info The info parameter for DHKE. Will use the class\n * property `INFO` if it is not passed in.\n * @returns {CryptoKey} New AES key\n */\n async getAesKey (\n publicKey?:CryptoKey|string|null,\n info?:string|null,\n ):Promise<CryptoKey> {\n if (!publicKey) {\n publicKey = this.publicExchangeKey\n }\n\n let pub:CryptoKey\n if (typeof publicKey === 'string') {\n pub = await importPublicKey(\n publicKey,\n EccCurve.X25519,\n KeyUse.Exchange\n )\n } else {\n pub = publicKey\n }\n\n // Generate a random salt for HKDF\n const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH))\n\n // Derive AES key using ECDH + HKDF\n const aesKey = await deriveKey(\n this.exchangeKey.privateKey,\n pub,\n salt,\n info || EccKeys.INFO\n )\n\n return aesKey\n }\n\n /**\n * Sign the given content using our private write key.\n */\n async sign (msg:Msg, _charsize?:CharSize):Promise<Uint8Array> {\n const encoder = new TextEncoder()\n let data:Uint8Array\n\n if (typeof msg === 'string') {\n data = encoder.encode(msg)\n } else if (msg instanceof ArrayBuffer) {\n data = new Uint8Array(msg)\n } else {\n data = msg\n }\n\n const signature = await webcrypto.subtle.sign(\n { name: ECC_WRITE_ALGORITHM },\n this.writeKey.privateKey,\n toArrayBuffer(data)\n )\n\n return new Uint8Array(signature)\n }\n\n /**\n * Sign the given content and return as base64 string.\n */\n async signAsString (msg:string, _charsize?:CharSize):Promise<string> {\n const signature = await this.sign(msg, _charsize)\n return toString(signature, 'base64pad')\n }\n}\n\n// Attach asString to the prototype method for backward compatibility\nObject.assign(EccKeys.prototype.sign, {\n asString: async function (\n this:EccKeys,\n msg:string,\n _charsize?:CharSize\n ):Promise<string> {\n const signature = await this.sign(msg, _charsize)\n return toString(signature, 'base64pad')\n }\n})\n\n/**\n * Get the public key from a given keypair.\n *\n * @param {CryptoKeyPair} keypair The keypair to get the public side from.\n * @returns {Promise<ArrayBuffer>} ArrayBuffer of public key material\n */\nexport async function exportPublicKey(\n keypair:CryptoKeyPair,\n format:'jwk'\n):Promise<JsonWebKey>\n\nexport async function exportPublicKey(\n keypair:CryptoKeyPair,\n format?:'raw'|'spki'|'pkcs8'\n):Promise<ArrayBuffer>\n\nexport async function exportPublicKey (\n keypair:CryptoKeyPair,\n format:KeyFormat = 'raw'\n):Promise<JsonWebKey|ArrayBuffer> {\n return await crypto.subtle.exportKey(format, keypair.publicKey)\n}\n\nexport async function importPublicKey (\n base64Key:string,\n curve:EccCurve,\n use:KeyUse\n):Promise<PublicKey> {\n checkValidKeyUse(use)\n const alg = use === KeyUse.Exchange ? ECC_EXCHANGE_ALGORITHM : ECC_WRITE_ALGORITHM\n const uses:KeyUsage[] = use === KeyUse.Exchange ? [] : ['verify']\n const buf = base64ToArrBuf(base64Key)\n\n // X25519 doesn't use namedCurve in the algorithm parameter\n const algorithm = (curve === EccCurve.X25519) ?\n { name: alg } :\n { name: alg, namedCurve: curve }\n\n return webcrypto.subtle.importKey(\n 'raw',\n buf,\n algorithm,\n true,\n uses\n )\n}\n\nexport default {\n EccKeys,\n importPublicKey\n}\n\n// Add backward compatibility by attaching asString methods to prototypes\nObject.assign(EccKeys.prototype.encrypt, {\n asString: async function (\n this: EccKeys,\n content: string | Uint8Array,\n recipient?: CryptoKey | string,\n info?: string,\n aesKey?: SymmKey | Uint8Array | string,\n keysize?: SymmKeyLength\n ): Promise<string> {\n return this.encryptAsString(content, recipient, info, aesKey, keysize)\n }\n})\n\nObject.assign(EccKeys.prototype.decrypt, {\n asString: async function (\n this: EccKeys,\n msg: string | Uint8Array | ArrayBuffer,\n aesAlgorithm?: string\n ): Promise<string> {\n return this.decryptAsString(msg, aesAlgorithm)\n }\n})\n\nObject.assign(EccKeys.prototype.sign, {\n asString: async function (\n this: EccKeys,\n msg: string,\n _charsize?: CharSize\n ): Promise<string> {\n return this.signAsString(msg, _charsize)\n }\n})\n\n/**\n * Check that the given signature is valid with the given message.\n * This uses Ed25519 verification.\n */\nexport async function verify (\n msg:string|Uint8Array,\n sig:string|Uint8Array,\n signingDid:DID\n):Promise<boolean> {\n try {\n const _key = didToPublicKey(signingDid)\n\n // Verify it's an Ed25519 key\n if (_key.type !== 'ed25519') {\n throw new Error(`Expected Ed25519 key for ECC verification, got ${_key.type}`)\n }\n\n // Extract raw Ed25519 key from DER encoding\n // DER format has 12-byte header, then 32-byte raw key\n const rawKeyBytes = _key.publicKey.slice(-32)\n\n // Import the public key for verification\n const publicKey = await webcrypto.subtle.importKey(\n 'raw',\n rawKeyBytes,\n { name: ECC_WRITE_ALGORITHM },\n true,\n ['verify']\n )\n\n // Prepare the message using the same encoding as the sign function\n const encoder = new TextEncoder()\n let data:Uint8Array\n\n if (typeof msg === 'string') {\n data = encoder.encode(msg)\n } else if (msg instanceof ArrayBuffer) {\n data = new Uint8Array(msg)\n } else {\n data = msg\n }\n\n // Prepare the signature - handle both string and Uint8Array\n let signature:Uint8Array\n if (typeof sig === 'string') {\n signature = new Uint8Array(base64ToArrBuf(sig))\n } else {\n signature = sig\n }\n\n // Verify the signature\n const isValid = await webcrypto.subtle.verify(\n { name: ECC_WRITE_ALGORITHM },\n publicKey,\n toArrayBuffer(signature),\n toArrayBuffer(data)\n )\n\n return isValid\n } catch (_err) {\n return false\n }\n}\n\n/**\n * Derive an AES key from X25519 keypair via ECDH + HKDF\n */\nasync function deriveKey (\n privateKey:CryptoKey,\n publicKey:CryptoKey,\n salt:Uint8Array|ArrayBuffer,\n info:string,\n keysize?:number|null\n):Promise<CryptoKey> {\n const encoder = new TextEncoder()\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'X25519', public: publicKey },\n privateKey,\n 256\n )\n\n const hkdfBaseKey = await crypto.subtle.importKey(\n 'raw',\n sharedSecret,\n 'HKDF',\n false,\n ['deriveKey']\n )\n\n return crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: salt instanceof Uint8Array ? toArrayBuffer(salt) : salt,\n info: encoder.encode(info)\n },\n hkdfBaseKey,\n { name: 'AES-GCM', length: keysize || DEFAULT_SYMM_LENGTH },\n false,\n ['encrypt', 'decrypt']\n )\n}\n"],
5
+ "mappings": ";;;;AAAA,SAAS,iBAAiB;AAC1B,SAAkC,UAAU,kBAAkB;AAC9D;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP;AAAA,EACI;AAAA,EACA;AAAA,OAQG;AACP;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,wBAAwB;AACjC,SAAS,oBAAkC;AAG3C,SAAS,cAAe,MAA6B;AACjD,SAAO,IAAI,WAAW,IAAI,EAAE;AAChC;AAFS;AAOF,MAAM,WAAN,MAAM,iBAAgB,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAetC,aAAa,OACT,SACA,aACA,MAIS;AACT,WAAO,MAAM,MAAM,OAAU,SAAS,aAAa,IAAI;AAAA,EAC3D;AAAA,EAEA,YAAa,MAAc;AACvB,UAAM,IAAI;AACV,aAAQ,oBAAoB,KAAK,mBAAmB;AACpD,aAAQ,iBAAiB,KAAK,gBAAgB;AAAA,EAClD;AAAA,EAEA,IAAI,oBAAqB;AACrB,UAAM,YAAY,KAAK,YAAY;AACnC,WAAO,OAAO,OAAO,WAAW;AAAA,MAC5B,UAAU,8BAAO,WAAiD;AAC9D,cAAM,cAAc,MAAM,gBAAgB,KAAK,WAAW;AAC1D,cAAM,aAAa,IAAI,WAAW,WAAW;AAC7C,eAAO,SAAS,SAAS,YAAY,MAAM,IAAI,SAAS,WAAW;AAAA,MACvE,GAJU;AAAA,IAKd,CAAC;AAAA,EACL;AAAA,EAEA,IAAI,iBAAkB;AAClB,UAAM,YAAY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,WAAW,SAAS;AAAA,EACzB;AACJ;AAlCe;",
6
6
  "names": []
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var P=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var M=(s,e,t)=>e in s?P(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var u=(s,e)=>P(s,"name",{value:e,configurable:!0});var F=(s,e)=>{for(var t in e)P(s,t,{get:e[t],enumerable:!0})},H=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of L(e))!O.call(s,i)&&i!==t&&P(s,i,{get:()=>e[i],enumerable:!(r=_(e,i))||r.enumerable});return s};var R=s=>H(P({},"__esModule",{value:!0}),s);var S=(s,e,t)=>M(s,typeof e!="symbol"?e+"":e,t);var X={};F(X,{EccKeys:()=>h,default:()=>G,exportPublicKey:()=>B,importPublicKey:()=>C,verify:()=>W});module.exports=R(X);var b=require("@substrate-system/one-webcrypto"),A=require("uint8arrays"),n=require("../constants.js"),K=require("../types.js"),o=require("../util.js"),k=require("../errors.js"),I=require("../_base.js");function d(s){return new Uint8Array(s).buffer}u(d,"toArrayBuffer");const p=class p extends I.AbstractKeys{static async create(e,t,r){return await super.create(e,t,r)}constructor(e){super(e),p.EXCHANGE_KEY_NAME=e.exchangeKeyName||n.DEFAULT_ECC_EXCHANGE,p.WRITE_KEY_NAME=e.writeKeyName||n.DEFAULT_ECC_WRITE}get publicExchangeKey(){const e=this.exchangeKey.publicKey;return Object.assign(e,{asString:u(async t=>{const r=await B(this.exchangeKey),i=new Uint8Array(r);return t?(0,A.toString)(i,t):(0,o.toBase64)(r)},"asString")})}get publicWriteKey(){const e=this.writeKey.publicKey;return Object.assign(e,{asString:u(async t=>{const r=await B(this.writeKey),i=new Uint8Array(r);return t?(0,A.toString)(i,t):(0,o.toBase64)(r)},"asString")})}static async _createExchangeKeys(e=!1){return await b.webcrypto.subtle.generateKey({name:n.ECC_EXCHANGE_ALGORITHM},e,["deriveKey","deriveBits"])}static async _createWriteKeys(e=!1){return await b.webcrypto.subtle.generateKey({name:n.ECC_WRITE_ALGORITHM},e,["sign","verify"])}static async load(e={session:!1}){if(this._instance)return this._instance;const t=e.encryptionKeyName||n.DEFAULT_ECC_EXCHANGE,r=e.writeKeyName||n.DEFAULT_ECC_WRITE;return super.load({...e,encryptionKeyName:t,writeKeyName:r})}async toJson(e){const t=this.DID,r=await B(this.exchangeKey);return{publicExchangeKey:e?(0,A.toString)(new Uint8Array(r),e):(0,o.toBase64)(r),DID:t}}async wrap(e,t,r){const i=await p._createExchangeKeys(!0),a=crypto.getRandomValues(new Uint8Array(n.SALT_LENGTH)),c=await x(i.privateKey,t,a,r||"key-wrap");let y;if(e instanceof CryptoKey){const v=await crypto.subtle.exportKey("raw",e);y=new Uint8Array(v)}else typeof e=="string"?y=new Uint8Array((0,o.base64ToArrBuf)(e)):y=e;const g=crypto.getRandomValues(new Uint8Array(n.IV_LENGTH)),l=await crypto.subtle.encrypt({name:n.DEFAULT_SYMM_ALGORITHM,iv:g},c,d(y)),m=await B(i),f=new Uint8Array(a),E=new Uint8Array(g),T=new Uint8Array(l),U=f.length+E.length+T.length,w=new Uint8Array(U);return w.set(f,0),w.set(E,f.length),w.set(T,f.length+E.length),{enc:(0,o.toBase64)(new Uint8Array(m)),wrappedKey:(0,o.toBase64)(w)}}async unwrap(e,t,r){const i=await C(e,K.EccCurve.X25519,K.KeyUse.Exchange),a=new Uint8Array((0,o.base64ToArrBuf)(t)),c=a.slice(0,n.SALT_LENGTH),y=a.slice(n.SALT_LENGTH,n.SALT_LENGTH+n.IV_LENGTH),g=a.slice(n.SALT_LENGTH+n.IV_LENGTH),l=await x(this.exchangeKey.privateKey,i,c,r||"key-wrap"),m=await crypto.subtle.decrypt({name:n.DEFAULT_SYMM_ALGORITHM,iv:y},l,d(g));return await crypto.subtle.importKey("raw",m,{name:n.DEFAULT_SYMM_ALGORITHM},!0,["encrypt","decrypt"])}async encrypt(e,t,r,i,a){const c=new TextEncoder,y=crypto.getRandomValues(new Uint8Array(n.SALT_LENGTH)),g=t||this.exchangeKey.publicKey;let l;typeof g=="string"?l=await C(g,K.EccCurve.X25519,K.KeyUse.Exchange):l=g;let m=i||await x(this.exchangeKey.privateKey,l,y,r||p.INFO,a);m instanceof CryptoKey||(m=await x(this.exchangeKey.privateKey,l,y,r||p.INFO));const f=crypto.getRandomValues(new Uint8Array(n.IV_LENGTH)),E=typeof e=="string"?c.encode(e):e,T=await crypto.subtle.encrypt({name:n.DEFAULT_SYMM_ALGORITHM,iv:f},m,d(E)),U=new Uint8Array(y),w=new Uint8Array(f),v=new Uint8Array(T),D=U.length+w.length+v.length,N=new Uint8Array(D);return N.set(U,0),N.set(w,U.length),N.set(v,U.length+w.length),N}async encryptAsString(e,t,r,i,a){const c=await this.encrypt(e,t,r||p.INFO,i,a);return(0,A.toString)(new Uint8Array(c),"base64pad")}async decrypt(e,t,r,i){let a=typeof t=="string"?await C(t,K.EccCurve.X25519,K.KeyUse.Write):t;a||(a=this.publicExchangeKey);const c=(0,o.normalizeToBuf)(e,o.base64ToArrBuf),y=c.slice(0,n.SALT_LENGTH),g=c.slice(n.SALT_LENGTH,n.SALT_LENGTH+n.IV_LENGTH),l=c.slice(n.SALT_LENGTH+n.IV_LENGTH),{privateKey:m}=this.exchangeKey,f=await x(m,a,y,i||p.INFO);return await crypto.subtle.decrypt({name:r||n.DEFAULT_SYMM_ALGORITHM,iv:g},f,l)}async decryptAsString(e,t,r,i){const a=await this.decrypt(e,t,r,i);return(0,A.toString)(new Uint8Array(a))}async getAesKey(e,t){e||(e=this.publicExchangeKey);let r;typeof e=="string"?r=await C(e,K.EccCurve.X25519,K.KeyUse.Exchange):r=e;const i=crypto.getRandomValues(new Uint8Array(n.SALT_LENGTH));return await x(this.exchangeKey.privateKey,r,i,t||p.INFO)}async sign(e,t){const r=new TextEncoder;let i;typeof e=="string"?i=r.encode(e):e instanceof ArrayBuffer?i=new Uint8Array(e):i=e;const a=await b.webcrypto.subtle.sign({name:n.ECC_WRITE_ALGORITHM},this.writeKey.privateKey,d(i));return new Uint8Array(a)}async signAsString(e,t){const r=await this.sign(e,t);return(0,A.toString)(r,"base64pad")}};u(p,"EccKeys"),S(p,"TYPE","ecc"),S(p,"EXCHANGE_KEY_NAME",n.DEFAULT_ECC_EXCHANGE),S(p,"WRITE_KEY_NAME",n.DEFAULT_ECC_WRITE),S(p,"INFO","keys");let h=p;Object.assign(h.prototype.sign,{asString:u(async function(s,e){const t=await this.sign(s,e);return(0,A.toString)(t,"base64pad")},"asString")});async function B(s,e="raw"){return await crypto.subtle.exportKey(e,s.publicKey)}u(B,"exportPublicKey");async function C(s,e,t){(0,k.checkValidKeyUse)(t);const r=t===K.KeyUse.Exchange?n.ECC_EXCHANGE_ALGORITHM:n.ECC_WRITE_ALGORITHM,i=t===K.KeyUse.Exchange?[]:["verify"],a=(0,o.base64ToArrBuf)(s),c=e===K.EccCurve.X25519?{name:r}:{name:r,namedCurve:e};return b.webcrypto.subtle.importKey("raw",a,c,!0,i)}u(C,"importPublicKey");var G={EccKeys:h,importPublicKey:C};Object.assign(h.prototype.encrypt,{asString:u(async function(s,e,t,r,i){return this.encryptAsString(s,e,t,r,i)},"asString")}),Object.assign(h.prototype.decrypt,{asString:u(async function(s,e,t){return this.decryptAsString(s,e,t)},"asString")}),Object.assign(h.prototype.sign,{asString:u(async function(s,e){return this.signAsString(s,e)},"asString")});async function W(s,e,t){try{const r=(0,o.didToPublicKey)(t);if(r.type!=="ed25519")throw new Error(`Expected Ed25519 key for ECC verification, got ${r.type}`);const i=r.publicKey.slice(-32),a=await b.webcrypto.subtle.importKey("raw",i,{name:n.ECC_WRITE_ALGORITHM},!0,["verify"]),c=new TextEncoder;let y;typeof s=="string"?y=c.encode(s):s instanceof ArrayBuffer?y=new Uint8Array(s):y=s;let g;return typeof e=="string"?g=new Uint8Array((0,o.base64ToArrBuf)(e)):g=e,await b.webcrypto.subtle.verify({name:n.ECC_WRITE_ALGORITHM},a,d(g),d(y))}catch{return!1}}u(W,"verify");async function x(s,e,t,r,i){const a=new TextEncoder,c=await crypto.subtle.deriveBits({name:"X25519",public:e},s,256),y=await crypto.subtle.importKey("raw",c,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:t instanceof Uint8Array?d(t):t,info:a.encode(r)},y,{name:"AES-GCM",length:i||n.DEFAULT_SYMM_LENGTH},!1,["encrypt","decrypt"])}u(x,"deriveKey");
1
+ "use strict";var B=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var M=(a,e,t)=>e in a?B(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var u=(a,e)=>B(a,"name",{value:e,configurable:!0});var F=(a,e)=>{for(var t in e)B(a,t,{get:e[t],enumerable:!0})},G=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of O(e))!H.call(a,i)&&i!==t&&B(a,i,{get:()=>e[i],enumerable:!(n=L(e,i))||n.enumerable});return a};var R=a=>G(B({},"__esModule",{value:!0}),a);var T=(a,e,t)=>M(a,typeof e!="symbol"?e+"":e,t);var z={};F(z,{EccKeys:()=>d,default:()=>W,exportPublicKey:()=>x,importPublicKey:()=>v,verify:()=>X});module.exports=R(z);var A=require("@substrate-system/one-webcrypto"),m=require("uint8arrays"),r=require("../constants.js"),g=require("../types.js"),l=require("../util.js"),_=require("../errors.js"),k=require("../_base.js");function E(a){return new Uint8Array(a).buffer}u(E,"toArrayBuffer");const o=class o extends k.AbstractKeys{static async create(e,t,n){return await super.create(e,t,n)}constructor(e){super(e),o.EXCHANGE_KEY_NAME=e.exchangeKeyName||r.DEFAULT_ECC_EXCHANGE,o.WRITE_KEY_NAME=e.writeKeyName||r.DEFAULT_ECC_WRITE}get publicExchangeKey(){const e=this.exchangeKey.publicKey;return Object.assign(e,{asString:u(async t=>{const n=await x(this.exchangeKey),i=new Uint8Array(n);return t?(0,m.toString)(i,t):(0,l.toBase64)(n)},"asString")})}get publicWriteKey(){const e=this.writeKey.publicKey;return Object.assign(e,{asString:u(async t=>{const n=await x(this.writeKey),i=new Uint8Array(n);return t?(0,m.toString)(i,t):(0,l.toBase64)(n)},"asString")})}static async _createExchangeKeys(e=!1){return await A.webcrypto.subtle.generateKey({name:r.ECC_EXCHANGE_ALGORITHM},e,["deriveKey","deriveBits"])}static async _createWriteKeys(e=!1){return await A.webcrypto.subtle.generateKey({name:r.ECC_WRITE_ALGORITHM},e,["sign","verify"])}static async load(e={session:!1}){if(this._instance)return this._instance;const t=e.encryptionKeyName||r.DEFAULT_ECC_EXCHANGE,n=e.writeKeyName||r.DEFAULT_ECC_WRITE;return super.load({...e,encryptionKeyName:t,writeKeyName:n})}async toJson(e){const t=this.DID,n=await x(this.exchangeKey);return{publicExchangeKey:e?(0,m.toString)(new Uint8Array(n),e):(0,l.toBase64)(n),DID:t}}async wrap(e,t,n){const i=await o._createExchangeKeys(!0),s=crypto.getRandomValues(new Uint8Array(r.SALT_LENGTH)),c=await P(i.privateKey,t,s,n||"key-wrap");let y;if(e instanceof CryptoKey){const C=await crypto.subtle.exportKey("raw",e);y=new Uint8Array(C)}else typeof e=="string"?y=(0,m.fromString)(e,"base64pad"):y=e;const p=crypto.getRandomValues(new Uint8Array(r.IV_LENGTH)),K=await crypto.subtle.encrypt({name:r.DEFAULT_SYMM_ALGORITHM,iv:p},c,E(y)),w=await x(i),f=new Uint8Array(s),U=new Uint8Array(p),N=new Uint8Array(K),b=f.length+U.length+N.length,h=new Uint8Array(b);return h.set(f,0),h.set(U,f.length),h.set(N,f.length+U.length),{enc:(0,l.toBase64)(new Uint8Array(w)),wrappedKey:(0,l.toBase64)(h)}}async unwrap(e,t,n){const i=await v(e,g.EccCurve.X25519,g.KeyUse.Exchange),s=new Uint8Array((0,l.base64ToArrBuf)(t)),c=s.slice(0,r.SALT_LENGTH),y=s.slice(r.SALT_LENGTH,r.SALT_LENGTH+r.IV_LENGTH),p=s.slice(r.SALT_LENGTH+r.IV_LENGTH),K=await P(this.exchangeKey.privateKey,i,c,n||"key-wrap"),w=await crypto.subtle.decrypt({name:r.DEFAULT_SYMM_ALGORITHM,iv:y},K,E(p));return await crypto.subtle.importKey("raw",w,{name:r.DEFAULT_SYMM_ALGORITHM},!0,["encrypt","decrypt"])}async encrypt(e,t,n,i,s){const c=crypto.getRandomValues(new Uint8Array(r.SALT_LENGTH)),y=t||this.exchangeKey.publicKey;let p;typeof y=="string"?p=await v(y,g.EccCurve.X25519,g.KeyUse.Exchange):p=y;const K=await o._createExchangeKeys(!0);let w=i||await P(K.privateKey,p,c,n||o.INFO,s);w instanceof CryptoKey||(w=await P(K.privateKey,p,c,n||o.INFO));const f=crypto.getRandomValues(new Uint8Array(r.IV_LENGTH)),U=typeof e=="string"?new TextEncoder().encode(e):e,N=await crypto.subtle.encrypt({name:r.DEFAULT_SYMM_ALGORITHM,iv:f},w,E(U)),b=new Uint8Array(await x(K)),h=new Uint8Array(c),C=new Uint8Array(f),I=new Uint8Array(N),D=b.length+h.length+C.length+I.length,S=new Uint8Array(D);return S.set(b,0),S.set(h,b.length),S.set(C,b.length+h.length),S.set(I,b.length+h.length+C.length),S}async encryptAsString(e,t,n,i,s){const c=await this.encrypt(e,t,n||o.INFO,i,s);return(0,m.toString)(new Uint8Array(c),"base64pad")}async decrypt(e,t,n){const i=(0,l.normalizeToBuf)(e,l.base64ToArrBuf),s=i.slice(0,r.X25519_PUBLIC_KEY_LENGTH),c=await A.webcrypto.subtle.importKey("raw",s,{name:r.ECC_EXCHANGE_ALGORITHM},!0,[]),y=i.slice(r.X25519_PUBLIC_KEY_LENGTH,r.X25519_PUBLIC_KEY_LENGTH+r.SALT_LENGTH),p=i.slice(r.X25519_PUBLIC_KEY_LENGTH+r.SALT_LENGTH,r.X25519_PUBLIC_KEY_LENGTH+r.SALT_LENGTH+r.IV_LENGTH),K=i.slice(r.X25519_PUBLIC_KEY_LENGTH+r.SALT_LENGTH+r.IV_LENGTH),{privateKey:w}=this.exchangeKey,f=await P(w,c,y,n||o.INFO);return await crypto.subtle.decrypt({name:t||r.DEFAULT_SYMM_ALGORITHM,iv:p},f,K)}async decryptAsString(e,t,n){const i=await this.decrypt(e,t,n);return(0,m.toString)(new Uint8Array(i))}async getAesKey(e,t){e||(e=this.publicExchangeKey);let n;typeof e=="string"?n=await v(e,g.EccCurve.X25519,g.KeyUse.Exchange):n=e;const i=crypto.getRandomValues(new Uint8Array(r.SALT_LENGTH));return await P(this.exchangeKey.privateKey,n,i,t||o.INFO)}async sign(e,t){const n=new TextEncoder;let i;typeof e=="string"?i=n.encode(e):e instanceof ArrayBuffer?i=new Uint8Array(e):i=e;const s=await A.webcrypto.subtle.sign({name:r.ECC_WRITE_ALGORITHM},this.writeKey.privateKey,E(i));return new Uint8Array(s)}async signAsString(e,t){const n=await this.sign(e,t);return(0,m.toString)(n,"base64pad")}};u(o,"EccKeys"),T(o,"TYPE","ecc"),T(o,"EXCHANGE_KEY_NAME",r.DEFAULT_ECC_EXCHANGE),T(o,"WRITE_KEY_NAME",r.DEFAULT_ECC_WRITE),T(o,"INFO","keys");let d=o;Object.assign(d.prototype.sign,{asString:u(async function(a,e){const t=await this.sign(a,e);return(0,m.toString)(t,"base64pad")},"asString")});async function x(a,e="raw"){return await crypto.subtle.exportKey(e,a.publicKey)}u(x,"exportPublicKey");async function v(a,e,t){(0,_.checkValidKeyUse)(t);const n=t===g.KeyUse.Exchange?r.ECC_EXCHANGE_ALGORITHM:r.ECC_WRITE_ALGORITHM,i=t===g.KeyUse.Exchange?[]:["verify"],s=(0,l.base64ToArrBuf)(a),c=e===g.EccCurve.X25519?{name:n}:{name:n,namedCurve:e};return A.webcrypto.subtle.importKey("raw",s,c,!0,i)}u(v,"importPublicKey");var W={EccKeys:d,importPublicKey:v};Object.assign(d.prototype.encrypt,{asString:u(async function(a,e,t,n,i){return this.encryptAsString(a,e,t,n,i)},"asString")}),Object.assign(d.prototype.decrypt,{asString:u(async function(a,e){return this.decryptAsString(a,e)},"asString")}),Object.assign(d.prototype.sign,{asString:u(async function(a,e){return this.signAsString(a,e)},"asString")});async function X(a,e,t){try{const n=(0,l.didToPublicKey)(t);if(n.type!=="ed25519")throw new Error(`Expected Ed25519 key for ECC verification, got ${n.type}`);const i=n.publicKey.slice(-32),s=await A.webcrypto.subtle.importKey("raw",i,{name:r.ECC_WRITE_ALGORITHM},!0,["verify"]),c=new TextEncoder;let y;typeof a=="string"?y=c.encode(a):a instanceof ArrayBuffer?y=new Uint8Array(a):y=a;let p;return typeof e=="string"?p=new Uint8Array((0,l.base64ToArrBuf)(e)):p=e,await A.webcrypto.subtle.verify({name:r.ECC_WRITE_ALGORITHM},s,E(p),E(y))}catch{return!1}}u(X,"verify");async function P(a,e,t,n,i){const s=new TextEncoder,c=await crypto.subtle.deriveBits({name:"X25519",public:e},a,256),y=await crypto.subtle.importKey("raw",c,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:t instanceof Uint8Array?E(t):t,info:s.encode(n)},y,{name:"AES-GCM",length:i||r.DEFAULT_SYMM_LENGTH},!1,["encrypt","decrypt"])}u(P,"deriveKey");
2
2
  //# sourceMappingURL=index.min.cjs.map