@substrate-system/keys 0.3.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +35 -3
  2. package/dist/_base.min.js +2 -2
  3. package/dist/_base.min.js.map +3 -3
  4. package/dist/aes/index.cjs +14 -7
  5. package/dist/aes/index.cjs.map +2 -2
  6. package/dist/aes/index.d.ts +11 -3
  7. package/dist/aes/index.d.ts.map +1 -1
  8. package/dist/aes/index.js +14 -7
  9. package/dist/aes/index.js.map +2 -2
  10. package/dist/aes/index.min.cjs +1 -1
  11. package/dist/aes/index.min.cjs.map +3 -3
  12. package/dist/aes/index.min.js +2 -2
  13. package/dist/aes/index.min.js.map +3 -3
  14. package/dist/browser/index.js +223 -82
  15. package/dist/browser/index.min.js +2 -2
  16. package/dist/constants.cjs +4 -0
  17. package/dist/constants.cjs.map +2 -2
  18. package/dist/constants.d.ts +6 -0
  19. package/dist/constants.d.ts.map +1 -1
  20. package/dist/constants.js +4 -0
  21. package/dist/constants.js.map +2 -2
  22. package/dist/constants.min.cjs +1 -1
  23. package/dist/constants.min.cjs.map +3 -3
  24. package/dist/constants.min.js +1 -1
  25. package/dist/constants.min.js.map +3 -3
  26. package/dist/crypto.cjs +9 -7
  27. package/dist/crypto.cjs.map +2 -2
  28. package/dist/crypto.d.ts +6 -0
  29. package/dist/crypto.d.ts.map +1 -1
  30. package/dist/crypto.js +9 -8
  31. package/dist/crypto.js.map +2 -2
  32. package/dist/crypto.min.cjs +2 -2
  33. package/dist/crypto.min.cjs.map +2 -2
  34. package/dist/crypto.min.js +2 -2
  35. package/dist/crypto.min.js.map +3 -3
  36. package/dist/ecc/index.cjs +176 -60
  37. package/dist/ecc/index.cjs.map +2 -2
  38. package/dist/ecc/index.d.ts +47 -13
  39. package/dist/ecc/index.d.ts.map +1 -1
  40. package/dist/ecc/index.js +179 -61
  41. package/dist/ecc/index.js.map +2 -2
  42. package/dist/ecc/index.min.cjs +1 -1
  43. package/dist/ecc/index.min.cjs.map +3 -3
  44. package/dist/ecc/index.min.js +2 -2
  45. package/dist/ecc/index.min.js.map +3 -3
  46. package/dist/errors.min.js +1 -1
  47. package/dist/index.min.js +2 -2
  48. package/dist/index.min.js.map +3 -3
  49. package/dist/meta.json +33 -26
  50. package/dist/rsa/index.cjs +15 -4
  51. package/dist/rsa/index.cjs.map +2 -2
  52. package/dist/rsa/index.d.ts +6 -1
  53. package/dist/rsa/index.d.ts.map +1 -1
  54. package/dist/rsa/index.js +15 -5
  55. package/dist/rsa/index.js.map +2 -2
  56. package/dist/rsa/index.min.cjs +1 -1
  57. package/dist/rsa/index.min.cjs.map +3 -3
  58. package/dist/rsa/index.min.js +2 -2
  59. package/dist/rsa/index.min.js.map +3 -3
  60. package/dist/types.cjs.map +2 -2
  61. package/dist/types.d.ts +11 -0
  62. package/dist/types.d.ts.map +1 -1
  63. package/dist/types.js.map +2 -2
  64. package/dist/types.min.cjs +1 -1
  65. package/dist/types.min.cjs.map +2 -2
  66. package/dist/types.min.js +1 -1
  67. package/dist/types.min.js.map +2 -2
  68. package/dist/util.cjs +6 -4
  69. package/dist/util.cjs.map +2 -2
  70. package/dist/util.d.ts +4 -0
  71. package/dist/util.d.ts.map +1 -1
  72. package/dist/util.js +6 -4
  73. package/dist/util.js.map +2 -2
  74. package/dist/util.min.cjs +1 -1
  75. package/dist/util.min.cjs.map +3 -3
  76. package/dist/util.min.js +1 -1
  77. package/dist/util.min.js.map +3 -3
  78. package/package.json +2 -2
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/ecc/index.ts"],
4
- "sourcesContent": ["import { 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 } from '../_base.js'\n\nconst webcrypto = globalThis.crypto\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 {{ dbKey, exchangeKeys, writeKeys }} [keys] Key options.\n * `dbKey` prefixes the IndexedDB names used for both keypairs.\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 dbKey?:string,\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n }\n ):Promise<T> {\n return await super.create<T>(session, extractable, keys)\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 * Saves the keys to `indexedDB` before returning, unless you pass\n * `{ persist: false }`.\n *\n * @param {{ dbKey }} [opts] Prefix for both IndexedDB key names.\n */\n static async load<T extends AbstractKeys = EccKeys> (\n this:typeof EccKeys,\n opts:Partial<{\n dbKey:string,\n encryptionKeyName:string,\n writeKeyName:string,\n session:boolean,\n extractable:boolean,\n persist:boolean,\n }> = {\n session: false,\n }\n ):Promise<T> {\n return super.load(opts) 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,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,oBAAoB;AAE7B,MAAM,YAAY,WAAW;AAG7B,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;AAAA,EAgBtC,aAAa,OACT,SACA,aACA,MAKS;AACT,WAAO,MAAM,MAAM,OAAU,SAAS,aAAa,IAAI;AAAA,EAC3D;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,KAAK,SAAS;AAChC,WAAO,OAAO,OAAO,WAAW;AAAA,MAC5B,UAAU,8BAAO,WAAiD;AAC9D,cAAM,cAAc,MAAM,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7B,WAAW,eAAe,aAAa;AACnC,aAAO,IAAI,WAAW,GAAG;AAAA,IAC7B,OAAO;AACH,aAAO;AAAA,IACX;AAGA,QAAI;AACJ,QAAI,OAAO,QAAQ,UAAU;AACzB,kBAAY,IAAI,WAAW,eAAe,GAAG,CAAC;AAAA,IAClD,OAAO;AACH,kBAAY;AAAA,IAChB;AAGA,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 { 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 WRAP_FORMAT_VERSION,\n AES_GCM_TAG_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 } from '../_base.js'\nimport { AES } from '../aes/index.js'\n\nconst webcrypto = globalThis.crypto\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 {{ dbKey, exchangeKeys, writeKeys }} [keys] Key options.\n * `dbKey` prefixes the IndexedDB names used for both keypairs.\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 dbKey?:string,\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n }\n ):Promise<T> {\n return await super.create<T>(session, extractable, keys)\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 * Saves the keys to `indexedDB` before returning, unless you pass\n * `{ persist: false }`.\n *\n * @param {{ dbKey }} [opts] Prefix for both IndexedDB key names.\n */\n static async load<T extends AbstractKeys = EccKeys> (\n this:typeof EccKeys,\n opts:Partial<{\n dbKey:string,\n encryptionKeyName:string,\n writeKeyName:string,\n session:boolean,\n extractable:boolean,\n persist:boolean,\n }> = {\n session: false,\n }\n ):Promise<T> {\n return super.load(opts) 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 * The result is signed with our Ed25519 write key, so the recipient\n * can verify who created the wrap. `unwrap` requires our DID and\n * rejects the wrap unless the signature matches it.\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),\n * the wrapped AES key (base64), and a signature (base64) by\n * our write key.\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. Only the public half is\n // ever exported, so the private half does not need to be\n // extractable.\n const ephemeralKeypair = await EccKeys._createExchangeKeys(false)\n\n // 2. Export the ephemeral and recipient public keys up front, so\n // they can be bound into the KEK derivation below (HPKE-style)\n const ephemeralPubKeyBuffer = await exportPublicKey(ephemeralKeypair)\n const ephemeralPubKeyBytes = new Uint8Array(ephemeralPubKeyBuffer)\n const recipientPubKey = new Uint8Array(\n await webcrypto.subtle.exportKey('raw', newPublicKey)\n )\n const baseInfo = info || 'key-wrap'\n\n // 3. Generate random salt for HKDF\n const salt = webcrypto.getRandomValues(new Uint8Array(SALT_LENGTH))\n\n // 4. Derive KEK using ECDH + HKDF with ephemeral private key and\n // recipient's public key. The HKDF `info` binds the ephemeral and\n // recipient public keys into the derivation, so a KEK can't be\n // replayed against a different ephemeral/recipient pairing.\n const kek = await deriveKey(\n ephemeralKeypair.privateKey,\n newPublicKey,\n salt,\n wrapKekInfo(ephemeralPubKeyBytes, recipientPubKey, baseInfo)\n )\n\n // 5. Prepare the content key for encryption. Buffers we allocate\n // ourselves (from a CryptoKey export or a base64 string) are\n // zeroed below once no longer needed; a caller-supplied\n // Uint8Array is left alone, since zeroing it would mutate memory\n // the caller still owns a reference to.\n let contentKeyBytes:Uint8Array\n let ownsContentKeyBytes = false\n if (contentKey instanceof CryptoKey) {\n // Export the AES key to raw format\n const exported = await webcrypto.subtle.exportKey('raw', contentKey)\n contentKeyBytes = new Uint8Array(exported)\n ownsContentKeyBytes = true\n } else if (typeof contentKey === 'string') {\n contentKeyBytes = fromString(contentKey, 'base64pad')\n ownsContentKeyBytes = true\n } else {\n contentKeyBytes = contentKey\n }\n\n // 6. Generate IV for AES-GCM encryption\n const iv = webcrypto.getRandomValues(new Uint8Array(IV_LENGTH))\n\n // 7. Encrypt the content key with the KEK\n const wrappedKeyBuffer = await webcrypto.subtle.encrypt(\n { name: DEFAULT_SYMM_ALGORITHM, iv },\n kek,\n toArrayBuffer(contentKeyBytes)\n )\n if (ownsContentKeyBytes) contentKeyBytes.fill(0)\n\n // 8. Combine version + salt + iv + wrapped key for the final\n // wrapped key blob. The version byte lets future format or\n // algorithm changes be detected in `unwrap` instead of silently\n // misparsed.\n const ivBuf = new Uint8Array(iv)\n const wrappedBuf = new Uint8Array(wrappedKeyBuffer)\n const combinedSize = 1 + SALT_LENGTH + ivBuf.length + wrappedBuf.length\n const combined = new Uint8Array(combinedSize)\n combined[0] = WRAP_FORMAT_VERSION\n combined.set(salt, 1)\n combined.set(ivBuf, 1 + SALT_LENGTH)\n combined.set(wrappedBuf, 1 + SALT_LENGTH + ivBuf.length)\n\n // 9. Sign the wrap with our write key, binding the ephemeral\n // public key, the recipient, the blob, and the info string\n const signData = wrapSignData(\n ephemeralPubKeyBytes,\n recipientPubKey,\n combined,\n baseInfo\n )\n const signature = await this.sign(signData)\n\n // 10. Return base64-encoded results\n return {\n enc: toBase64(ephemeralPubKeyBytes),\n wrappedKey: toBase64(combined),\n signature: toString(signature, 'base64pad')\n }\n }\n\n /**\n * Unwrap a content key that another device wrapped for this device\n * with `wrap`.\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 * The wrap's signature is always checked against `signer` before\n * anything is decrypted, and this throws if the signature is missing\n * or invalid. `signer` must be the DID of the device you expect the\n * key from, obtained over a channel an attacker cannot tamper with.\n * A DID that travels alongside the wrapped key proves nothing, since\n * an attacker who can swap the wrapped key can swap the DID too.\n *\n * @param wrapped The `{ enc, wrappedKey, signature }` object returned\n * by `wrap`.\n * @param signer The DID of the expected sender.\n * @param opts.info The HKDF info string. Must match what was passed to\n * `wrap`. Defaults to 'key-wrap'.\n * @param opts.extractable Can the returned key be exported with\n * `crypto.subtle.exportKey`? Default `true`.\n * @returns {Promise<CryptoKey>} The unwrapped AES content key.\n */\n async unwrap (\n wrapped:WrappedKey,\n signer:DID,\n opts:{ info?:string, extractable?:boolean } = {}\n ):Promise<CryptoKey> {\n const { enc, wrappedKey, signature } = wrapped\n const info = opts.info\n const extractable = opts.extractable ?? true\n\n // Fail closed for JS callers, or anyone who casts around the\n // types: an unsigned or unattributed wrap is never accepted.\n if (!signer) {\n throw new Error('`unwrap` requires the DID of the sender')\n }\n if (!signature) {\n throw new Error('The wrapped key is not signed')\n }\n\n // 1. Decode and validate the ephemeral public key and wrapped\n // key blob up front, so truncated/malformed input fails with a\n // clear error instead of an opaque `OperationError` deep inside\n // WebCrypto.\n const encBytes = fromString(enc, 'base64pad')\n if (encBytes.length !== X25519_PUBLIC_KEY_LENGTH) {\n throw new Error(\n `\\`enc\\` must be a ${X25519_PUBLIC_KEY_LENGTH}-byte ` +\n `X25519 public key, got ${encBytes.length} bytes`\n )\n }\n\n const wrappedBuf = new Uint8Array(base64ToArrBuf(wrappedKey))\n const baseInfo = info || 'key-wrap'\n const minWrappedLength = 1 + SALT_LENGTH + IV_LENGTH + AES_GCM_TAG_LENGTH\n if (wrappedBuf.length < minWrappedLength) {\n throw new Error(\n `Wrapped key must be at least ${minWrappedLength} bytes, ` +\n `got ${wrappedBuf.length} bytes`\n )\n }\n\n // 2. Check the format version, so a future format/algorithm\n // change can be detected instead of silently misparsed\n const version = wrappedBuf[0]\n if (version !== WRAP_FORMAT_VERSION) {\n throw new Error(\n `Unsupported wrapped key format version: ${version}`\n )\n }\n\n const ourPubKeyBytes = new Uint8Array(\n await exportPublicKey(this.exchangeKey)\n )\n\n // 3. Verify the sender's signature before decrypting anything\n const signData = wrapSignData(\n encBytes,\n ourPubKeyBytes,\n wrappedBuf,\n baseInfo\n )\n const isValid = await verify(signData, signature, signer)\n if (!isValid) {\n throw new Error('Invalid signature for the wrapped key')\n }\n\n // 4. Import the ephemeral public key\n const ephemeralPubKey = await importPublicKey(\n enc,\n EccCurve.X25519,\n KeyUse.Exchange\n )\n\n // 5. Extract salt, iv, and ciphertext (after the version byte)\n const salt = wrappedBuf.slice(1, 1 + SALT_LENGTH)\n const iv = wrappedBuf.slice(\n 1 + SALT_LENGTH,\n 1 + SALT_LENGTH + IV_LENGTH\n )\n const ciphertext = wrappedBuf.slice(1 + SALT_LENGTH + IV_LENGTH)\n\n // 6. Derive the same KEK using our private key and the ephemeral\n // public key. The HKDF `info` must match what `wrap` bound in:\n // the ephemeral public key + our own (recipient) public key.\n const kek = await deriveKey(\n this.exchangeKey.privateKey,\n ephemeralPubKey,\n salt,\n wrapKekInfo(encBytes, ourPubKeyBytes, baseInfo)\n )\n\n // 7. Decrypt the wrapped key\n const contentKeyBytes = await webcrypto.subtle.decrypt(\n { name: DEFAULT_SYMM_ALGORITHM, iv },\n kek,\n toArrayBuffer(ciphertext)\n )\n\n // 8. Import the content key back as a CryptoKey\n const contentKey = await webcrypto.subtle.importKey(\n 'raw',\n contentKeyBytes,\n { name: DEFAULT_SYMM_ALGORITHM },\n extractable,\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] Use this exact AES key\n * instead of deriving one from ECDH. Not relevant for most use\n * cases. Pass the same key to `decrypt` to read it back.\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 = webcrypto.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. Only the\n // public half is ever exported, so the private half does not need\n // to be extractable.\n const ephemeralKeypair = await EccKeys._createExchangeKeys(false)\n\n // honor a caller-supplied key end to end; otherwise derive one\n // using the ephemeral private key\n const key = aesKey ?\n (aesKey instanceof CryptoKey ? aesKey : await AES.import(aesKey)) :\n await deriveKey(\n ephemeralKeypair.privateKey, // use ephemeral private key\n publicKey,\n salt,\n info || EccKeys.INFO,\n keysize\n )\n\n const iv = webcrypto.getRandomValues(new Uint8Array(IV_LENGTH))\n const plaintext:Uint8Array = (typeof content === 'string' ?\n new TextEncoder().encode(content) :\n content)\n\n const ciphertext = await webcrypto.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 * @param {SymmKey|Uint8Array|string} [aesKey] Use this exact AES key\n * instead of deriving one from ECDH. Must match the `aesKey`\n * passed to the corresponding `encrypt` call.\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 aesKey?:SymmKey|Uint8Array|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 // honor a caller-supplied key end to end; otherwise derive one\n // with our private key + the ephemeral public key\n const { privateKey } = this.exchangeKey\n const key = aesKey ?\n (aesKey instanceof CryptoKey ? aesKey : await AES.import(aesKey)) :\n 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 webcrypto.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 aesKey?:SymmKey|Uint8Array|string|null,\n ):Promise<string> {\n const dec = await this.decrypt(msg, aesAlgorithm, info, aesKey)\n return toString(new Uint8Array(dec))\n }\n\n /**\n * Do DHKE, create a new AES-GCM key.\n *\n * The HKDF salt is either supplied by the caller (so both sides can\n * re-derive the exact same key later) or generated at random, in\n * which case it is returned as a `.salt` (base64) property on the\n * key so the caller can persist it for later re-derivation.\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 * @param {Uint8Array|ArrayBuffer|string|null} [salt] Reuse this salt\n * instead of generating a random one -- pass the same salt on\n * both sides to re-derive the same key.\n * @returns {CryptoKey} New AES key, with a `.salt` (base64) property\n */\n async getAesKey (\n publicKey?:CryptoKey|string|null,\n info?:string|null,\n salt?:Uint8Array|ArrayBuffer|string|null,\n ):Promise<CryptoKey & { salt:string }> {\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 // Reuse the given salt, or generate a random one for HKDF\n const saltBytes:Uint8Array = (salt ?\n new Uint8Array(\n typeof salt === 'string' ? base64ToArrBuf(salt) : salt\n ) :\n webcrypto.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 saltBytes,\n info || EccKeys.INFO\n )\n\n // expose the salt used, so a randomly-generated one isn't lost\n return Object.assign(aesKey, { salt: toBase64(saltBytes) })\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 webcrypto.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 * Build the HKDF `info` used to derive a `wrap`/`unwrap` KEK: the\n * ephemeral public key + recipient public key + the caller's info string\n * (HPKE-style). Binding both public keys into the derivation means a KEK\n * can only ever be reconstructed for this exact ephemeral/recipient\n * pairing. The two public keys are fixed-length X25519 keys, so they\n * can't be shifted into each other or into the trailing, variable-length\n * info string.\n */\nfunction wrapKekInfo (\n ephemeralPubKey:Uint8Array,\n recipientPubKey:Uint8Array,\n info:string\n):Uint8Array {\n const infoBytes = new TextEncoder().encode(info)\n const data = new Uint8Array(\n ephemeralPubKey.length + recipientPubKey.length + infoBytes.length\n )\n data.set(ephemeralPubKey, 0)\n data.set(recipientPubKey, ephemeralPubKey.length)\n data.set(infoBytes, ephemeralPubKey.length + recipientPubKey.length)\n return data\n}\n\n/**\n * Build the message that `wrap` signs and `unwrap` verifies:\n * ephemeral public key + recipient public key + wrapped key blob + info.\n * The blob gets a length prefix so variable-length fields can't be\n * shifted into each other.\n */\nfunction wrapSignData (\n ephemeralPubKey:Uint8Array,\n recipientPubKey:Uint8Array,\n wrappedBlob:Uint8Array,\n info:string\n):Uint8Array {\n const infoBytes = new TextEncoder().encode(info)\n const blobLength = new Uint8Array(4)\n new DataView(blobLength.buffer).setUint32(0, wrappedBlob.length)\n\n const data = new Uint8Array(\n ephemeralPubKey.length + recipientPubKey.length +\n blobLength.length + wrappedBlob.length + infoBytes.length\n )\n let offset = 0\n data.set(ephemeralPubKey, offset)\n offset += ephemeralPubKey.length\n data.set(recipientPubKey, offset)\n offset += recipientPubKey.length\n data.set(blobLength, offset)\n offset += blobLength.length\n data.set(wrappedBlob, offset)\n offset += wrappedBlob.length\n data.set(infoBytes, offset)\n\n return data\n}\n\n/**\n * Derive an AES key from X25519 keypair via ECDH + HKDF.\n * @param {string|Uint8Array} info Passing a `Uint8Array` lets callers bind\n * extra transcript data (e.g. the ephemeral and recipient public keys)\n * into the HKDF `info` field, HPKE-style.\n */\nasync function deriveKey (\n privateKey:CryptoKey,\n publicKey:CryptoKey,\n salt:Uint8Array|ArrayBuffer,\n info:string|Uint8Array,\n keysize?:number|null\n):Promise<CryptoKey> {\n const encoder = new TextEncoder()\n const infoBytes = typeof info === 'string' ? encoder.encode(info) : info\n const sharedSecret = await webcrypto.subtle.deriveBits(\n { name: 'X25519', public: publicKey },\n privateKey,\n 256\n )\n\n const hkdfBaseKey = await webcrypto.subtle.importKey(\n 'raw',\n sharedSecret,\n 'HKDF',\n false,\n ['deriveKey']\n )\n\n return webcrypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: salt instanceof Uint8Array ? toArrayBuffer(salt) : salt,\n info: toArrayBuffer(infoBytes)\n },\n hkdfBaseKey,\n { name: 'AES-GCM', length: keysize || DEFAULT_SYMM_LENGTH },\n false,\n ['encrypt', 'decrypt']\n )\n}\n"],
5
+ "mappings": ";;;;AAAA,SAAkC,UAAU,kBAAkB;AAC9D;AAAA,EACI;AAAA,EACA;AAAA,EACA;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,oBAAoB;AAC7B,SAAS,WAAW;AAEpB,MAAM,YAAY,WAAW;AAG7B,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;AAAA,EAgBtC,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AAW,QAAQ,OAAO,IAAI,IAAI;AACpE,QAAM,eAAe,MAAM,UAAU,OAAO;AAAA,IACxC,EAAE,MAAM,UAAU,QAAQ,UAAU;AAAA,IACpC;AAAA,IACA;AAAA,EACJ;AAEA,QAAM,cAAc,MAAM,UAAU,OAAO;AAAA,IACvC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,CAAC,WAAW;AAAA,EAChB;AAEA,SAAO,UAAU,OAAO;AAAA,IACpB;AAAA,MACI,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM,gBAAgB,aAAa,cAAc,IAAI,IAAI;AAAA,MACzD,MAAM,cAAc,SAAS;AAAA,IACjC;AAAA,IACA;AAAA,IACA,EAAE,MAAM,WAAW,QAAQ,WAAW,oBAAoB;AAAA,IAC1D;AAAA,IACA,CAAC,WAAW,SAAS;AAAA,EACzB;AACJ;AAnCe;",
6
6
  "names": []
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var B=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var H=(s,e,t)=>e in s?B(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var u=(s,e)=>B(s,"name",{value:e,configurable:!0});var M=(s,e)=>{for(var t in e)B(s,t,{get:e[t],enumerable:!0})},G=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of O(e))!F.call(s,i)&&i!==t&&B(s,i,{get:()=>e[i],enumerable:!(n=_(e,i))||n.enumerable});return s};var R=s=>G(B({},"__esModule",{value:!0}),s);var T=(s,e,t)=>H(s,typeof e!="symbol"?e+"":e,t);var W={};M(W,{EccKeys:()=>A,default:()=>z,exportPublicKey:()=>x,importPublicKey:()=>v,verify:()=>V});module.exports=R(W);var w=require("uint8arrays"),r=require("../constants.js"),g=require("../types.js"),p=require("../util.js"),D=require("../errors.js"),L=require("../_base.js");const b=globalThis.crypto;function U(s){return new Uint8Array(s).buffer}u(U,"toArrayBuffer");const l=class l extends L.AbstractKeys{static async create(e,t,n){return await super.create(e,t,n)}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,w.toString)(i,t):(0,p.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,w.toString)(i,t):(0,p.toBase64)(n)},"asString")})}static async _createExchangeKeys(e=!1){return await b.subtle.generateKey({name:r.ECC_EXCHANGE_ALGORITHM},e,["deriveKey","deriveBits"])}static async _createWriteKeys(e=!1){return await b.subtle.generateKey({name:r.ECC_WRITE_ALGORITHM},e,["sign","verify"])}static async load(e={session:!1}){return super.load(e)}async toJson(e){const t=this.DID,n=await x(this.exchangeKey);return{publicExchangeKey:e?(0,w.toString)(new Uint8Array(n),e):(0,p.toBase64)(n),DID:t}}async wrap(e,t,n){const i=await l._createExchangeKeys(!0),a=crypto.getRandomValues(new Uint8Array(r.SALT_LENGTH)),c=await P(i.privateKey,t,a,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,w.fromString)(e,"base64pad"):y=e;const o=crypto.getRandomValues(new Uint8Array(r.IV_LENGTH)),K=await crypto.subtle.encrypt({name:r.DEFAULT_SYMM_ALGORITHM,iv:o},c,U(y)),m=await x(i),f=new Uint8Array(a),E=new Uint8Array(o),k=new Uint8Array(K),d=f.length+E.length+k.length,h=new Uint8Array(d);return h.set(f,0),h.set(E,f.length),h.set(k,f.length+E.length),{enc:(0,p.toBase64)(new Uint8Array(m)),wrappedKey:(0,p.toBase64)(h)}}async unwrap(e,t,n){const i=await v(e,g.EccCurve.X25519,g.KeyUse.Exchange),a=new Uint8Array((0,p.base64ToArrBuf)(t)),c=a.slice(0,r.SALT_LENGTH),y=a.slice(r.SALT_LENGTH,r.SALT_LENGTH+r.IV_LENGTH),o=a.slice(r.SALT_LENGTH+r.IV_LENGTH),K=await P(this.exchangeKey.privateKey,i,c,n||"key-wrap"),m=await crypto.subtle.decrypt({name:r.DEFAULT_SYMM_ALGORITHM,iv:y},K,U(o));return await crypto.subtle.importKey("raw",m,{name:r.DEFAULT_SYMM_ALGORITHM},!0,["encrypt","decrypt"])}async encrypt(e,t,n,i,a){const c=crypto.getRandomValues(new Uint8Array(r.SALT_LENGTH)),y=t||this.exchangeKey.publicKey;let o;typeof y=="string"?o=await v(y,g.EccCurve.X25519,g.KeyUse.Exchange):o=y;const K=await l._createExchangeKeys(!0);let m=i||await P(K.privateKey,o,c,n||l.INFO,a);m instanceof CryptoKey||(m=await P(K.privateKey,o,c,n||l.INFO));const f=crypto.getRandomValues(new Uint8Array(r.IV_LENGTH)),E=typeof e=="string"?new TextEncoder().encode(e):e,k=await crypto.subtle.encrypt({name:r.DEFAULT_SYMM_ALGORITHM,iv:f},m,U(E)),d=new Uint8Array(await x(K)),h=new Uint8Array(c),C=new Uint8Array(f),I=new Uint8Array(k),N=d.length+h.length+C.length+I.length,S=new Uint8Array(N);return S.set(d,0),S.set(h,d.length),S.set(C,d.length+h.length),S.set(I,d.length+h.length+C.length),S}async encryptAsString(e,t,n,i,a){const c=await this.encrypt(e,t,n||l.INFO,i,a);return(0,w.toString)(new Uint8Array(c),"base64pad")}async decrypt(e,t,n){const i=(0,p.normalizeToBuf)(e,p.base64ToArrBuf),a=i.slice(0,r.X25519_PUBLIC_KEY_LENGTH),c=await b.subtle.importKey("raw",a,{name:r.ECC_EXCHANGE_ALGORITHM},!0,[]),y=i.slice(r.X25519_PUBLIC_KEY_LENGTH,r.X25519_PUBLIC_KEY_LENGTH+r.SALT_LENGTH),o=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:m}=this.exchangeKey,f=await P(m,c,y,n||l.INFO);return await crypto.subtle.decrypt({name:t||r.DEFAULT_SYMM_ALGORITHM,iv:o},f,K)}async decryptAsString(e,t,n){const i=await this.decrypt(e,t,n);return(0,w.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||l.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 a=await b.subtle.sign({name:r.ECC_WRITE_ALGORITHM},this.writeKey.privateKey,U(i));return new Uint8Array(a)}async signAsString(e,t){const n=await this.sign(e,t);return(0,w.toString)(n,"base64pad")}};u(l,"EccKeys"),T(l,"TYPE","ecc"),T(l,"EXCHANGE_KEY_NAME",r.DEFAULT_ECC_EXCHANGE),T(l,"WRITE_KEY_NAME",r.DEFAULT_ECC_WRITE),T(l,"INFO","keys");let A=l;Object.assign(A.prototype.sign,{asString:u(async function(s,e){const t=await this.sign(s,e);return(0,w.toString)(t,"base64pad")},"asString")});async function x(s,e="raw"){return await crypto.subtle.exportKey(e,s.publicKey)}u(x,"exportPublicKey");async function v(s,e,t){(0,D.checkValidKeyUse)(t);const n=t===g.KeyUse.Exchange?r.ECC_EXCHANGE_ALGORITHM:r.ECC_WRITE_ALGORITHM,i=t===g.KeyUse.Exchange?[]:["verify"],a=(0,p.base64ToArrBuf)(s),c=e===g.EccCurve.X25519?{name:n}:{name:n,namedCurve:e};return b.subtle.importKey("raw",a,c,!0,i)}u(v,"importPublicKey");var z={EccKeys:A,importPublicKey:v};Object.assign(A.prototype.encrypt,{asString:u(async function(s,e,t,n,i){return this.encryptAsString(s,e,t,n,i)},"asString")}),Object.assign(A.prototype.decrypt,{asString:u(async function(s,e){return this.decryptAsString(s,e)},"asString")}),Object.assign(A.prototype.sign,{asString:u(async function(s,e){return this.signAsString(s,e)},"asString")});async function V(s,e,t){try{const n=(0,p.didToPublicKey)(t);if(n.type!=="ed25519")throw new Error(`Expected Ed25519 key for ECC verification, got ${n.type}`);const i=n.publicKey.slice(-32),a=await b.subtle.importKey("raw",i,{name:r.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 o;return typeof e=="string"?o=new Uint8Array((0,p.base64ToArrBuf)(e)):o=e,await b.subtle.verify({name:r.ECC_WRITE_ALGORITHM},a,U(o),U(y))}catch{return!1}}u(V,"verify");async function P(s,e,t,n,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?U(t):t,info:a.encode(n)},y,{name:"AES-GCM",length:i||r.DEFAULT_SYMM_LENGTH},!1,["encrypt","decrypt"])}u(P,"deriveKey");
1
+ "use strict";var v=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var z=(s,e,r)=>e in s?v(s,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[e]=r;var g=(s,e)=>v(s,"name",{value:e,configurable:!0});var j=(s,e)=>{for(var r in e)v(s,r,{get:e[r],enumerable:!0})},Y=(s,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of W(e))!X.call(s,n)&&n!==r&&v(s,n,{get:()=>e[n],enumerable:!(i=V(e,n))||i.enumerable});return s};var $=s=>Y(v({},"__esModule",{value:!0}),s);var k=(s,e,r)=>z(s,typeof e!="symbol"?e+"":e,r);var q={};j(q,{EccKeys:()=>S,default:()=>J,exportPublicKey:()=>B,importPublicKey:()=>I,verify:()=>R});module.exports=$(q);var K=require("uint8arrays"),t=require("../constants.js"),A=require("../types.js"),l=require("../util.js"),H=require("../errors.js"),M=require("../_base.js"),N=require("../aes/index.js");const c=globalThis.crypto;function C(s){return new Uint8Array(s).buffer}g(C,"toArrayBuffer");const h=class h extends M.AbstractKeys{static async create(e,r,i){return await super.create(e,r,i)}get publicExchangeKey(){const e=this.exchangeKey.publicKey;return Object.assign(e,{asString:g(async r=>{const i=await B(this.exchangeKey),n=new Uint8Array(i);return r?(0,K.toString)(n,r):(0,l.toBase64)(i)},"asString")})}get publicWriteKey(){const e=this.writeKey.publicKey;return Object.assign(e,{asString:g(async r=>{const i=await B(this.writeKey),n=new Uint8Array(i);return r?(0,K.toString)(n,r):(0,l.toBase64)(i)},"asString")})}static async _createExchangeKeys(e=!1){return await c.subtle.generateKey({name:t.ECC_EXCHANGE_ALGORITHM},e,["deriveKey","deriveBits"])}static async _createWriteKeys(e=!1){return await c.subtle.generateKey({name:t.ECC_WRITE_ALGORITHM},e,["sign","verify"])}static async load(e={session:!1}){return super.load(e)}async toJson(e){const r=this.DID,i=await B(this.exchangeKey);return{publicExchangeKey:e?(0,K.toString)(new Uint8Array(i),e):(0,l.toBase64)(i),DID:r}}async wrap(e,r,i){const n=await h._createExchangeKeys(!1),a=await B(n),y=new Uint8Array(a),o=new Uint8Array(await c.subtle.exportKey("raw",r)),p=i||"key-wrap",u=c.getRandomValues(new Uint8Array(t.SALT_LENGTH)),f=await D(n.privateKey,r,u,O(y,o,p));let w,d=!1;if(e instanceof CryptoKey){const L=await c.subtle.exportKey("raw",e);w=new Uint8Array(L),d=!0}else typeof e=="string"?(w=(0,K.fromString)(e,"base64pad"),d=!0):w=e;const x=c.getRandomValues(new Uint8Array(t.IV_LENGTH)),m=await c.subtle.encrypt({name:t.DEFAULT_SYMM_ALGORITHM,iv:x},f,C(w));d&&w.fill(0);const b=new Uint8Array(x),P=new Uint8Array(m),T=1+t.SALT_LENGTH+b.length+P.length,U=new Uint8Array(T);U[0]=t.WRAP_FORMAT_VERSION,U.set(u,1),U.set(b,1+t.SALT_LENGTH),U.set(P,1+t.SALT_LENGTH+b.length);const E=G(y,o,U,p),_=await this.sign(E);return{enc:(0,l.toBase64)(y),wrappedKey:(0,l.toBase64)(U),signature:(0,K.toString)(_,"base64pad")}}async unwrap(e,r,i={}){const{enc:n,wrappedKey:a,signature:y}=e,o=i.info,p=i.extractable??!0;if(!r)throw new Error("`unwrap` requires the DID of the sender");if(!y)throw new Error("The wrapped key is not signed");const u=(0,K.fromString)(n,"base64pad");if(u.length!==t.X25519_PUBLIC_KEY_LENGTH)throw new Error(`\`enc\` must be a ${t.X25519_PUBLIC_KEY_LENGTH}-byte X25519 public key, got ${u.length} bytes`);const f=new Uint8Array((0,l.base64ToArrBuf)(a)),w=o||"key-wrap",d=1+t.SALT_LENGTH+t.IV_LENGTH+t.AES_GCM_TAG_LENGTH;if(f.length<d)throw new Error(`Wrapped key must be at least ${d} bytes, got ${f.length} bytes`);const x=f[0];if(x!==t.WRAP_FORMAT_VERSION)throw new Error(`Unsupported wrapped key format version: ${x}`);const m=new Uint8Array(await B(this.exchangeKey)),b=G(u,m,f,w);if(!await R(b,y,r))throw new Error("Invalid signature for the wrapped key");const T=await I(n,A.EccCurve.X25519,A.KeyUse.Exchange),U=f.slice(1,1+t.SALT_LENGTH),E=f.slice(1+t.SALT_LENGTH,1+t.SALT_LENGTH+t.IV_LENGTH),_=f.slice(1+t.SALT_LENGTH+t.IV_LENGTH),L=await D(this.exchangeKey.privateKey,T,U,O(u,m,w)),F=await c.subtle.decrypt({name:t.DEFAULT_SYMM_ALGORITHM,iv:E},L,C(_));return await c.subtle.importKey("raw",F,{name:t.DEFAULT_SYMM_ALGORITHM},p,["encrypt","decrypt"])}async encrypt(e,r,i,n,a){const y=c.getRandomValues(new Uint8Array(t.SALT_LENGTH)),o=r||this.exchangeKey.publicKey;let p;typeof o=="string"?p=await I(o,A.EccCurve.X25519,A.KeyUse.Exchange):p=o;const u=await h._createExchangeKeys(!1),f=n?n instanceof CryptoKey?n:await N.AES.import(n):await D(u.privateKey,p,y,i||h.INFO,a),w=c.getRandomValues(new Uint8Array(t.IV_LENGTH)),d=typeof e=="string"?new TextEncoder().encode(e):e,x=await c.subtle.encrypt({name:t.DEFAULT_SYMM_ALGORITHM,iv:w},f,C(d)),m=new Uint8Array(await B(u)),b=new Uint8Array(y),P=new Uint8Array(w),T=new Uint8Array(x),U=m.length+b.length+P.length+T.length,E=new Uint8Array(U);return E.set(m,0),E.set(b,m.length),E.set(P,m.length+b.length),E.set(T,m.length+b.length+P.length),E}async encryptAsString(e,r,i,n,a){const y=await this.encrypt(e,r,i||h.INFO,n,a);return(0,K.toString)(new Uint8Array(y),"base64pad")}async decrypt(e,r,i,n){const a=(0,l.normalizeToBuf)(e,l.base64ToArrBuf),y=a.slice(0,t.X25519_PUBLIC_KEY_LENGTH),o=await c.subtle.importKey("raw",y,{name:t.ECC_EXCHANGE_ALGORITHM},!0,[]),p=a.slice(t.X25519_PUBLIC_KEY_LENGTH,t.X25519_PUBLIC_KEY_LENGTH+t.SALT_LENGTH),u=a.slice(t.X25519_PUBLIC_KEY_LENGTH+t.SALT_LENGTH,t.X25519_PUBLIC_KEY_LENGTH+t.SALT_LENGTH+t.IV_LENGTH),f=a.slice(t.X25519_PUBLIC_KEY_LENGTH+t.SALT_LENGTH+t.IV_LENGTH),{privateKey:w}=this.exchangeKey,d=n?n instanceof CryptoKey?n:await N.AES.import(n):await D(w,o,p,i||h.INFO);return await c.subtle.decrypt({name:r||t.DEFAULT_SYMM_ALGORITHM,iv:u},d,f)}async decryptAsString(e,r,i,n){const a=await this.decrypt(e,r,i,n);return(0,K.toString)(new Uint8Array(a))}async getAesKey(e,r,i){e||(e=this.publicExchangeKey);let n;typeof e=="string"?n=await I(e,A.EccCurve.X25519,A.KeyUse.Exchange):n=e;const a=i?new Uint8Array(typeof i=="string"?(0,l.base64ToArrBuf)(i):i):c.getRandomValues(new Uint8Array(t.SALT_LENGTH)),y=await D(this.exchangeKey.privateKey,n,a,r||h.INFO);return Object.assign(y,{salt:(0,l.toBase64)(a)})}async sign(e,r){const i=new TextEncoder;let n;typeof e=="string"?n=i.encode(e):e instanceof ArrayBuffer?n=new Uint8Array(e):n=e;const a=await c.subtle.sign({name:t.ECC_WRITE_ALGORITHM},this.writeKey.privateKey,C(n));return new Uint8Array(a)}async signAsString(e,r){const i=await this.sign(e,r);return(0,K.toString)(i,"base64pad")}};g(h,"EccKeys"),k(h,"TYPE","ecc"),k(h,"EXCHANGE_KEY_NAME",t.DEFAULT_ECC_EXCHANGE),k(h,"WRITE_KEY_NAME",t.DEFAULT_ECC_WRITE),k(h,"INFO","keys");let S=h;Object.assign(S.prototype.sign,{asString:g(async function(s,e){const r=await this.sign(s,e);return(0,K.toString)(r,"base64pad")},"asString")});async function B(s,e="raw"){return await c.subtle.exportKey(e,s.publicKey)}g(B,"exportPublicKey");async function I(s,e,r){(0,H.checkValidKeyUse)(r);const i=r===A.KeyUse.Exchange?t.ECC_EXCHANGE_ALGORITHM:t.ECC_WRITE_ALGORITHM,n=r===A.KeyUse.Exchange?[]:["verify"],a=(0,l.base64ToArrBuf)(s),y=e===A.EccCurve.X25519?{name:i}:{name:i,namedCurve:e};return c.subtle.importKey("raw",a,y,!0,n)}g(I,"importPublicKey");var J={EccKeys:S,importPublicKey:I};Object.assign(S.prototype.encrypt,{asString:g(async function(s,e,r,i,n){return this.encryptAsString(s,e,r,i,n)},"asString")}),Object.assign(S.prototype.decrypt,{asString:g(async function(s,e){return this.decryptAsString(s,e)},"asString")}),Object.assign(S.prototype.sign,{asString:g(async function(s,e){return this.signAsString(s,e)},"asString")});async function R(s,e,r){try{const i=(0,l.didToPublicKey)(r);if(i.type!=="ed25519")throw new Error(`Expected Ed25519 key for ECC verification, got ${i.type}`);const n=i.publicKey.slice(-32),a=await c.subtle.importKey("raw",n,{name:t.ECC_WRITE_ALGORITHM},!0,["verify"]),y=new TextEncoder;let o;typeof s=="string"?o=y.encode(s):s instanceof ArrayBuffer?o=new Uint8Array(s):o=s;let p;return typeof e=="string"?p=new Uint8Array((0,l.base64ToArrBuf)(e)):p=e,await c.subtle.verify({name:t.ECC_WRITE_ALGORITHM},a,C(p),C(o))}catch{return!1}}g(R,"verify");function O(s,e,r){const i=new TextEncoder().encode(r),n=new Uint8Array(s.length+e.length+i.length);return n.set(s,0),n.set(e,s.length),n.set(i,s.length+e.length),n}g(O,"wrapKekInfo");function G(s,e,r,i){const n=new TextEncoder().encode(i),a=new Uint8Array(4);new DataView(a.buffer).setUint32(0,r.length);const y=new Uint8Array(s.length+e.length+a.length+r.length+n.length);let o=0;return y.set(s,o),o+=s.length,y.set(e,o),o+=e.length,y.set(a,o),o+=a.length,y.set(r,o),o+=r.length,y.set(n,o),y}g(G,"wrapSignData");async function D(s,e,r,i,n){const a=new TextEncoder,y=typeof i=="string"?a.encode(i):i,o=await c.subtle.deriveBits({name:"X25519",public:e},s,256),p=await c.subtle.importKey("raw",o,"HKDF",!1,["deriveKey"]);return c.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:r instanceof Uint8Array?C(r):r,info:C(y)},p,{name:"AES-GCM",length:n||t.DEFAULT_SYMM_LENGTH},!1,["encrypt","decrypt"])}g(D,"deriveKey");
2
2
  //# sourceMappingURL=index.min.cjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/ecc/index.ts"],
