@substrate-system/keys 0.2.34 → 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.
Files changed (50) hide show
  1. package/README.md +131 -13
  2. package/dist/_base.min.js +2 -2
  3. package/dist/_base.min.js.map +3 -3
  4. package/dist/aes/index.min.js +2 -2
  5. package/dist/aes/index.min.js.map +3 -3
  6. package/dist/browser/index.js +107 -15
  7. package/dist/browser/index.min.js +2 -2
  8. package/dist/constants.cjs +4 -8
  9. package/dist/constants.cjs.map +2 -2
  10. package/dist/constants.d.ts +2 -4
  11. package/dist/constants.d.ts.map +1 -1
  12. package/dist/constants.js +4 -8
  13. package/dist/constants.js.map +2 -2
  14. package/dist/constants.min.cjs +1 -1
  15. package/dist/constants.min.cjs.map +3 -3
  16. package/dist/constants.min.js +1 -1
  17. package/dist/constants.min.js.map +3 -3
  18. package/dist/crypto.min.js +2 -2
  19. package/dist/crypto.min.js.map +3 -3
  20. package/dist/ecc/index.cjs +103 -7
  21. package/dist/ecc/index.cjs.map +2 -2
  22. package/dist/ecc/index.d.ts +34 -3
  23. package/dist/ecc/index.d.ts.map +1 -1
  24. package/dist/ecc/index.js +105 -11
  25. package/dist/ecc/index.js.map +2 -2
  26. package/dist/ecc/index.min.cjs +1 -1
  27. package/dist/ecc/index.min.cjs.map +3 -3
  28. package/dist/ecc/index.min.js +2 -2
  29. package/dist/ecc/index.min.js.map +3 -3
  30. package/dist/errors.min.js +1 -1
  31. package/dist/index.min.js +2 -2
  32. package/dist/index.min.js.map +3 -3
  33. package/dist/meta.json +14 -16
  34. package/dist/rsa/index.cjs.map +2 -2
  35. package/dist/rsa/index.d.ts.map +1 -1
  36. package/dist/rsa/index.js.map +2 -2
  37. package/dist/rsa/index.min.cjs.map +2 -2
  38. package/dist/rsa/index.min.js +2 -2
  39. package/dist/rsa/index.min.js.map +3 -3
  40. package/dist/types.cjs.map +2 -2
  41. package/dist/types.d.ts +10 -0
  42. package/dist/types.d.ts.map +1 -1
  43. package/dist/types.js.map +2 -2
  44. package/dist/types.min.cjs +1 -1
  45. package/dist/types.min.cjs.map +2 -2
  46. package/dist/types.min.js +1 -1
  47. package/dist/types.min.js.map +2 -2
  48. package/dist/util.min.js +1 -1
  49. package/dist/util.min.js.map +3 -3
  50. package/package.json +4 -10
