@substrate-system/keys 0.3.2 → 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 (86) hide show
  1. package/README.md +35 -3
  2. package/dist/_base.cjs +20 -3
  3. package/dist/_base.cjs.map +2 -2
  4. package/dist/_base.d.ts +9 -1
  5. package/dist/_base.d.ts.map +1 -1
  6. package/dist/_base.js +20 -3
  7. package/dist/_base.js.map +2 -2
  8. package/dist/_base.min.cjs +1 -1
  9. package/dist/_base.min.cjs.map +3 -3
  10. package/dist/_base.min.js +2 -2
  11. package/dist/_base.min.js.map +3 -3
  12. package/dist/aes/index.cjs +14 -7
  13. package/dist/aes/index.cjs.map +2 -2
  14. package/dist/aes/index.d.ts +11 -3
  15. package/dist/aes/index.d.ts.map +1 -1
  16. package/dist/aes/index.js +14 -7
  17. package/dist/aes/index.js.map +2 -2
  18. package/dist/aes/index.min.cjs +1 -1
  19. package/dist/aes/index.min.cjs.map +3 -3
  20. package/dist/aes/index.min.js +2 -2
  21. package/dist/aes/index.min.js.map +3 -3
  22. package/dist/browser/index.js +244 -110
  23. package/dist/browser/index.min.js +2 -2
  24. package/dist/constants.cjs +4 -0
  25. package/dist/constants.cjs.map +2 -2
  26. package/dist/constants.d.ts +6 -0
  27. package/dist/constants.d.ts.map +1 -1
  28. package/dist/constants.js +4 -0
  29. package/dist/constants.js.map +2 -2
  30. package/dist/constants.min.cjs +1 -1
  31. package/dist/constants.min.cjs.map +3 -3
  32. package/dist/constants.min.js +1 -1
  33. package/dist/constants.min.js.map +3 -3
  34. package/dist/crypto.cjs +9 -7
  35. package/dist/crypto.cjs.map +2 -2
  36. package/dist/crypto.d.ts +6 -0
  37. package/dist/crypto.d.ts.map +1 -1
  38. package/dist/crypto.js +9 -8
  39. package/dist/crypto.js.map +2 -2
  40. package/dist/crypto.min.cjs +2 -2
  41. package/dist/crypto.min.cjs.map +2 -2
  42. package/dist/crypto.min.js +2 -2
  43. package/dist/crypto.min.js.map +3 -3
  44. package/dist/ecc/index.cjs +176 -72
  45. package/dist/ecc/index.cjs.map +2 -2
  46. package/dist/ecc/index.d.ts +47 -13
  47. package/dist/ecc/index.d.ts.map +1 -1
  48. package/dist/ecc/index.js +179 -73
  49. package/dist/ecc/index.js.map +2 -2
  50. package/dist/ecc/index.min.cjs +1 -1
  51. package/dist/ecc/index.min.cjs.map +3 -3
  52. package/dist/ecc/index.min.js +2 -2
  53. package/dist/ecc/index.min.js.map +3 -3
  54. package/dist/errors.min.js +1 -1
  55. package/dist/index.min.js +2 -2
  56. package/dist/index.min.js.map +3 -3
  57. package/dist/meta.json +37 -30
  58. package/dist/rsa/index.cjs +15 -16
  59. package/dist/rsa/index.cjs.map +2 -2
  60. package/dist/rsa/index.d.ts +6 -1
  61. package/dist/rsa/index.d.ts.map +1 -1
  62. package/dist/rsa/index.js +15 -17
  63. package/dist/rsa/index.js.map +2 -2
  64. package/dist/rsa/index.min.cjs +1 -1
  65. package/dist/rsa/index.min.cjs.map +3 -3
  66. package/dist/rsa/index.min.js +2 -2
  67. package/dist/rsa/index.min.js.map +3 -3
  68. package/dist/types.cjs.map +2 -2
  69. package/dist/types.d.ts +11 -0
  70. package/dist/types.d.ts.map +1 -1
  71. package/dist/types.js.map +2 -2
  72. package/dist/types.min.cjs +1 -1
  73. package/dist/types.min.cjs.map +2 -2
  74. package/dist/types.min.js +1 -1
  75. package/dist/types.min.js.map +2 -2
  76. package/dist/util.cjs +6 -4
  77. package/dist/util.cjs.map +2 -2
  78. package/dist/util.d.ts +4 -0
  79. package/dist/util.d.ts.map +1 -1
  80. package/dist/util.js +6 -4
  81. package/dist/util.js.map +2 -2
  82. package/dist/util.min.cjs +1 -1
  83. package/dist/util.min.cjs.map +3 -3
  84. package/dist/util.min.js +1 -1
  85. package/dist/util.min.js.map +3 -3
  86. package/package.json +2 -2
@@ -55,6 +55,7 @@
55
55
  var rsa_exports = {};