4
- "sourcesContent": ["import { 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 } from '../_base.js'\n\nconst webcrypto = globalThis.crypto\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 {{ dbKey, exchangeKeys, writeKeys }} [keys] Key options.\n * `dbKey` prefixes the IndexedDB names used for both keypairs.\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 dbKey?:string,\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n }\n ):Promise<T> {\n return await super.create<T>(session, extractable, keys)\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 * Saves the keys to `indexedDB` before returning, unless you pass\n * `{ persist: false }`.\n *\n * @param {{ dbKey }} [opts] Prefix for both IndexedDB key names.\n */\n static async load<T extends AbstractKeys = EccKeys> (\n this:typeof EccKeys,\n opts:Partial<{\n dbKey:string,\n encryptionKeyName:string,\n writeKeyName:string,\n session:boolean,\n extractable:boolean,\n persist:boolean,\n }> = {\n session: false,\n }\n ):Promise<T> {\n return super.load(opts) 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: keys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,KAAMzD,aAAgB,WAAanB,EAAcmB,CAAI,EAAIA,EACzD,KAAMuC,EAAQ,OAAOzC,CAAI,CAC7B,EACA4D,EACA,CAAE,KAAM,UAAW,OAAQrC,GAAW,qBAAoB,EAC1D,GACA,CAAC,UAAW,SAAS,CACzB,CACJ,CAlCetC,EAAAmB,EAAA",
6
- "names": ["ecc_exports", "__export", "EccKeys", "ecc_default", "exportPublicKey", "importPublicKey", "verify", "__toCommonJS", "import_uint8arrays", "import_constants", "import_types", "import_util", "import_errors", "import_base", "webcrypto", "toArrayBuffer", "data", "__name", "_EccKeys", "session", "extractable", "keys", "publicKey", "format", "arrayBuffer", "exportPublicKey", "uint8Array", "opts", "did", "rawKey", "contentKey", "newPublicKey", "info", "ephemeralKeypair", "salt", "kek", "deriveKey", "contentKeyBytes", "exported", "iv", "wrappedKeyBuffer", "ephemeralPubKeyBuffer", "saltBuf", "ivBuf", "wrappedBuf", "combinedSize", "combined", "enc", "wrappedKey", "ephemeralPubKey", "importPublicKey", "ciphertext", "content", "recipient", "aesKey", "keysize", "_publicKey", "key", "plaintext", "ephemeralPubKeyBuf", "saltBuffer", "ivBuffer", "cipherBuf", "size", "result", "encrypted", "msg", "aesAlgorithm", "ephemeralPublicKey", "privateKey", "dec", "pub", "_charsize", "encoder", "signature", "__publicField", "EccKeys", "keypair", "base64Key", "curve", "use", "alg", "uses", "buf", "algorithm", "ecc_default", "verify", "sig", "signingDid", "_key", "rawKeyBytes", "sharedSecret", "hkdfBaseKey"]
4
+ "sourcesContent": ["import { 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 WRAP_FORMAT_VERSION,\n AES_GCM_TAG_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 } from '../_base.js'\nimport { AES } from '../aes/index.js'\n\nconst webcrypto = globalThis.crypto\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 {{ dbKey, exchangeKeys, writeKeys }} [keys] Key options.\n * `dbKey` prefixes the IndexedDB names used for both keypairs.\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 dbKey?:string,\n exchangeKeys?:CryptoKeyPair|null,\n writeKeys?:CryptoKeyPair|null,\n }\n ):Promise<T> {\n return await super.create<T>(session, extractable, keys)\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 * Saves the keys to `indexedDB` before returning, unless you pass\n * `{ persist: false }`.\n *\n * @param {{ dbKey }} [opts] Prefix for both IndexedDB key names.\n */\n static async load<T extends AbstractKeys = EccKeys> (\n this:typeof EccKeys,\n opts:Partial<{\n dbKey:string,\n encryptionKeyName:string,\n writeKeyName:string,\n session:boolean,\n extractable:boolean,\n persist:boolean,\n }> = {\n session: false,\n }\n ):Promise<T> {\n return super.load(opts) 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 * The result is signed with our Ed25519 write key, so the recipient\n * can verify who created the wrap. `unwrap` requires our DID and\n * rejects the wrap unless the signature matches it.\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),\n * the wrapped AES key (base64), and a signature (base64) by\n * our write key.\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. Only the public half is\n // ever exported, so the private half does not need to be\n // extractable.\n const ephemeralKeypair = await EccKeys._createExchangeKeys(false)\n\n // 2. Export the ephemeral and recipient public keys up front, so\n // they can be bound into the KEK derivation below (HPKE-style)\n const ephemeralPubKeyBuffer = await exportPublicKey(ephemeralKeypair)\n const ephemeralPubKeyBytes = new Uint8Array(ephemeralPubKeyBuffer)\n const recipientPubKey = new Uint8Array(\n await webcrypto.subtle.exportKey('raw', newPublicKey)\n )\n const baseInfo = info || 'key-wrap'\n\n // 3. Generate random salt for HKDF\n const salt = webcrypto.getRandomValues(new Uint8Array(SALT_LENGTH))\n\n // 4. Derive KEK using ECDH + HKDF with ephemeral private key and\n // recipient's public key. The HKDF `info` binds the ephemeral and\n // recipient public keys into the derivation, so a KEK can't be\n // replayed against a different ephemeral/recipient pairing.\n const kek = await deriveKey(\n ephemeralKeypair.privateKey,\n newPublicKey,\n salt,\n wrapKekInfo(ephemeralPubKeyBytes, recipientPubKey, baseInfo)\n )\n\n // 5. Prepare the content key for encryption. Buffers we allocate\n // ourselves (from a CryptoKey export or a base64 string) are\n // zeroed below once no longer needed; a caller-supplied\n // Uint8Array is left alone, since zeroing it would mutate memory\n // the caller still owns a reference to.\n let contentKeyBytes:Uint8Array\n let ownsContentKeyBytes = false\n if (contentKey instanceof CryptoKey) {\n // Export the AES key to raw format\n const exported = await webcrypto.subtle.exportKey('raw', contentKey)\n contentKeyBytes = new Uint8Array(exported)\n ownsContentKeyBytes = true\n } else if (typeof contentKey === 'string') {\n contentKeyBytes = fromString(contentKey, 'base64pad')\n ownsContentKeyBytes = true\n } else {\n contentKeyBytes = contentKey\n }\n\n // 6. Generate IV for AES-GCM encryption\n const iv = webcrypto.getRandomValues(new Uint8Array(IV_LENGTH))\n\n // 7. Encrypt the content key with the KEK\n const wrappedKeyBuffer = await webcrypto.subtle.encrypt(\n { name: DEFAULT_SYMM_ALGORITHM, iv },\n kek,\n toArrayBuffer(contentKeyBytes)\n )\n if (ownsContentKeyBytes) contentKeyBytes.fill(0)\n\n // 8. Combine version + salt + iv + wrapped key for the final\n // wrapped key blob. The version byte lets future format or\n // algorithm changes be detected in `unwrap` instead of silently\n // misparsed.\n const ivBuf = new Uint8Array(iv)\n const wrappedBuf = new Uint8Array(wrappedKeyBuffer)\n const combinedSize = 1 + SALT_LENGTH + ivBuf.length + wrappedBuf.length\n const combined = new Uint8Array(combinedSize)\n combined[0] = WRAP_FORMAT_VERSION\n combined.set(salt, 1)\n combined.set(ivBuf, 1 + SALT_LENGTH)\n combined.set(wrappedBuf, 1 + SALT_LENGTH + ivBuf.length)\n\n // 9. Sign the wrap with our write key, binding the ephemeral\n // public key, the recipient, the blob, and the info string\n const signData = wrapSignData(\n ephemeralPubKeyBytes,\n recipientPubKey,\n combined,\n baseInfo\n )\n const signature = await this.sign(signData)\n\n // 10. Return base64-encoded results\n return {\n enc: toBase64(ephemeralPubKeyBytes),\n wrappedKey: toBase64(combined),\n signature: toString(signature, 'base64pad')\n }\n }\n\n /**\n * Unwrap a content key that another device wrapped for this device\n * with `wrap`.\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 * The wrap's signature is always checked against `signer` before\n * anything is decrypted, and this throws if the signature is missing\n * or invalid. `signer` must be the DID of the device you expect the\n * key from, obtained over a channel an attacker cannot tamper with.\n * A DID that travels alongside the wrapped key proves nothing, since\n * an attacker who can swap the wrapped key can swap the DID too.\n *\n * @param wrapped The `{ enc, wrappedKey, signature }` object returned\n * by `wrap`.\n * @param signer The DID of the expected sender.\n * @param opts.info The HKDF info string. Must match what was passed to\n * `wrap`. Defaults to 'key-wrap'.\n * @param opts.extractable Can the returned key be exported with\n * `crypto.subtle.exportKey`? Default `true`.\n * @returns {Promise<CryptoKey>} The unwrapped AES content key.\n */\n async unwrap (\n wrapped:WrappedKey,\n signer:DID,\n opts:{ info?:string, extractable?:boolean } = {}\n ):Promise<CryptoKey> {\n const { enc, wrappedKey, signature } = wrapped\n const info = opts.info\n const extractable = opts.extractable ?? true\n\n // Fail closed for JS callers, or anyone who casts around the\n // types: an unsigned or unattributed wrap is never accepted.\n if (!signer) {\n throw new Error('`unwrap` requires the DID of the sender')\n }\n if (!signature) {\n throw new Error('The wrapped key is not signed')\n }\n\n // 1. Decode and validate the ephemeral public key and wrapped\n // key blob up front, so truncated/malformed input fails with a\n // clear error instead of an opaque `OperationError` deep inside\n // WebCrypto.\n const encBytes = fromString(enc, 'base64pad')\n if (encBytes.length !== X25519_PUBLIC_KEY_LENGTH) {\n throw new Error(\n `\\`enc\\` must be a ${X25519_PUBLIC_KEY_LENGTH}-byte ` +\n `X25519 public key, got ${encBytes.length} bytes`\n )\n }\n\n const wrappedBuf = new Uint8Array(base64ToArrBuf(wrappedKey))\n const baseInfo = info || 'key-wrap'\n const minWrappedLength = 1 + SALT_LENGTH + IV_LENGTH + AES_GCM_TAG_LENGTH\n if (wrappedBuf.length < minWrappedLength) {\n throw new Error(\n `Wrapped key must be at least ${minWrappedLength} bytes, ` +\n `got ${wrappedBuf.length} bytes`\n )\n }\n\n // 2. Check the format version, so a future format/algorithm\n // change can be detected instead of silently misparsed\n const version = wrappedBuf[0]\n if (version !== WRAP_FORMAT_VERSION) {\n throw new Error(\n `Unsupported wrapped key format version: ${version}`\n )\n }\n\n const ourPubKeyBytes = new Uint8Array(\n await exportPublicKey(this.exchangeKey)\n )\n\n // 3. Verify the sender's signature before decrypting anything\n const signData = wrapSignData(\n encBytes,\n ourPubKeyBytes,\n wrappedBuf,\n baseInfo\n )\n const isValid = await verify(signData, signature, signer)\n if (!isValid) {\n throw new Error('Invalid signature for the wrapped key')\n }\n\n // 4. Import the ephemeral public key\n const ephemeralPubKey = await importPublicKey(\n enc,\n EccCurve.X25519,\n KeyUse.Exchange\n )\n\n // 5. Extract salt, iv, and ciphertext (after the version byte)\n const salt = wrappedBuf.slice(1, 1 + SALT_LENGTH)\n const iv = wrappedBuf.slice(\n 1 + SALT_LENGTH,\n 1 + SALT_LENGTH + IV_LENGTH\n )\n const ciphertext = wrappedBuf.slice(1 + SALT_LENGTH + IV_LENGTH)\n\n // 6. Derive the same KEK using our private key and the ephemeral\n // public key. The HKDF `info` must match what `wrap` bound in:\n // the ephemeral public key + our own (recipient) public key.\n const kek = await deriveKey(\n this.exchangeKey.privateKey,\n ephemeralPubKey,\n salt,\n wrapKekInfo(encBytes, ourPubKeyBytes, baseInfo)\n )\n\n // 7. Decrypt the wrapped key\n const contentKeyBytes = await webcrypto.subtle.decrypt(\n { name: DEFAULT_SYMM_ALGORITHM, iv },\n kek,\n toArrayBuffer(ciphertext)\n )\n\n // 8. Import the content key back as a CryptoKey\n const contentKey = await webcrypto.subtle.importKey(\n 'raw',\n contentKeyBytes,\n { name: DEFAULT_SYMM_ALGORITHM },\n extractable,\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] Use this exact AES key\n * instead of deriving one from ECDH. Not relevant for most use\n * cases. Pass the same key to `decrypt` to read it back.\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 = webcrypto.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. Only the\n // public half is ever exported, so the private half does not need\n // to be extractable.\n const ephemeralKeypair = await EccKeys._createExchangeKeys(false)\n\n // honor a caller-supplied key end to end; otherwise derive one\n // using the ephemeral private key\n const key = aesKey ?\n (aesKey instanceof CryptoKey ? aesKey : await AES.import(aesKey)) :\n await deriveKey(\n ephemeralKeypair.privateKey, // use ephemeral private key\n publicKey,\n salt,\n info || EccKeys.INFO,\n keysize\n )\n\n const iv = webcrypto.getRandomValues(new Uint8Array(IV_LENGTH))\n const plaintext:Uint8Array = (typeof content === 'string' ?\n new TextEncoder().encode(content) :\n content)\n\n const ciphertext = await webcrypto.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 * @param {SymmKey|Uint8Array|string} [aesKey] Use this exact AES key\n * instead of deriving one from ECDH. Must match the `aesKey`\n * passed to the corresponding `encrypt` call.\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 aesKey?:SymmKey|Uint8Array|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 // honor a caller-supplied key end to end; otherwise derive one\n // with our private key + the ephemeral public key\n const { privateKey } = this.exchangeKey\n const key = aesKey ?\n (aesKey instanceof CryptoKey ? aesKey : await AES.import(aesKey)) :\n 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 webcrypto.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 aesKey?:SymmKey|Uint8Array|string|null,\n ):Promise<string> {\n const dec = await this.decrypt(msg, aesAlgorithm, info, aesKey)\n return toString(new Uint8Array(dec))\n }\n\n /**\n * Do DHKE, create a new AES-GCM key.\n *\n * The HKDF salt is either supplied by the caller (so both sides can\n * re-derive the exact same key later) or generated at random, in\n * which case it is returned as a `.salt` (base64) property on the\n * key so the caller can persist it for later re-derivation.\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 * @param {Uint8Array|ArrayBuffer|string|null} [salt] Reuse this salt\n * instead of generating a random one -- pass the same salt on\n * both sides to re-derive the same key.\n * @returns {CryptoKey} New AES key, with a `.salt` (base64) property\n */\n async getAesKey (\n publicKey?:CryptoKey|string|null,\n info?:string|null,\n salt?:Uint8Array|ArrayBuffer|string|null,\n ):Promise<CryptoKey & { salt:string }> {\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 // Reuse the given salt, or generate a random one for HKDF\n const saltBytes:Uint8Array = (salt ?\n new Uint8Array(\n typeof salt === 'string' ? base64ToArrBuf(salt) : salt\n ) :\n webcrypto.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 saltBytes,\n info || EccKeys.INFO\n )\n\n // expose the salt used, so a randomly-generated one isn't lost\n return Object.assign(aesKey, { salt: toBase64(saltBytes) })\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 webcrypto.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 * Build the HKDF `info` used to derive a `wrap`/`unwrap` KEK: the\n * ephemeral public key + recipient public key + the caller's info string\n * (HPKE-style). Binding both public keys into the derivation means a KEK\n * can only ever be reconstructed for this exact ephemeral/recipient\n * pairing. The two public keys are fixed-length X25519 keys, so they\n * can't be shifted into each other or into the trailing, variable-length\n * info string.\n */\nfunction wrapKekInfo (\n ephemeralPubKey:Uint8Array,\n recipientPubKey:Uint8Array,\n info:string\n):Uint8Array {\n const infoBytes = new TextEncoder().encode(info)\n const data = new Uint8Array(\n ephemeralPubKey.length + recipientPubKey.length + infoBytes.length\n )\n data.set(ephemeralPubKey, 0)\n data.set(recipientPubKey, ephemeralPubKey.length)\n data.set(infoBytes, ephemeralPubKey.length + recipientPubKey.length)\n return data\n}\n\n/**\n * Build the message that `wrap` signs and `unwrap` verifies:\n * ephemeral public key + recipient public key + wrapped key blob + info.\n * The blob gets a length prefix so variable-length fields can't be\n * shifted into each other.\n */\nfunction wrapSignData (\n ephemeralPubKey:Uint8Array,\n recipientPubKey:Uint8Array,\n wrappedBlob:Uint8Array,\n info:string\n):Uint8Array {\n const infoBytes = new TextEncoder().encode(info)\n const blobLength = new Uint8Array(4)\n new DataView(blobLength.buffer).setUint32(0, wrappedBlob.length)\n\n const data = new Uint8Array(\n ephemeralPubKey.length + recipientPubKey.length +\n blobLength.length + wrappedBlob.length + infoBytes.length\n )\n let offset = 0\n data.set(ephemeralPubKey, offset)\n offset += ephemeralPubKey.length\n data.set(recipientPubKey, offset)\n offset += recipientPubKey.length\n data.set(blobLength, offset)\n offset += blobLength.length\n data.set(wrappedBlob, offset)\n offset += wrappedBlob.length\n data.set(infoBytes, offset)\n\n return data\n}\n\n/**\n * Derive an AES key from X25519 keypair via ECDH + HKDF.\n * @param {string|Uint8Array} info Passing a `Uint8Array` lets callers bind\n * extra transcript data (e.g. the ephemeral and recipient public keys)\n * into the HKDF `info` field, HPKE-style.\n */\nasync function deriveKey (\n privateKey:CryptoKey,\n publicKey:CryptoKey,\n salt:Uint8Array|ArrayBuffer,\n info:string|Uint8Array,\n keysize?:number|null\n):Promise<CryptoKey> {\n const encoder = new TextEncoder()\n const infoBytes = typeof info === 'string' ? encoder.encode(info) : info\n const sharedSecret = await webcrypto.subtle.deriveBits(\n { name: 'X25519', public: publicKey },\n privateKey,\n 256\n )\n\n const hkdfBaseKey = await webcrypto.subtle.importKey(\n 'raw',\n sharedSecret,\n 'HKDF',\n false,\n ['deriveKey']\n )\n\n return webcrypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: salt instanceof Uint8Array ? toArrayBuffer(salt) : salt,\n info: toArrayBuffer(infoBytes)\n },\n hkdfBaseKey,\n { name: 'AES-GCM', length: keysize || DEFAULT_SYMM_LENGTH },\n false,\n ['encrypt', 'decrypt']\n )\n}\n"],
5
+ "mappings": "omBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,YAAAC,EAAA,oBAAAC,EAAA,oBAAAC,EAAA,WAAAC,IAAA,eAAAC,EAAAP,GAAA,IAAAQ,EAA8D,uBAC9DC,EAYO,2BACPC,EAUO,uBACPC,EAKO,sBACPC,EAAiC,wBACjCC,EAA6B,uBAC7BC,EAAoB,2BAEpB,MAAMC,EAAY,WAAW,OAG7B,SAASC,EAAeC,EAA6B,CACjD,OAAO,IAAI,WAAWA,CAAI,EAAE,MAChC,CAFSC,EAAAF,EAAA,iBAOF,MAAMG,EAAN,MAAMA,UAAgB,cAAa,CAgBtC,aAAa,OACTC,EACAC,EACAC,EAKS,CACT,OAAO,MAAM,MAAM,OAAUF,EAASC,EAAaC,CAAI,CAC3D,CAEA,IAAI,mBAAqB,CACrB,MAAMC,EAAY,KAAK,YAAY,UACnC,OAAO,OAAO,OAAOA,EAAW,CAC5B,SAAUL,EAAA,MAAOM,GAAiD,CAC9D,MAAMC,EAAc,MAAMC,EAAgB,KAAK,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EAChCA,GAAUvE,EAAgB,OAC1BpB,EAAK,IAAI0F,EAAYC,CAAM,EAC3BA,GAAUD,EAAW,OACrB1F,EAAK,IAAIyF,EAAaE,CAAM,EAC5BA,GAAUF,EAAY,OACtBzF,EAAK,IAAIwF,EAAWG,CAAM,EAEnB3F,CACX,CA1BSC,EAAAmC,EAAA,gBAkCT,eAAeZ,EACX2C,EACA7D,EACAgB,EACAN,EACAqC,EACiB,CACjB,MAAMmB,EAAU,IAAI,YACdgB,EAAY,OAAOxE,GAAS,SAAWwD,EAAQ,OAAOxD,CAAI,EAAIA,EAC9D4E,EAAe,MAAM9F,EAAU,OAAO,WACxC,CAAE,KAAM,SAAU,OAAQQ,CAAU,EACpC6D,EACA,GACJ,EAEM0B,EAAc,MAAM/F,EAAU,OAAO,UACvC,MACA8F,EACA,OACA,GACA,CAAC,WAAW,CAChB,EAEA,OAAO9F,EAAU,OAAO,UACpB,CACI,KAAM,OACN,KAAM,UACN,KAAMwB,aAAgB,WAAavB,EAAcuB,CAAI,EAAIA,EACzD,KAAMvB,EAAcyF,CAAS,CACjC,EACAK,EACA,CAAE,KAAM,UAAW,OAAQxC,GAAW,qBAAoB,EAC1D,GACA,CAAC,UAAW,SAAS,CACzB,CACJ,CAnCepD,EAAAuB,EAAA",
6
+ "names": ["ecc_exports", "__export", "EccKeys", "ecc_default", "exportPublicKey", "importPublicKey", "verify", "__toCommonJS", "import_uint8arrays", "import_constants", "import_types", "import_util", "import_errors", "import_base", "import_aes", "webcrypto", "toArrayBuffer", "data", "__name", "_EccKeys", "session", "extractable", "keys", "publicKey", "format", "arrayBuffer", "exportPublicKey", "uint8Array", "opts", "did", "rawKey", "contentKey", "newPublicKey", "info", "ephemeralKeypair", "ephemeralPubKeyBuffer", "ephemeralPubKeyBytes", "recipientPubKey", "baseInfo", "salt", "kek", "deriveKey", "wrapKekInfo", "contentKeyBytes", "ownsContentKeyBytes", "exported", "iv", "wrappedKeyBuffer", "ivBuf", "wrappedBuf", "combinedSize", "combined", "signData", "wrapSignData", "signature", "wrapped", "signer", "enc", "wrappedKey", "encBytes", "minWrappedLength", "version", "ourPubKeyBytes", "verify", "ephemeralPubKey", "importPublicKey", "ciphertext", "content", "recipient", "aesKey", "keysize", "_publicKey", "key", "plaintext", "ephemeralPubKeyBuf", "saltBuffer", "ivBuffer", "cipherBuf", "size", "result", "encrypted", "msg", "aesAlgorithm", "ephemeralPublicKey", "privateKey", "dec", "pub", "saltBytes", "_charsize", "encoder", "__publicField", "EccKeys", "keypair", "base64Key", "curve", "use", "alg", "uses", "buf", "algorithm", "ecc_default", "sig", "signingDid", "_key", "rawKeyBytes", "infoBytes", "wrappedBlob", "blobLength", "offset", "sharedSecret", "hkdfBaseKey"]
7
7
  }