@@ -80,7 +80,7 @@ const _EccKeys = class _EccKeys extends import_base.AbstractKeys {
80
80
  static async _createExchangeKeys(extractable = false) {
81
81
  return await import_one_webcrypto.webcrypto.subtle.generateKey(
82
82
  {
83
- name: import_constants.ECC_EXCHANGE_NAME
83
+ name: import_constants.ECC_EXCHANGE_ALGORITHM
84
84
  // namedCurve: EccCurve.X25519
85
85
  },
86
86
  extractable,
@@ -90,7 +90,7 @@ const _EccKeys = class _EccKeys extends import_base.AbstractKeys {
90
90
  static async _createWriteKeys(extractable = false) {
91
91
  return await import_one_webcrypto.webcrypto.subtle.generateKey(
92
92
  {
93
- name: import_constants.ECC_WRITE_NAME
93
+ name: import_constants.ECC_WRITE_ALGORITHM
94
94
  },
95
95
  extractable,
96
96
  ["sign", "verify"]
@@ -127,9 +127,105 @@ const _EccKeys = class _EccKeys extends import_base.AbstractKeys {
127
127
  DID: did
128
128
  };
129
129
  }
130
+ /**
131
+ * "Add a device," meaning, take an existing AES key and add the ability
132
+ * for a new keypair to decrypt/use the AES key.
133
+ *
134
+ * This implements HPKE-style key wrapping:
135
+ * 1. Generate ephemeral X25519 keypair
136
+ * 2. Do ECDH with recipient's public key -> shared secret
137
+ * 3. Use HKDF to derive a KEK (key encryption key)
138
+ * 4. AES-GCM encrypt the content key under the KEK
139
+ * 5. Return the ephemeral public key (encapsulation) + wrapped key
140
+ *
141
+ * @param contentKey The existing AES key used to encrypt the content.
142
+ * @param newPublicKey The new device's public X25519 key.
143
+ * @param info Optional info parameter for HKDF. Defaults to 'key-wrap'.
144
+ * @returns {Promise<WrappedKey>} The ephemeral public key (base64) and
145
+ * the wrapped content key (base64).
146
+ */
147
+ async wrap(contentKey, newPublicKey, info) {
148
+ const ephemeralKeypair = await _EccKeys._createExchangeKeys(true);
149
+ const salt = crypto.getRandomValues(new Uint8Array(import_constants.SALT_LENGTH));
150
+ const kek = await deriveKey(
151
+ ephemeralKeypair.privateKey,
152
+ newPublicKey,
153
+ salt,
154
+ info || "key-wrap"
155
+ );
156
+ let contentKeyBytes;
157
+ if (contentKey instanceof CryptoKey) {
158
+ const exported = await crypto.subtle.exportKey("raw", contentKey);
159
+ contentKeyBytes = new Uint8Array(exported);
160
+ } else if (typeof contentKey === "string") {
161
+ contentKeyBytes = new Uint8Array((0, import_util.base64ToArrBuf)(contentKey));
162
+ } else {
163
+ contentKeyBytes = contentKey;
164
+ }
165
+ const iv = crypto.getRandomValues(new Uint8Array(import_constants.IV_LENGTH));
166
+ const wrappedKeyBuffer = await crypto.subtle.encrypt(
167
+ { name: import_constants.DEFAULT_SYMM_ALGORITHM, iv },
168
+ kek,
169
+ toArrayBuffer(contentKeyBytes)
170
+ );
171
+ const ephemeralPubKeyBuffer = await exportPublicKey(ephemeralKeypair);
172
+ const saltBuf = new Uint8Array(salt);
173
+ const ivBuf = new Uint8Array(iv);
174
+ const wrappedBuf = new Uint8Array(wrappedKeyBuffer);
175
+ const combinedSize = saltBuf.length + ivBuf.length + wrappedBuf.length;
176
+ const combined = new Uint8Array(combinedSize);
177
+ combined.set(saltBuf, 0);
178
+ combined.set(ivBuf, saltBuf.length);
179
+ combined.set(wrappedBuf, saltBuf.length + ivBuf.length);
180
+ return {
181
+ enc: (0, import_util.toBase64)(new Uint8Array(ephemeralPubKeyBuffer)),
182
+ wrappedKey: (0, import_util.toBase64)(combined)
183
+ };
184
+ }
185
+ /**
186
+ * Unwrap a content key that was wrapped for this device using the `add` method.
187
+ *
188
+ * The recipient device uses its private key + the ephemeral public key
189
+ * to rederive the KEK and decrypt the wrapped content key.
190
+ *
191
+ * @param enc The ephemeral public key (base64) from the sender.
192
+ * @param wrappedKey The wrapped content key (base64) - contains salt + iv + ciphertext.
193
+ * @param info Optional info parameter for HKDF. Must match what was used in `add`. Defaults to 'key-wrap'.
194
+ * @returns {Promise<CryptoKey>} The unwrapped AES content key.
195
+ */
196
+ async unwrap(enc, wrappedKey, info) {
197
+ const ephemeralPubKey = await importPublicKey(
198
+ enc,
199
+ import_types.EccCurve.X25519,
200
+ import_types.KeyUse.Exchange
201
+ );
202
+ const wrappedBuf = new Uint8Array((0, import_util.base64ToArrBuf)(wrappedKey));
203
+ const salt = wrappedBuf.slice(0, import_constants.SALT_LENGTH);
204
+ const iv = wrappedBuf.slice(import_constants.SALT_LENGTH, import_constants.SALT_LENGTH + import_constants.IV_LENGTH);
205
+ const ciphertext = wrappedBuf.slice(import_constants.SALT_LENGTH + import_constants.IV_LENGTH);
206
+ const kek = await deriveKey(
207
+ this.exchangeKey.privateKey,
208
+ ephemeralPubKey,
209
+ salt,
210
+ info || "key-wrap"
211
+ );
212
+ const contentKeyBytes = await crypto.subtle.decrypt(
213
+ { name: import_constants.DEFAULT_SYMM_ALGORITHM, iv },
214
+ kek,
215
+ toArrayBuffer(ciphertext)
216
+ );
217
+ const contentKey = await crypto.subtle.importKey(
218
+ "raw",
219
+ contentKeyBytes,
220
+ { name: import_constants.DEFAULT_SYMM_ALGORITHM },
221
+ true,
222
+ ["encrypt", "decrypt"]
223
+ );
224
+ return contentKey;
225
+ }
130
226
  /**
131
227
  * Encrypt the given content to the given public key, or encrypt to
132
- * our public key if it is not passed in.
228
+ * our own public key if a key is not passed in.
133
229
  *
134
230
  * @param {string|Uint8Array} content Content to encrypt
135
231
  * @param {CryptoKey|string} [recipient] Their public key. Optional b/c we
@@ -296,7 +392,7 @@ const _EccKeys = class _EccKeys extends import_base.AbstractKeys {
296
392
  data = msg;
297
393
  }
298
394
  const signature = await import_one_webcrypto.webcrypto.subtle.sign(
299
- { name: import_constants.ECC_WRITE_ALG },
395
+ { name: import_constants.ECC_WRITE_ALGORITHM },
300
396
  this.writeKey.privateKey,
301
397
  toArrayBuffer(data)
302
398
  );
@@ -328,7 +424,7 @@ async function exportPublicKey(keypair, format = "raw") {
328
424
  __name(exportPublicKey, "exportPublicKey");
329
425
  async function importPublicKey(base64Key, curve, use) {
330
426
  (0, import_errors.checkValidKeyUse)(use);
331
- const alg = use === import_types.KeyUse.Exchange ? import_constants.ECC_EXCHANGE_ALG : import_constants.ECC_WRITE_ALG;
427
+ const alg = use === import_types.KeyUse.Exchange ? import_constants.ECC_EXCHANGE_ALGORITHM : import_constants.ECC_WRITE_ALGORITHM;
332
428
  const uses = use === import_types.KeyUse.Exchange ? [] : ["verify"];
333
429
  const buf = (0, import_util.base64ToArrBuf)(base64Key);
334
430
  const algorithm = curve === import_types.EccCurve.X25519 ? { name: alg } : { name: alg, namedCurve: curve };
@@ -370,7 +466,7 @@ async function verify(msg, sig, signingDid) {
370
466
  const publicKey = await import_one_webcrypto.webcrypto.subtle.importKey(
371
467
  "raw",
372
468
  rawKeyBytes,
373
- { name: import_constants.ECC_WRITE_ALG },
469
+ { name: import_constants.ECC_WRITE_ALGORITHM },
374
470
  true,
375
471
  ["verify"]
376
472
  );
@@ -390,7 +486,7 @@ async function verify(msg, sig, signingDid) {
390
486
  signature = sig;
391
487
  }
392
488
  const isValid = await import_one_webcrypto.webcrypto.subtle.verify(
393
- { name: import_constants.ECC_WRITE_ALG },
489
+ { name: import_constants.ECC_WRITE_ALGORITHM },
394
490
  publicKey,
395
491
  toArrayBuffer(signature),
396
492
  toArrayBuffer(data)
@@ -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 ECC_EXCHANGE_ALG,\n ECC_WRITE_ALG,\n DEFAULT_SYMM_ALGORITHM,\n SALT_LENGTH,\n IV_LENGTH,\n DEFAULT_SYMM_LENGTH,\n ECC_WRITE_NAME,\n ECC_EXCHANGE_NAME\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} 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 (extractable:boolean = false):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_NAME\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_NAME\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 EccKeys = 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 * Encrypt the given content to the given public key, or encrypt to\n * our public key if it 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_ALG },\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_ALG : ECC_WRITE_ALG\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_ALG },\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_ALG },\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-GCM', length: keysize || DEFAULT_SYMM_LENGTH },\n false,\n ['encrypt', 'decrypt']\n )\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAA0B;AAC1B,yBAAkD;AAClD,uBAWO;AACP,mBASO;AACP,kBAKO;AACP,oBAAiC;AACjC,kBAA2C;AAG3C,SAAS,cAAe,MAA6B;AACjD,SAAO,IAAI,WAAW,IAAI,EAAE;AAChC;AAFS;AAOF,MAAM,WAAN,MAAM,iBAAgB,yBAAa;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,oBA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,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,qCAAoB;AAAA,IAC1D;AAAA,IACA,CAAC,WAAW,SAAS;AAAA,EACzB;AACJ;AAlCe;",
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-GCM', length: keysize || DEFAULT_SYMM_LENGTH },\n false,\n ['encrypt', 'decrypt']\n )\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAA0B;AAC1B,yBAAkD;AAClD,uBASO;AACP,mBAUO;AACP,kBAKO;AACP,oBAAiC;AACjC,kBAA2C;AAG3C,SAAS,cAAe,MAA6B;AACjD,SAAO,IAAI,WAAW,IAAI,EAAE;AAChC;AAFS;AAOF,MAAM,WAAN,MAAM,iBAAgB,yBAAa;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,aAAS,6BAAS,YAAY,MAAM,QAAI,sBAAS,WAAW;AAAA,MACvE,GAJU;AAAA,IAKd,CAAC;AAAA,EACL;AAAA,EAEA,IAAI,iB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AACnC,aAAO,IAAI,WAAW,GAAG;AAAA,IAC7B,OAAO;AACH,aAAO;AAAA,IACX;AAGA,QAAI;AACJ,QAAI,OAAO,QAAQ,UAAU;AACzB,kBAAY,IAAI,eAAW,4BAAe,GAAG,CAAC;AAAA,IAClD,OAAO;AACH,kBAAY;AAAA,IAChB;AAGA,UAAM,UAAU,MAAM,+BAAU,OAAO;AAAA,MACnC,EAAE,MAAM,qCAAoB;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,qCAAoB;AAAA,IAC1D;AAAA,IACA,CAAC,WAAW,SAAS;AAAA,EACzB;AACJ;AAlCe;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,5 @@
1
1
  import { type SupportedEncodings } from 'uint8arrays';
2
- import { EccCurve, KeyUse, type PublicKey, type SymmKeyLength, type SymmKey, type Msg, type CharSize, type DID } from '../types.js';
2
+ import { EccCurve, KeyUse, type PublicKey, type SymmKeyLength, type SymmKey, type Msg, type CharSize, type DID, type WrappedKey } from '../types.js';
3
3
  import { AbstractKeys, type KeyArgs } from '../_base.js';
4
4
  /**
5
5
  * Class for ECC keys
@@ -35,7 +35,7 @@ export declare class EccKeys extends AbstractKeys {
35
35
  * Restore some keys from indexedDB, or create a new keypair if it doesn't
36
36
  * exist yet. Overrides base class to use ECC-specific key names.
37
37
  */
38
- static load<T extends EccKeys = EccKeys>(this: typeof EccKeys, opts?: Partial<{
38
+ static load<T extends AbstractKeys = EccKeys>(this: typeof EccKeys, opts?: Partial<{
39
39
  encryptionKeyName: string;
40
40
  writeKeyName: string;
41
41
  session: boolean;
@@ -51,9 +51,40 @@ export declare class EccKeys extends AbstractKeys {
51
51
  DID: DID;
52
52
  publicExchangeKey: string;
53
53
  }>;
54
+ /**
55
+ * "Add a device," meaning, take an existing AES key and add the ability
56
+ * for a new keypair to decrypt/use the AES key.
57
+ *
58
+ * This implements HPKE-style key wrapping:
59
+ * 1. Generate ephemeral X25519 keypair
60
+ * 2. Do ECDH with recipient's public key -> shared secret
61
+ * 3. Use HKDF to derive a KEK (key encryption key)
62
+ * 4. AES-GCM encrypt the content key under the KEK
63
+ * 5. Return the ephemeral public key (encapsulation) + wrapped key
64
+ *
65
+ * @param contentKey The existing AES key used to encrypt the content.
66
+ * @param newPublicKey The new device's public X25519 key.
67
+ * @param info Optional info parameter for HKDF. Defaults to 'key-wrap'.
68
+ * @returns {Promise<WrappedKey>} The ephemeral public key (base64) and
69
+ * the wrapped content key (base64).
70
+ */
71
+ wrap(contentKey: SymmKey | Uint8Array | string, newPublicKey: CryptoKey, // the new device's public key
72
+ info?: string): Promise<WrappedKey>;
73
+ /**
74
+ * Unwrap a content key that was wrapped for this device using the `add` method.
75
+ *
76
+ * The recipient device uses its private key + the ephemeral public key
77
+ * to rederive the KEK and decrypt the wrapped content key.
78
+ *
79
+ * @param enc The ephemeral public key (base64) from the sender.
80
+ * @param wrappedKey The wrapped content key (base64) - contains salt + iv + ciphertext.
81
+ * @param info Optional info parameter for HKDF. Must match what was used in `add`. Defaults to 'key-wrap'.
82
+ * @returns {Promise<CryptoKey>} The unwrapped AES content key.
83
+ */
84
+ unwrap(enc: string, wrappedKey: string, info?: string): Promise<CryptoKey>;
54
85
  /**
55
86
  * Encrypt the given content to the given public key, or encrypt to
56
- * our public key if it is not passed in.
87
+ * our own public key if a key is not passed in.
57
88
  *
58
89
  * @param {string|Uint8Array} content Content to encrypt
59
90
  * @param {CryptoKey|string} [recipient] Their public key. Optional b/c we
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ecc/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,kBAAkB,EAAY,MAAM,aAAa,CAAA;AAa/D,OAAO,EACH,QAAQ,EACR,MAAM,EACN,KAAK,SAAS,EACd,KAAK,aAAa,EAClB,KAAK,OAAO,EACZ,KAAK,GAAG,EACR,KAAK,QAAQ,EACb,KAAK,GAAG,EACX,MAAM,aAAa,CAAA;AAQpB,OAAO,EAAE,YAAY,EAAE,KAAK,OAAO,EAAE,MAAM,aAAa,CAAA;AAOxD;;GAEG;AACH,qBAAa,OAAQ,SAAQ,YAAY;IACrC,MAAM,CAAC,IAAI,EAAC,KAAK,GAAC,KAAK,CAAiB;IACxC,MAAM,CAAC,iBAAiB,EAAC,MAAM,CAAuB;IACtD,MAAM,CAAC,cAAc,EAAC,MAAM,CAAoB;IAChD,MAAM,CAAC,IAAI,SAAS;IAEpB;;;;;;;;OAQG;WACU,MAAM,CAAC,CAAC,SAAS,YAAY,GAAG,OAAO,EAChD,OAAO,CAAC,EAAC,OAAO,EAChB,WAAW,CAAC,EAAC,OAAO,EACpB,IAAI,CAAC,EAAC;QACF,YAAY,CAAC,EAAC,aAAa,GAAC,IAAI,CAAC;QACjC,SAAS,CAAC,EAAC,aAAa,GAAC,IAAI,CAAC;KACjC,GACH,OAAO,CAAC,CAAC,CAAC;gBAIC,IAAI,EAAC,OAAO;IAMzB,IAAI,iBAAiB;4BAGa,kBA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AC,MAAM,GAAC,OAAO,GAC9B,OAAO,CAAC,WAAW,CAAC,CAAA;AAStB,wBAAsB,eAAe,CACjC,SAAS,EAAC,MAAM,EAChB,KAAK,EAAC,QAAQ,EACd,GAAG,EAAC,MAAM,GACZ,OAAO,CAAC,SAAS,CAAC,CAkBnB;;;;;AAED,wBAGC;AAqCD;;;GAGG;AACH,wBAAsB,MAAM,CACxB,GAAG,EAAC,MAAM,GAAC,UAAU,EACrB,GAAG,EAAC,MAAM,GAAC,UAAU,EACrB,UAAU,EAAC,GAAG,GAChB,OAAO,CAAC,OAAO,CAAC,CAsDjB"}
package/dist/ecc/index.js CHANGED
@@ -7,14 +7,12 @@ import { toString } from "uint8arrays";
7
7
  import {
8
8
  DEFAULT_ECC_EXCHANGE,
9
9
  DEFAULT_ECC_WRITE,
10
- ECC_EXCHANGE_ALG,
11
- ECC_WRITE_ALG,
12
10
  DEFAULT_SYMM_ALGORITHM,
13
11
  SALT_LENGTH,
14
12
  IV_LENGTH,
15
13
  DEFAULT_SYMM_LENGTH,
16
- ECC_WRITE_NAME,
17
- ECC_EXCHANGE_NAME
14
+ ECC_WRITE_ALGORITHM,
15
+ ECC_EXCHANGE_ALGORITHM
18
16
  } from "../constants.js";
19
17
  import {
20
18
  EccCurve,
@@ -73,7 +71,7 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
73
71
  static async _createExchangeKeys(extractable = false) {
74
72
  return await webcrypto.subtle.generateKey(
75
73
  {
76
- name: ECC_EXCHANGE_NAME
74
+ name: ECC_EXCHANGE_ALGORITHM
77
75
  // namedCurve: EccCurve.X25519
78
76
  },
79
77
  extractable,
@@ -83,7 +81,7 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
83
81
  static async _createWriteKeys(extractable = false) {
84
82
  return await webcrypto.subtle.generateKey(
85
83
  {
86
- name: ECC_WRITE_NAME
84
+ name: ECC_WRITE_ALGORITHM
87
85
  },
88
86
  extractable,
89
87
  ["sign", "verify"]
@@ -120,9 +118,105 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
120
118
  DID: did
121
119
  };
122
120
  }
121
+ /**
122
+ * "Add a device," meaning, take an existing AES key and add the ability
123
+ * for a new keypair to decrypt/use the AES key.
124
+ *
125
+ * This implements HPKE-style key wrapping:
126
+ * 1. Generate ephemeral X25519 keypair
127
+ * 2. Do ECDH with recipient's public key -> shared secret
128
+ * 3. Use HKDF to derive a KEK (key encryption key)
129
+ * 4. AES-GCM encrypt the content key under the KEK
130
+ * 5. Return the ephemeral public key (encapsulation) + wrapped key
131
+ *
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'.
135
+ * @returns {Promise<WrappedKey>} The ephemeral public key (base64) and
136
+ * the wrapped content key (base64).
137
+ */
138
+ async wrap(contentKey, newPublicKey, info) {
139
+ const ephemeralKeypair = await _EccKeys._createExchangeKeys(true);
140
+ const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
141
+ const kek = await deriveKey(
142
+ ephemeralKeypair.privateKey,
143
+ newPublicKey,
144
+ salt,
145
+ info || "key-wrap"
146
+ );
147
+ let contentKeyBytes;
148
+ if (contentKey instanceof CryptoKey) {
149
+ const exported = await crypto.subtle.exportKey("raw", contentKey);
150
+ contentKeyBytes = new Uint8Array(exported);
151
+ } else if (typeof contentKey === "string") {
152
+ contentKeyBytes = new Uint8Array(base64ToArrBuf(contentKey));
153
+ } else {
154
+ contentKeyBytes = contentKey;
155
+ }
156
+ const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
157
+ const wrappedKeyBuffer = await crypto.subtle.encrypt(
158
+ { name: DEFAULT_SYMM_ALGORITHM, iv },
159
+ kek,
160
+ toArrayBuffer(contentKeyBytes)
161
+ );
162
+ const ephemeralPubKeyBuffer = await exportPublicKey(ephemeralKeypair);
163
+ const saltBuf = new Uint8Array(salt);
164
+ const ivBuf = new Uint8Array(iv);
165
+ const wrappedBuf = new Uint8Array(wrappedKeyBuffer);
166
+ const combinedSize = saltBuf.length + ivBuf.length + wrappedBuf.length;
167
+ const combined = new Uint8Array(combinedSize);
168
+ combined.set(saltBuf, 0);
169
+ combined.set(ivBuf, saltBuf.length);
170
+ combined.set(wrappedBuf, saltBuf.length + ivBuf.length);
171
+ return {
172
+ enc: toBase64(new Uint8Array(ephemeralPubKeyBuffer)),
173
+ wrappedKey: toBase64(combined)
174
+ };
175
+ }
176
+ /**
177
+ * Unwrap a content key that was wrapped for this device using the `add` method.
178
+ *
179
+ * The recipient device uses its private key + the ephemeral public key
180
+ * to rederive the KEK and decrypt the wrapped content key.
181
+ *
182
+ * @param enc The ephemeral public key (base64) from the sender.
183
+ * @param wrappedKey The wrapped content key (base64) - contains salt + iv + ciphertext.
184
+ * @param info Optional info parameter for HKDF. Must match what was used in `add`. Defaults to 'key-wrap'.
185
+ * @returns {Promise<CryptoKey>} The unwrapped AES content key.
186
+ */
187
+ async unwrap(enc, wrappedKey, info) {
188
+ const ephemeralPubKey = await importPublicKey(
189
+ enc,
190
+ EccCurve.X25519,
191
+ KeyUse.Exchange
192
+ );
193
+ const wrappedBuf = new Uint8Array(base64ToArrBuf(wrappedKey));
194
+ const salt = wrappedBuf.slice(0, SALT_LENGTH);
195
+ const iv = wrappedBuf.slice(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
196
+ const ciphertext = wrappedBuf.slice(SALT_LENGTH + IV_LENGTH);
197
+ const kek = await deriveKey(
198
+ this.exchangeKey.privateKey,
199
+ ephemeralPubKey,
200
+ salt,
201
+ info || "key-wrap"
202
+ );
203
+ const contentKeyBytes = await crypto.subtle.decrypt(
204
+ { name: DEFAULT_SYMM_ALGORITHM, iv },
205
+ kek,
206
+ toArrayBuffer(ciphertext)
207
+ );
208
+ const contentKey = await crypto.subtle.importKey(
209
+ "raw",
210
+ contentKeyBytes,
211
+ { name: DEFAULT_SYMM_ALGORITHM },
212
+ true,
213
+ ["encrypt", "decrypt"]
214
+ );
215
+ return contentKey;
216
+ }
123
217
  /**
124
218
  * Encrypt the given content to the given public key, or encrypt to
125
- * our public key if it is not passed in.
219
+ * our own public key if a key is not passed in.
126
220
  *
127
221
  * @param {string|Uint8Array} content Content to encrypt
128
222
  * @param {CryptoKey|string} [recipient] Their public key. Optional b/c we
@@ -289,7 +383,7 @@ const _EccKeys = class _EccKeys extends AbstractKeys {
289
383
  data = msg;
290
384
  }
291
385
  const signature = await webcrypto.subtle.sign(
292
- { name: ECC_WRITE_ALG },
386
+ { name: ECC_WRITE_ALGORITHM },
293
387
  this.writeKey.privateKey,
294
388
  toArrayBuffer(data)
295
389
  );
@@ -321,7 +415,7 @@ async function exportPublicKey(keypair, format = "raw") {
321
415
  __name(exportPublicKey, "exportPublicKey");
322
416
  async function importPublicKey(base64Key, curve, use) {
323
417
  checkValidKeyUse(use);
324
- const alg = use === KeyUse.Exchange ? ECC_EXCHANGE_ALG : ECC_WRITE_ALG;
418
+ const alg = use === KeyUse.Exchange ? ECC_EXCHANGE_ALGORITHM : ECC_WRITE_ALGORITHM;
325
419
  const uses = use === KeyUse.Exchange ? [] : ["verify"];
326
420
  const buf = base64ToArrBuf(base64Key);
327
421
  const algorithm = curve === EccCurve.X25519 ? { name: alg } : { name: alg, namedCurve: curve };
@@ -363,7 +457,7 @@ async function verify(msg, sig, signingDid) {
363
457
  const publicKey = await webcrypto.subtle.importKey(
364
458
  "raw",
365
459
  rawKeyBytes,
366
- { name: ECC_WRITE_ALG },
460
+ { name: ECC_WRITE_ALGORITHM },
367
461
  true,
368
462
  ["verify"]
369
463
  );
@@ -383,7 +477,7 @@ async function verify(msg, sig, signingDid) {
383
477
  signature = sig;
384
478
  }
385
479
  const isValid = await webcrypto.subtle.verify(
386
- { name: ECC_WRITE_ALG },
480
+ { name: ECC_WRITE_ALGORITHM },
387
481
  publicKey,
388
482
  toArrayBuffer(signature),
389
483
  toArrayBuffer(data)