56
56
  __export(rsa_exports, {
57
57
  AES_GCM: () => AES_GCM,
58
+ AES_GCM_TAG_LENGTH: () => AES_GCM_TAG_LENGTH,
58
59
  BASE58_DID_PREFIX: () => BASE58_DID_PREFIX,
59
60
  BLS_DID_PREFIX: () => BLS_DID_PREFIX,
60
61
  DEFAULT_CHAR_SIZE: () => DEFAULT_CHAR_SIZE,
@@ -79,6 +80,7 @@
79
80
  RSA_SIGN_ALGORITHM: () => RSA_SIGN_ALGORITHM,
80
81
  RsaKeys: () => RsaKeys,
81
82
  SALT_LENGTH: () => SALT_LENGTH,
83
+ WRAP_FORMAT_VERSION: () => WRAP_FORMAT_VERSION,
82
84
  X25519_PUBLIC_KEY_LENGTH: () => X25519_PUBLIC_KEY_LENGTH,
83
85
  encrypt: () => encrypt2,
84
86
  encryptKeyTo: () => encryptKeyTo2,
@@ -1417,6 +1419,7 @@
1417
1419
  var DEFAULT_SYMM_ALGORITHM = AES_GCM;
1418
1420
  var DEFAULT_SYMM_LENGTH = 256;
1419
1421
  var IV_LENGTH = 12;
1422
+ var AES_GCM_TAG_LENGTH = 16;
1420
1423
  var BLS_DID_PREFIX = new Uint8Array([234, 1]);
1421
1424
  var EDWARDS_DID_PREFIX = new Uint8Array([237, 1]);
1422
1425
  var KEY_TYPE = {
@@ -1429,6 +1432,7 @@
1429
1432
  var DEFAULT_ECC_EXCHANGE = "ecc-exchange";
1430
1433
  var DEFAULT_ECC_WRITE = "ecc-write";
1431
1434
  var SALT_LENGTH = 16;
1435
+ var WRAP_FORMAT_VERSION = 1;
1432
1436
 
1433
1437
  // src/util.ts
1434
1438
  var webcrypto = globalThis.crypto;
@@ -1439,9 +1443,11 @@
1439
1443
  }
1440
1444
  __name(toArrayBuffer, "toArrayBuffer");
1441
1445
  async function sha2562(bytes) {
1442
- return new Uint8Array(
1443
- await webcrypto.subtle.digest("sha-256", bytes.buffer)
1446
+ const buf = bytes.buffer.slice(
1447
+ bytes.byteOffset,
1448
+ bytes.byteOffset + bytes.byteLength
1444
1449
  );
1450
+ return new Uint8Array(await webcrypto.subtle.digest("sha-256", buf));
1445
1451
  }
1446
1452
  __name(sha2562, "sha256");
1447
1453
  function base64ToArrBuf(string2) {
@@ -1464,7 +1470,7 @@
1464
1470
  }
1465
1471
  __name(normalizeBase64ToBuf, "normalizeBase64ToBuf");
1466
1472
  var normalizeUtf8ToBuf = /* @__PURE__ */ __name((msg) => {
1467
- return normalizeToBuf(msg, (str) => strToArrBuf(str, 8 /* B8 */));
1473
+ return normalizeToBuf(msg, (str) => toArrayBuffer(new TextEncoder().encode(str)));
1468
1474
  }, "normalizeUtf8ToBuf");
1469
1475
  function strToArrBuf(str, charSize) {
1470
1476
  const view = charSize === 8 ? new Uint8Array(str.length) : new Uint16Array(str.length);
@@ -1552,7 +1558,7 @@
1552
1558
  name: opts?.alg || DEFAULT_SYMM_ALGORITHM,
1553
1559
  length: opts?.length || DEFAULT_SYMM_LENGTH
1554
1560
  },
1555
- true,
1561
+ opts?.extractable ?? true,
1556
1562
  ["encrypt", "decrypt"]
1557
1563
  );
1558
1564
  }
@@ -1719,8 +1725,7 @@
1719
1725
  verify: /* @__PURE__ */ __name(async function rsaVerify2(msg, sig, publicKey, charSize = DEFAULT_CHAR_SIZE, hashAlg = DEFAULT_HASH_ALGORITHM) {
1720
1726
  return webcrypto2.subtle.verify(
1721
1727
  {
1722
- name: RSA_SIGN_ALGORITHM,
1723
- saltLength: SALT_LENGTH
1728
+ name: RSA_SIGN_ALGORITHM
1724
1729
  },
1725
1730
  typeof publicKey === "string" ? await rsaImportPublicKey(publicKey, hashAlg, "signing" /* Sign */) : publicKey,
1726
1731
  normalizeBase64ToBuf(sig),
@@ -1729,7 +1734,7 @@
1729
1734
  }, "rsaVerify"),
1730
1735
  sign: /* @__PURE__ */ __name(async function sign(msg, privateKey, charSize = DEFAULT_CHAR_SIZE) {
1731
1736
  return webcrypto2.subtle.sign(
1732
- { name: RSA_SIGN_ALGORITHM, saltLength: SALT_LENGTH },
1737
+ { name: RSA_SIGN_ALGORITHM },
1733
1738
  privateKey,
1734
1739
  normalizeUnicodeToBuf(msg, charSize)
1735
1740
  );
@@ -1801,6 +1806,9 @@
1801
1806
  }
1802
1807
  __name(stripKeyHeader, "stripKeyHeader");
1803
1808
  function isCryptoKey(val) {
1809
+ if (typeof CryptoKey !== "undefined") {
1810
+ return val instanceof CryptoKey;
1811
+ }
1804
1812
  return hasProp(val, "algorithm") && hasProp(val, "extractable") && hasProp(val, "type");
1805
1813
  }
1806
1814
  __name(isCryptoKey, "isCryptoKey");
@@ -1841,8 +1849,8 @@
1841
1849
  const magicalBuf = fromString2(didWithoutPrefix, "base58btc");
1842
1850
  const result = Object.entries(did.keyTypes).find(
1843
1851
  ([_key, attr]) => hasPrefix(
1844
- magicalBuf.buffer,
1845
- attr.magicBytes.buffer
1852
+ toArrayBuffer(magicalBuf),
1853
+ toArrayBuffer(attr.magicBytes)
1846
1854
  )
1847
1855
  );
1848
1856
  if (!result) throw new Error("Invalid key type");
@@ -1877,8 +1885,8 @@
1877
1885
  const magicalBuf = fromString2(didWithoutPrefix, "base58btc");
1878
1886
  const result = Object.entries(did.keyTypes).find(
1879
1887
  ([_key, attr]) => hasPrefix(
1880
- magicalBuf.buffer,
1881
- attr.magicBytes.buffer
1888
+ toArrayBuffer(magicalBuf),
1889
+ toArrayBuffer(attr.magicBytes)
1882
1890
  )
1883
1891
  );
1884
1892
  if (!result) throw new Error("Unsupported key algorithm.");
@@ -1902,7 +1910,9 @@
1902
1910
  /**
1903
1911
  * Factory function -- create a new AES key. Defaults are `AES-GCM`
1904
1912
  * algorithm and 12 bytes `iv` size.
1905
- * @param {{ alg?:string, lenght?:number }} opts Algorithm and key size.
1913
+ * @param {{ alg?:string, length?:number, extractable?:boolean }} opts
1914
+ * Algorithm, key size, and whether the key can be exported with
1915
+ * `crypto.subtle.exportKey`. `extractable` defaults to `true`.
1906
1916
  * @returns {Promise<CryptoKey>}
1907
1917
  */
1908
1918
  create(opts = {
@@ -1911,10 +1921,11 @@
1911
1921
  }) {
1912
1922
  const length2 = opts.length || DEFAULT_SYMM_LENGTH;
1913
1923
  const alg = opts.alg || DEFAULT_SYMM_ALGORITHM;
1924
+ const extractable = opts.extractable ?? true;
1914
1925
  return webcrypto3.subtle.generateKey({
1915
1926
  name: alg,
1916
1927
  length: length2
1917
- }, true, ["encrypt", "decrypt"]);
1928
+ }, extractable, ["encrypt", "decrypt"]);
1918
1929
  },
1919
1930
  /**
1920
1931
  * key.export -> return a Uint8Array of the key
@@ -1932,8 +1943,12 @@
1932
1943
  }, "asString")
1933
1944
  }
1934
1945
  ),
1935
- import(key) {
1936
- return importAesKey(typeof key === "string" ? base64ToArrBuf(key) : key);
1946
+ import(key, extractable) {
1947
+ return importAesKey(
1948
+ typeof key === "string" ? base64ToArrBuf(key) : key,
1949
+ void 0,
1950
+ extractable
1951
+ );
1937
1952
  },
1938
1953
  async exportAsString(key) {
1939
1954
  const raw = await AES.export(key);
@@ -1948,12 +1963,12 @@
1948
1963
  iv: toArrayBuffer(iv)
1949
1964
  },
1950
1965
  key,
1951
- typeof encryptedData === "string" ? toArrayBuffer(fromString2(encryptedData)) : encryptedData instanceof Uint8Array ? toArrayBuffer(encryptedData) : encryptedData
1966
+ typeof encryptedData === "string" ? toArrayBuffer(fromString2(encryptedData, "base64pad")) : encryptedData instanceof Uint8Array ? toArrayBuffer(encryptedData) : encryptedData
1952
1967
  ) : await decryptBytes(encryptedData, key);
1953
1968
  return new Uint8Array(decrypted);
1954
1969
  }
1955
1970
  };
1956
- function importAesKey(key, length2) {
1971
+ function importAesKey(key, length2, extractable = true) {
1957
1972
  return webcrypto3.subtle.importKey(
1958
1973
  "raw",
1959
1974
  key instanceof Uint8Array ? toArrayBuffer(key) : key,
@@ -1961,7 +1976,7 @@
1961
1976
  name: AES_GCM,
1962
1977
  length: length2 || 256 /* B256 */
1963
1978
  },
1964
- true,
1979
+ extractable,
1965
1980
  ["encrypt", "decrypt"]
1966
1981
  );
1967
1982
  }
@@ -2261,6 +2276,19 @@
2261
2276
  static _createWriteKeys(_extractable) {
2262
2277
  throw new Error("The child should implement this");
2263
2278
  }
2279
+ /**
2280
+ * The indexedDB names for this class, optionally prefixed with `dbKey`.
2281
+ * Pure -- never writes to the class statics.
2282
+ */
2283
+ static _keyNames(dbKey) {
2284
+ return dbKey ? {
2285
+ exchangeKeyName: `${dbKey}.${this.EXCHANGE_KEY_NAME}`,
2286
+ writeKeyName: `${dbKey}.${this.WRITE_KEY_NAME}`
2287
+ } : {
2288
+ exchangeKeyName: this.EXCHANGE_KEY_NAME,
2289
+ writeKeyName: this.WRITE_KEY_NAME
2290
+ };
2291
+ }
2264
2292
  static async create(session, extractable, keys) {
2265
2293
  const exchange = keys?.exchangeKeys || await this._createExchangeKeys(
2266
2294
  extractable
@@ -2271,11 +2299,14 @@
2271
2299
  new Uint8Array(publicSigningKey),
2272
2300
  this.TYPE === "ecc" ? "ed25519" : "rsa"
2273
2301
  );
2302
+ const { exchangeKeyName, writeKeyName } = this._keyNames(keys?.dbKey);
2274
2303
  const keysInstance = new this({
2275
2304
  keys: { exchange, write },
2276
2305
  did: did2,
2277
2306
  hasPersisted: false,
2278
- isSessionOnly: !!session
2307
+ isSessionOnly: !!session,
2308
+ exchangeKeyName,
2309
+ writeKeyName
2279
2310
  });
2280
2311
  this._instance = keysInstance;
2281
2312
  return keysInstance;
@@ -2305,8 +2336,9 @@
2305
2336
  session: false
2306
2337
  }) {
2307
2338
  const shouldPersist = opts.persist !== false;
2308
- const exchangeKeyName = opts.encryptionKeyName || this.EXCHANGE_KEY_NAME;
2309
- const writeKeyName = opts.writeKeyName || this.WRITE_KEY_NAME;
2339
+ const defaults = this._keyNames(opts.dbKey);
2340
+ const exchangeKeyName = opts.encryptionKeyName || defaults.exchangeKeyName;
2341
+ const writeKeyName = opts.writeKeyName || defaults.writeKeyName;
2310
2342
  const cached = this._instance;
2311
2343
  if (cached && !cached.destroyed && cached.exchangeKeyName === exchangeKeyName && cached.writeKeyName === writeKeyName) {
2312
2344
  if (shouldPersist && !cached.hasPersisted) await cached.persist();
@@ -2386,7 +2418,11 @@
2386
2418
  return new Uint8Array(data).buffer;
2387
2419
  }
2388
2420
  __name(toArrayBuffer2, "toArrayBuffer");
2389
- var RsaKeys = class _RsaKeys extends AbstractKeys {
2421
+ function rsaCiphertextByteLength(rsaKey) {
2422
+ return rsaKey.algorithm.modulusLength / 8;
2423
+ }
2424
+ __name(rsaCiphertextByteLength, "rsaCiphertextByteLength");
2425
+ var RsaKeys = class extends AbstractKeys {
2390
2426
  static {
2391
2427
  __name(this, "RsaKeys");
2392
2428
  }
@@ -2405,12 +2441,6 @@
2405
2441
  * @returns {Promise<RsaKeys>} A new class instance.
2406
2442
  */
2407
2443
  static async create(session, extractable, keys) {
2408
- if (keys?.dbKey) {
2409
- const exchangeKeyName = `${keys.dbKey}.${DEFAULT_RSA_EXCHANGE}`;
2410
- const writeKeyName = `${keys.dbKey}.${DEFAULT_RSA_WRITE}`;
2411
- _RsaKeys.EXCHANGE_KEY_NAME = exchangeKeyName;
2412
- _RsaKeys.WRITE_KEY_NAME = writeKeyName;
2413
- }
2414
2444
  return await super.create(session, extractable, keys);
2415
2445
  }
2416
2446
  /**
@@ -2421,12 +2451,6 @@
2421
2451
  static async load(opts = {
2422
2452
  session: false
2423
2453
  }) {
2424
- if (opts.dbKey) {
2425
- const exchangeKeyName = `${opts.dbKey}.${DEFAULT_RSA_EXCHANGE}`;
2426
- const writeKeyName = `${opts.dbKey}.${DEFAULT_RSA_WRITE}`;
2427
- _RsaKeys.EXCHANGE_KEY_NAME = exchangeKeyName;
2428
- _RsaKeys.WRITE_KEY_NAME = writeKeyName;
2429
- }
2430
2454
  return super.load(opts);
2431
2455
  }
2432
2456
  static async _createExchangeKeys(extractable = false) {
@@ -2510,12 +2534,19 @@
2510
2534
  }
2511
2535
  /**
2512
2536
  * Decrypt the given message. Expects encrypted AES key + encrypted content.
2537
+ *
2538
+ * The RSA-encrypted AES key is always exactly one RSA-modulus-sized
2539
+ * block, so the split point between it and the AES-encrypted content
2540
+ * is derived from this instance's RSA modulus length -- not from the
2541
+ * (unrelated) AES key size.
2513
2542
  */
2514
- async decrypt(msg, keysize, _aesAlgorithm) {
2515
- const keysizeValue = (typeof keysize === "number" ? keysize : void 0) || DEFAULT_SYMM_LENGTH;
2543
+ async decrypt(msg, _keysize, _aesAlgorithm) {
2516
2544
  const cipherText = normalizeToBuf(msg, base64ToArrBuf);
2517
- const key = cipherText.slice(0, keysizeValue);
2518
- const data = cipherText.slice(keysizeValue);
2545
+ const rsaCipherLength = rsaCiphertextByteLength(
2546
+ this.exchangeKey.privateKey
2547
+ );
2548
+ const key = cipherText.slice(0, rsaCipherLength);
2549
+ const data = cipherText.slice(rsaCipherLength);
2519
2550
  const decryptedKey = await this.decryptKey(key);
2520
2551
  const decryptedContent = await AES.decrypt(data, decryptedKey);
2521
2552
  return decryptedContent;
@@ -2689,12 +2720,6 @@
2689
2720
  * @returns {Promise<EccKeys>} A new class instance.
2690
2721
  */
2691
2722
  static async create(session, extractable, keys) {
2692
- if (keys?.dbKey) {
2693
- const exchangeKeyName = `${keys.dbKey}.${DEFAULT_ECC_EXCHANGE}`;
2694
- const writeKeyName = `${keys.dbKey}.${DEFAULT_ECC_WRITE}`;
2695
- _EccKeys.EXCHANGE_KEY_NAME = exchangeKeyName;
2696
- _EccKeys.WRITE_KEY_NAME = writeKeyName;
2697
- }
2698
2723
  return await super.create(session, extractable, keys);
2699
2724
  }
2700
2725
  get publicExchangeKey() {
@@ -2748,12 +2773,6 @@
2748
2773
  static async load(opts = {
2749
2774
  session: false
2750
2775
  }) {
2751
- if (opts.dbKey) {
2752
- const exchangeKeyName = `${opts.dbKey}.${DEFAULT_ECC_EXCHANGE}`;
2753
- const writeKeyName = `${opts.dbKey}.${DEFAULT_ECC_WRITE}`;
2754
- _EccKeys.EXCHANGE_KEY_NAME = exchangeKeyName;
2755
- _EccKeys.WRITE_KEY_NAME = writeKeyName;
2756
- }
2757
2776
  return super.load(opts);
2758
2777
  }
2759
2778
  /**
@@ -2782,89 +2801,167 @@
2782
2801
  * 4. AES-GCM encrypt the content
2783
2802
  * 5. Return the ephemeral public key (encapsulation) + wrapped key
2784
2803
  *
2804
+ * The result is signed with our Ed25519 write key, so the recipient
2805
+ * can verify who created the wrap. `unwrap` requires our DID and
2806
+ * rejects the wrap unless the signature matches it.
2807
+ *
2785
2808
  * @param {SymmKey|Uint8Array|string} contentKey The existing AES key used
2786
2809
  * to encrypt the content. Can be a base64 encoded string.
2787
2810
  * @param {CryptoKey} newPublicKey The new device's public X25519 key.
2788
2811
  * @param {string} [info] Optional info parameter for HKDF.
2789
2812
  * Defaults to 'key-wrap'.
2790
- * @returns {Promise<WrappedKey>} The ephemeral public key (base64) and
2791
- * the wrapped AES key (base64).
2813
+ * @returns {Promise<WrappedKey>} The ephemeral public key (base64),
2814
+ * the wrapped AES key (base64), and a signature (base64) by
2815
+ * our write key.
2792
2816
  */
2793
2817
  async wrap(contentKey, newPublicKey, info) {
2794
- const ephemeralKeypair = await _EccKeys._createExchangeKeys(true);
2795
- const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
2818
+ const ephemeralKeypair = await _EccKeys._createExchangeKeys(false);
2819
+ const ephemeralPubKeyBuffer = await exportPublicKey(ephemeralKeypair);
2820
+ const ephemeralPubKeyBytes = new Uint8Array(ephemeralPubKeyBuffer);
2821
+ const recipientPubKey = new Uint8Array(
2822
+ await webcrypto5.subtle.exportKey("raw", newPublicKey)
2823
+ );
2824
+ const baseInfo = info || "key-wrap";
2825
+ const salt = webcrypto5.getRandomValues(new Uint8Array(SALT_LENGTH));
2796
2826
  const kek = await deriveKey(
2797
2827
  ephemeralKeypair.privateKey,
2798
2828
  newPublicKey,
2799
2829
  salt,
2800
- info || "key-wrap"
2830
+ wrapKekInfo(ephemeralPubKeyBytes, recipientPubKey, baseInfo)
2801
2831
  );
2802
2832
  let contentKeyBytes;
2833
+ let ownsContentKeyBytes = false;
2803
2834
  if (contentKey instanceof CryptoKey) {
2804
- const exported = await crypto.subtle.exportKey("raw", contentKey);
2835
+ const exported = await webcrypto5.subtle.exportKey("raw", contentKey);
2805
2836
  contentKeyBytes = new Uint8Array(exported);
2837
+ ownsContentKeyBytes = true;
2806
2838
  } else if (typeof contentKey === "string") {
2807
2839
  contentKeyBytes = fromString2(contentKey, "base64pad");
2840
+ ownsContentKeyBytes = true;
2808
2841
  } else {
2809
2842
  contentKeyBytes = contentKey;
2810
2843
  }
2811
- const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
2812
- const wrappedKeyBuffer = await crypto.subtle.encrypt(
2844
+ const iv = webcrypto5.getRandomValues(new Uint8Array(IV_LENGTH));
2845
+ const wrappedKeyBuffer = await webcrypto5.subtle.encrypt(
2813
2846
  { name: DEFAULT_SYMM_ALGORITHM, iv },
2814
2847
  kek,
2815
2848
  toArrayBuffer3(contentKeyBytes)
2816
2849
  );
2817
- const ephemeralPubKeyBuffer = await exportPublicKey(ephemeralKeypair);
2818
- const saltBuf = new Uint8Array(salt);
2850
+ if (ownsContentKeyBytes) contentKeyBytes.fill(0);
2819
2851
  const ivBuf = new Uint8Array(iv);
2820
2852
  const wrappedBuf = new Uint8Array(wrappedKeyBuffer);
2821
- const combinedSize = saltBuf.length + ivBuf.length + wrappedBuf.length;
2853
+ const combinedSize = 1 + SALT_LENGTH + ivBuf.length + wrappedBuf.length;
2822
2854
  const combined = new Uint8Array(combinedSize);
2823
- combined.set(saltBuf, 0);
2824
- combined.set(ivBuf, saltBuf.length);
2825
- combined.set(wrappedBuf, saltBuf.length + ivBuf.length);
2855
+ combined[0] = WRAP_FORMAT_VERSION;
2856
+ combined.set(salt, 1);
2857
+ combined.set(ivBuf, 1 + SALT_LENGTH);
2858
+ combined.set(wrappedBuf, 1 + SALT_LENGTH + ivBuf.length);
2859
+ const signData = wrapSignData(
2860
+ ephemeralPubKeyBytes,
2861
+ recipientPubKey,
2862
+ combined,
2863
+ baseInfo
2864
+ );
2865
+ const signature = await this.sign(signData);
2826
2866
  return {
2827
- enc: toBase64(new Uint8Array(ephemeralPubKeyBuffer)),
2828
- wrappedKey: toBase64(combined)
2867
+ enc: toBase64(ephemeralPubKeyBytes),
2868
+ wrappedKey: toBase64(combined),
2869
+ signature: toString2(signature, "base64pad")
2829
2870
  };
2830
2871
  }
2831
2872
  /**
2832
- * Unwrap a content key that was wrapped for this device using the `add` method.
2873
+ * Unwrap a content key that another device wrapped for this device
2874
+ * with `wrap`.
2833
2875
  *
2834
2876
  * The recipient device uses its private key + the ephemeral public key
2835
2877
  * to rederive the KEK and decrypt the wrapped content key.
2836
2878
  *
2837
- * @param enc The ephemeral public key (base64) from the sender.
2838
- * @param wrappedKey The wrapped content key (base64) - contains salt + iv + ciphertext.
2839
- * @param info Optional info parameter for HKDF. Must match what was used in `add`. Defaults to 'key-wrap'.
2879
+ * The wrap's signature is always checked against `signer` before
2880
+ * anything is decrypted, and this throws if the signature is missing
2881
+ * or invalid. `signer` must be the DID of the device you expect the
2882
+ * key from, obtained over a channel an attacker cannot tamper with.
2883
+ * A DID that travels alongside the wrapped key proves nothing, since
2884
+ * an attacker who can swap the wrapped key can swap the DID too.
2885
+ *
2886
+ * @param wrapped The `{ enc, wrappedKey, signature }` object returned
2887
+ * by `wrap`.
2888
+ * @param signer The DID of the expected sender.
2889
+ * @param opts.info The HKDF info string. Must match what was passed to
2890
+ * `wrap`. Defaults to 'key-wrap'.
2891
+ * @param opts.extractable Can the returned key be exported with
2892
+ * `crypto.subtle.exportKey`? Default `true`.
2840
2893
  * @returns {Promise<CryptoKey>} The unwrapped AES content key.
2841
2894
  */
2842
- async unwrap(enc, wrappedKey, info) {
2895
+ async unwrap(wrapped, signer, opts = {}) {
2896
+ const { enc, wrappedKey, signature } = wrapped;
2897
+ const info = opts.info;
2898
+ const extractable = opts.extractable ?? true;
2899
+ if (!signer) {
2900
+ throw new Error("`unwrap` requires the DID of the sender");
2901
+ }
2902
+ if (!signature) {
2903
+ throw new Error("The wrapped key is not signed");
2904
+ }
2905
+ const encBytes = fromString2(enc, "base64pad");
2906
+ if (encBytes.length !== X25519_PUBLIC_KEY_LENGTH) {
2907
+ throw new Error(
2908
+ `\`enc\` must be a ${X25519_PUBLIC_KEY_LENGTH}-byte X25519 public key, got ${encBytes.length} bytes`
2909
+ );
2910
+ }
2911
+ const wrappedBuf = new Uint8Array(base64ToArrBuf(wrappedKey));
2912
+ const baseInfo = info || "key-wrap";
2913
+ const minWrappedLength = 1 + SALT_LENGTH + IV_LENGTH + AES_GCM_TAG_LENGTH;
2914
+ if (wrappedBuf.length < minWrappedLength) {
2915
+ throw new Error(
2916
+ `Wrapped key must be at least ${minWrappedLength} bytes, got ${wrappedBuf.length} bytes`
2917
+ );
2918
+ }
2919
+ const version = wrappedBuf[0];
2920
+ if (version !== WRAP_FORMAT_VERSION) {
2921
+ throw new Error(
2922
+ `Unsupported wrapped key format version: ${version}`
2923
+ );
2924
+ }
2925
+ const ourPubKeyBytes = new Uint8Array(
2926
+ await exportPublicKey(this.exchangeKey)
2927
+ );
2928
+ const signData = wrapSignData(
2929
+ encBytes,
2930
+ ourPubKeyBytes,
2931
+ wrappedBuf,
2932
+ baseInfo
2933
+ );
2934
+ const isValid = await verify3(signData, signature, signer);
2935
+ if (!isValid) {
2936
+ throw new Error("Invalid signature for the wrapped key");
2937
+ }
2843
2938
  const ephemeralPubKey = await importPublicKey(
2844
2939
  enc,
2845
2940
  "X25519" /* X25519 */,
2846
2941
  "exchange" /* Exchange */
2847
2942
  );
2848
- const wrappedBuf = new Uint8Array(base64ToArrBuf(wrappedKey));
2849
- const salt = wrappedBuf.slice(0, SALT_LENGTH);
2850
- const iv = wrappedBuf.slice(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
2851
- const ciphertext = wrappedBuf.slice(SALT_LENGTH + IV_LENGTH);
2943
+ const salt = wrappedBuf.slice(1, 1 + SALT_LENGTH);
2944
+ const iv = wrappedBuf.slice(
2945
+ 1 + SALT_LENGTH,
2946
+ 1 + SALT_LENGTH + IV_LENGTH
2947
+ );
2948
+ const ciphertext = wrappedBuf.slice(1 + SALT_LENGTH + IV_LENGTH);
2852
2949
  const kek = await deriveKey(
2853
2950
  this.exchangeKey.privateKey,
2854
2951
  ephemeralPubKey,
2855
2952
  salt,
2856
- info || "key-wrap"
2953
+ wrapKekInfo(encBytes, ourPubKeyBytes, baseInfo)
2857
2954
  );
2858
- const contentKeyBytes = await crypto.subtle.decrypt(
2955
+ const contentKeyBytes = await webcrypto5.subtle.decrypt(
2859
2956
  { name: DEFAULT_SYMM_ALGORITHM, iv },
2860
2957
  kek,
2861
2958
  toArrayBuffer3(ciphertext)
2862
2959
  );
2863
- const contentKey = await crypto.subtle.importKey(
2960
+ const contentKey = await webcrypto5.subtle.importKey(
2864
2961
  "raw",
2865
2962
  contentKeyBytes,
2866
2963
  { name: DEFAULT_SYMM_ALGORITHM },
2867
- true,
2964
+ extractable,
2868
2965
  ["encrypt", "decrypt"]
2869
2966
  );
2870
2967
  return contentKey;
@@ -2882,14 +2979,15 @@
2882
2979
  * will use our own public key if not passed in. Can be a CryptoKey
2883
2980
  * or a base64 encoded string.
2884
2981
  * @param {string} [info] info tag for HKDF. Default is the class property.
2885
- * @param {SymmKey|Uint8Array|string} [aesKey] This is not relevant for most
2886
- * use cases.
2982
+ * @param {SymmKey|Uint8Array|string} [aesKey] Use this exact AES key
2983
+ * instead of deriving one from ECDH. Not relevant for most use
2984
+ * cases. Pass the same key to `decrypt` to read it back.
2887
2985
  * @param {SymmKeyLength} [keysize] Default is 256
2888
2986
  * @returns {Promise<ArrayBuffer>} Buffer of ephemeral-public-key + salt +
2889
2987
  * iv + cipher text
2890
2988
  */
2891
2989
  async encrypt(content, recipient, info, aesKey, keysize) {
2892
- const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
2990
+ const salt = webcrypto5.getRandomValues(new Uint8Array(SALT_LENGTH));
2893
2991
  const _publicKey = recipient || this.exchangeKey.publicKey;
2894
2992
  let publicKey;
2895
2993
  if (typeof _publicKey === "string") {
@@ -2901,8 +2999,8 @@
2901
2999
  } else {
2902
3000
  publicKey = _publicKey;
2903
3001
  }
2904
- const ephemeralKeypair = await _EccKeys._createExchangeKeys(true);
2905
- let key = aesKey || await deriveKey(
3002
+ const ephemeralKeypair = await _EccKeys._createExchangeKeys(false);
3003
+ const key = aesKey ? aesKey instanceof CryptoKey ? aesKey : await AES.import(aesKey) : await deriveKey(
2906
3004
  ephemeralKeypair.privateKey,
2907
3005
  // use ephemeral private key
2908
3006
  publicKey,
@@ -2910,18 +3008,9 @@
2910
3008
  info || _EccKeys.INFO,
2911
3009
  keysize
2912
3010
  );
2913
- if (!(key instanceof CryptoKey)) {
2914
- key = await deriveKey(
2915
- ephemeralKeypair.privateKey,
2916
- // use ephemeral private key
2917
- publicKey,
2918
- salt,
2919
- info || _EccKeys.INFO
2920
- );
2921
- }
2922
- const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
3011
+ const iv = webcrypto5.getRandomValues(new Uint8Array(IV_LENGTH));
2923
3012
  const plaintext = typeof content === "string" ? new TextEncoder().encode(content) : content;
2924
- const ciphertext = await crypto.subtle.encrypt(
3013
+ const ciphertext = await webcrypto5.subtle.encrypt(
2925
3014
  { name: DEFAULT_SYMM_ALGORITHM, iv },
2926
3015
  key,
2927
3016
  toArrayBuffer3(plaintext)
@@ -2963,9 +3052,12 @@
2963
3052
  * @param msg The encrypted content
2964
3053
  * @param {string} aesAlgorithm The algorithm. Default is AES-GCM.
2965
3054
  * @param {string} info Custom "info" parameter
3055
+ * @param {SymmKey|Uint8Array|string} [aesKey] Use this exact AES key
3056
+ * instead of deriving one from ECDH. Must match the `aesKey`
3057
+ * passed to the corresponding `encrypt` call.
2966
3058
  * @returns {Promise<ArrayBuffer>} The decrypted content.
2967
3059
  */
2968
- async decrypt(msg, aesAlgorithm, info) {
3060
+ async decrypt(msg, aesAlgorithm, info, aesKey) {
2969
3061
  const encrypted = normalizeToBuf(msg, base64ToArrBuf);
2970
3062
  const ephemeralPubKeyBuf = encrypted.slice(0, X25519_PUBLIC_KEY_LENGTH);
2971
3063
  const ephemeralPublicKey = await webcrypto5.subtle.importKey(
@@ -2987,13 +3079,13 @@
2987
3079
  X25519_PUBLIC_KEY_LENGTH + SALT_LENGTH + IV_LENGTH
2988
3080
  );
2989
3081
  const { privateKey } = this.exchangeKey;
2990
- const key = await deriveKey(
3082
+ const key = aesKey ? aesKey instanceof CryptoKey ? aesKey : await AES.import(aesKey) : await deriveKey(
2991
3083
  privateKey,
2992
3084
  ephemeralPublicKey,
2993
3085
  salt,
2994
3086
  info || _EccKeys.INFO
2995
3087
  );
2996
- const decrypted = await crypto.subtle.decrypt(
3088
+ const decrypted = await webcrypto5.subtle.decrypt(
2997
3089
  {
2998
3090
  name: aesAlgorithm || DEFAULT_SYMM_ALGORITHM,
2999
3091
  iv
@@ -3015,20 +3107,28 @@
3015
3107
  * @param {string} info Custom "info" parameter
3016
3108
  * @returns {Promise<string>} The decrypted content as a string.
3017
3109
  */
3018
- async decryptAsString(msg, aesAlgorithm, info) {
3019
- const dec = await this.decrypt(msg, aesAlgorithm, info);
3110
+ async decryptAsString(msg, aesAlgorithm, info, aesKey) {
3111
+ const dec = await this.decrypt(msg, aesAlgorithm, info, aesKey);
3020
3112
  return toString2(new Uint8Array(dec));
3021
3113
  }
3022
3114
  /**
3023
3115
  * Do DHKE, create a new AES-GCM key.
3024
3116
  *
3117
+ * The HKDF salt is either supplied by the caller (so both sides can
3118
+ * re-derive the exact same key later) or generated at random, in
3119
+ * which case it is returned as a `.salt` (base64) property on the
3120
+ * key so the caller can persist it for later re-derivation.
3121
+ *
3025
3122
  * @param {CryptoKey|string|null} [publicKey] Public key to use in DHKE.
3026
3123
  * Will use our public key if it is not passed in.
3027
3124
  * @param {string} info The info parameter for DHKE. Will use the class
3028
3125
  * property `INFO` if it is not passed in.
3029
- * @returns {CryptoKey} New AES key
3126
+ * @param {Uint8Array|ArrayBuffer|string|null} [salt] Reuse this salt
3127
+ * instead of generating a random one -- pass the same salt on
3128
+ * both sides to re-derive the same key.
3129
+ * @returns {CryptoKey} New AES key, with a `.salt` (base64) property
3030
3130
  */
3031
- async getAesKey(publicKey, info) {
3131
+ async getAesKey(publicKey, info, salt) {
3032
3132
  if (!publicKey) {
3033
3133
  publicKey = this.publicExchangeKey;
3034
3134
  }
@@ -3042,14 +3142,16 @@
3042
3142
  } else {
3043
3143
  pub = publicKey;
3044
3144
  }
3045
- const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
3145
+ const saltBytes = salt ? new Uint8Array(
3146
+ typeof salt === "string" ? base64ToArrBuf(salt) : salt
3147
+ ) : webcrypto5.getRandomValues(new Uint8Array(SALT_LENGTH));
3046
3148
  const aesKey = await deriveKey(
3047
3149
  this.exchangeKey.privateKey,
3048
3150
  pub,
3049
- salt,
3151
+ saltBytes,
3050
3152
  info || _EccKeys.INFO
3051
3153
  );
3052
- return aesKey;
3154
+ return Object.assign(aesKey, { salt: toBase64(saltBytes) });
3053
3155
  }
3054
3156
  /**
3055
3157
  * Sign the given content using our private write key.
@@ -3086,7 +3188,7 @@
3086
3188
  }, "asString")
3087
3189
  });
3088
3190
  async function exportPublicKey(keypair, format2 = "raw") {
3089
- return await crypto.subtle.exportKey(format2, keypair.publicKey);
3191
+ return await webcrypto5.subtle.exportKey(format2, keypair.publicKey);
3090
3192
  }
3091
3193
  __name(exportPublicKey, "exportPublicKey");
3092
3194
  async function importPublicKey(base64Key, curve, use) {
@@ -3164,26 +3266,58 @@
3164
3266
  }
3165
3267
  }
3166
3268
  __name(verify3, "verify");
3269
+ function wrapKekInfo(ephemeralPubKey, recipientPubKey, info) {
3270
+ const infoBytes = new TextEncoder().encode(info);
3271
+ const data = new Uint8Array(
3272
+ ephemeralPubKey.length + recipientPubKey.length + infoBytes.length
3273
+ );
3274
+ data.set(ephemeralPubKey, 0);
3275
+ data.set(recipientPubKey, ephemeralPubKey.length);
3276
+ data.set(infoBytes, ephemeralPubKey.length + recipientPubKey.length);
3277
+ return data;
3278
+ }
3279
+ __name(wrapKekInfo, "wrapKekInfo");
3280
+ function wrapSignData(ephemeralPubKey, recipientPubKey, wrappedBlob, info) {
3281
+ const infoBytes = new TextEncoder().encode(info);
3282
+ const blobLength = new Uint8Array(4);
3283
+ new DataView(blobLength.buffer).setUint32(0, wrappedBlob.length);
3284
+ const data = new Uint8Array(
3285
+ ephemeralPubKey.length + recipientPubKey.length + blobLength.length + wrappedBlob.length + infoBytes.length
3286
+ );
3287
+ let offset = 0;
3288
+ data.set(ephemeralPubKey, offset);
3289
+ offset += ephemeralPubKey.length;
3290
+ data.set(recipientPubKey, offset);
3291
+ offset += recipientPubKey.length;
3292
+ data.set(blobLength, offset);
3293
+ offset += blobLength.length;
3294
+ data.set(wrappedBlob, offset);
3295
+ offset += wrappedBlob.length;
3296
+ data.set(infoBytes, offset);
3297
+ return data;
3298
+ }
3299
+ __name(wrapSignData, "wrapSignData");
3167
3300
  async function deriveKey(privateKey, publicKey, salt, info, keysize) {
3168
3301
  const encoder = new TextEncoder();
3169
- const sharedSecret = await crypto.subtle.deriveBits(
3302
+ const infoBytes = typeof info === "string" ? encoder.encode(info) : info;
3303
+ const sharedSecret = await webcrypto5.subtle.deriveBits(
3170
3304
  { name: "X25519", public: publicKey },
3171
3305
  privateKey,
3172
3306
  256
3173
3307
  );
3174
- const hkdfBaseKey = await crypto.subtle.importKey(
3308
+ const hkdfBaseKey = await webcrypto5.subtle.importKey(
3175
3309
  "raw",
3176
3310
  sharedSecret,
3177
3311
  "HKDF",
3178
3312
  false,
3179
3313
  ["deriveKey"]
3180
3314
  );
3181
- return crypto.subtle.deriveKey(
3315
+ return webcrypto5.subtle.deriveKey(
3182
3316
  {
3183
3317
  name: "HKDF",
3184
3318
  hash: "SHA-256",
3185
3319
  salt: salt instanceof Uint8Array ? toArrayBuffer3(salt) : salt,
3186
- info: encoder.encode(info)
3320
+ info: toArrayBuffer3(infoBytes)
3187
3321
  },
3188
3322
  hkdfBaseKey,
3189
3323
  { name: "AES-GCM", length: keysize || DEFAULT_SYMM_LENGTH },