@mysten/seal 0.2.0 → 0.3.1

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 (108) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cjs/bcs.d.ts +132 -0
  3. package/dist/cjs/bcs.js +67 -0
  4. package/dist/cjs/bcs.js.map +7 -0
  5. package/dist/cjs/client.d.ts +83 -0
  6. package/dist/cjs/client.js +283 -0
  7. package/dist/cjs/client.js.map +7 -0
  8. package/dist/cjs/decrypt.d.ts +15 -0
  9. package/dist/cjs/decrypt.js +94 -0
  10. package/dist/cjs/decrypt.js.map +7 -0
  11. package/dist/cjs/dem.d.ts +36 -0
  12. package/dist/cjs/dem.js +173 -0
  13. package/dist/cjs/dem.js.map +7 -0
  14. package/dist/cjs/elgamal.js.map +2 -2
  15. package/dist/cjs/encrypt.d.ts +14 -5
  16. package/dist/cjs/encrypt.js +52 -22
  17. package/dist/cjs/encrypt.js.map +3 -3
  18. package/dist/cjs/error.d.ts +58 -0
  19. package/dist/cjs/error.js +175 -0
  20. package/dist/cjs/error.js.map +7 -0
  21. package/dist/cjs/ibe.d.ts +13 -17
  22. package/dist/cjs/ibe.js +25 -28
  23. package/dist/cjs/ibe.js.map +2 -2
  24. package/dist/cjs/index.d.ts +3 -5
  25. package/dist/cjs/index.js +5 -11
  26. package/dist/cjs/index.js.map +2 -2
  27. package/dist/cjs/kdf.d.ts +7 -2
  28. package/dist/cjs/kdf.js +37 -2
  29. package/dist/cjs/kdf.js.map +3 -3
  30. package/dist/cjs/key-server.d.ts +5 -5
  31. package/dist/cjs/key-server.js +24 -21
  32. package/dist/cjs/key-server.js.map +2 -2
  33. package/dist/cjs/keys.d.ts +17 -0
  34. package/dist/cjs/keys.js +61 -0
  35. package/dist/cjs/keys.js.map +7 -0
  36. package/dist/cjs/session-key.d.ts +20 -14
  37. package/dist/cjs/session-key.js +90 -23
  38. package/dist/cjs/session-key.js.map +2 -2
  39. package/dist/cjs/types.d.ts +1 -86
  40. package/dist/cjs/types.js +0 -32
  41. package/dist/cjs/types.js.map +2 -2
  42. package/dist/cjs/utils.d.ts +2 -1
  43. package/dist/cjs/utils.js +17 -5
  44. package/dist/cjs/utils.js.map +2 -2
  45. package/dist/cjs/version.d.ts +1 -0
  46. package/dist/cjs/version.js +25 -0
  47. package/dist/cjs/version.js.map +7 -0
  48. package/dist/esm/bcs.d.ts +132 -0
  49. package/dist/esm/bcs.js +47 -0
  50. package/dist/esm/bcs.js.map +7 -0
  51. package/dist/esm/client.d.ts +83 -0
  52. package/dist/esm/client.js +268 -0
  53. package/dist/esm/client.js.map +7 -0
  54. package/dist/esm/decrypt.d.ts +15 -0
  55. package/dist/esm/decrypt.js +74 -0
  56. package/dist/esm/decrypt.js.map +7 -0
  57. package/dist/esm/dem.d.ts +36 -0
  58. package/dist/esm/dem.js +153 -0
  59. package/dist/esm/dem.js.map +7 -0
  60. package/dist/esm/elgamal.js.map +2 -2
  61. package/dist/esm/encrypt.d.ts +14 -5
  62. package/dist/esm/encrypt.js +49 -19
  63. package/dist/esm/encrypt.js.map +3 -3
  64. package/dist/esm/error.d.ts +58 -0
  65. package/dist/esm/error.js +155 -0
  66. package/dist/esm/error.js.map +7 -0
  67. package/dist/esm/ibe.d.ts +13 -17
  68. package/dist/esm/ibe.js +25 -28
  69. package/dist/esm/ibe.js.map +2 -2
  70. package/dist/esm/index.d.ts +3 -5
  71. package/dist/esm/index.js +5 -16
  72. package/dist/esm/index.js.map +2 -2
  73. package/dist/esm/kdf.d.ts +7 -2
  74. package/dist/esm/kdf.js +37 -2
  75. package/dist/esm/kdf.js.map +3 -3
  76. package/dist/esm/key-server.d.ts +5 -5
  77. package/dist/esm/key-server.js +29 -21
  78. package/dist/esm/key-server.js.map +2 -2
  79. package/dist/esm/keys.d.ts +17 -0
  80. package/dist/esm/keys.js +41 -0
  81. package/dist/esm/keys.js.map +7 -0
  82. package/dist/esm/session-key.d.ts +20 -14
  83. package/dist/esm/session-key.js +95 -24
  84. package/dist/esm/session-key.js.map +2 -2
  85. package/dist/esm/types.d.ts +1 -86
  86. package/dist/esm/types.js +0 -28
  87. package/dist/esm/types.js.map +3 -3
  88. package/dist/esm/utils.d.ts +2 -1
  89. package/dist/esm/utils.js +17 -5
  90. package/dist/esm/utils.js.map +2 -2
  91. package/dist/esm/version.d.ts +1 -0
  92. package/dist/esm/version.js +5 -0
  93. package/dist/esm/version.js.map +7 -0
  94. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  95. package/dist/tsconfig.tsbuildinfo +1 -1
  96. package/package.json +6 -5
  97. package/dist/cjs/aes.d.ts +0 -18
  98. package/dist/cjs/aes.js +0 -111
  99. package/dist/cjs/aes.js.map +0 -7
  100. package/dist/cjs/key-store.d.ts +0 -49
  101. package/dist/cjs/key-store.js +0 -203
  102. package/dist/cjs/key-store.js.map +0 -7
  103. package/dist/esm/aes.d.ts +0 -18
  104. package/dist/esm/aes.js +0 -91
  105. package/dist/esm/aes.js.map +0 -7
  106. package/dist/esm/key-store.d.ts +0 -49
  107. package/dist/esm/key-store.js +0 -183
  108. package/dist/esm/key-store.js.map +0 -7
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var decrypt_exports = {};
20
+ __export(decrypt_exports, {
21
+ decrypt: () => decrypt
22
+ });
23
+ module.exports = __toCommonJS(decrypt_exports);
24
+ var import_bcs = require("@mysten/bcs");
25
+ var import_shamir_secret_sharing = require("shamir-secret-sharing");
26
+ var import_bls12381 = require("./bls12381.js");
27
+ var import_dem = require("./dem.js");
28
+ var import_error = require("./error.js");
29
+ var import_ibe = require("./ibe.js");
30
+ var import_kdf = require("./kdf.js");
31
+ var import_utils = require("./utils.js");
32
+ async function decrypt({ encryptedObject, keys }) {
33
+ if (!encryptedObject.encryptedShares.BonehFranklinBLS12381) {
34
+ throw new import_error.UnsupportedFeatureError("Encryption mode not supported");
35
+ }
36
+ const fullId = (0, import_utils.createFullId)(import_ibe.DST, encryptedObject.packageId, encryptedObject.id);
37
+ const inKeystore = encryptedObject.services.map((_, i) => i).filter((i) => keys.has(`${fullId}:${encryptedObject.services[i][0]}`));
38
+ if (inKeystore.length < encryptedObject.threshold) {
39
+ throw new Error("Not enough shares. Please fetch more keys.");
40
+ }
41
+ const encryptedShares = encryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedShares;
42
+ if (encryptedShares.length !== encryptedObject.services.length) {
43
+ throw new import_error.InvalidCiphertextError(
44
+ `Mismatched shares ${encryptedShares.length} and services ${encryptedObject.services.length}`
45
+ );
46
+ }
47
+ const nonce = import_bls12381.G2Element.fromBytes(encryptedObject.encryptedShares.BonehFranklinBLS12381.nonce);
48
+ const shares = inKeystore.map((i) => {
49
+ const [objectId, index] = encryptedObject.services[i];
50
+ const share = import_ibe.BonehFranklinBLS12381Services.decrypt(
51
+ nonce,
52
+ keys.get(`${fullId}:${objectId}`),
53
+ encryptedShares[i],
54
+ (0, import_bcs.fromHex)(fullId),
55
+ [objectId, index]
56
+ );
57
+ return { index, share };
58
+ });
59
+ const key = await combine(shares);
60
+ const demKey = (0, import_kdf.deriveKey)(import_kdf.KeyPurpose.DEM, key);
61
+ if (encryptedObject.ciphertext.Aes256Gcm) {
62
+ try {
63
+ return import_dem.AesGcm256.decrypt(demKey, encryptedObject.ciphertext);
64
+ } catch {
65
+ throw new Error("Decryption failed");
66
+ }
67
+ } else if (encryptedObject.ciphertext.Plain) {
68
+ return demKey;
69
+ } else if (encryptedObject.ciphertext.Hmac256Ctr) {
70
+ try {
71
+ return import_dem.Hmac256Ctr.decrypt(demKey, encryptedObject.ciphertext);
72
+ } catch {
73
+ throw new Error("Decryption failed");
74
+ }
75
+ } else {
76
+ throw new Error("Invalid encrypted object");
77
+ }
78
+ }
79
+ async function combine(shares) {
80
+ if (shares.length === 0) {
81
+ throw new Error("Invalid shares length");
82
+ } else if (shares.length === 1) {
83
+ return Promise.resolve(shares[0].share);
84
+ }
85
+ return (0, import_shamir_secret_sharing.combine)(
86
+ shares.map(({ index, share }) => {
87
+ const packedShare = new Uint8Array(share.length + 1);
88
+ packedShare.set(share, 0);
89
+ packedShare[share.length] = index;
90
+ return packedShare;
91
+ })
92
+ );
93
+ }
94
+ //# sourceMappingURL=decrypt.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/decrypt.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromHex } from '@mysten/bcs';\nimport { combine as externalCombine } from 'shamir-secret-sharing';\n\nimport type { EncryptedObject } from './bcs.js';\nimport type { G1Element } from './bls12381.js';\nimport { G2Element } from './bls12381.js';\nimport { AesGcm256, Hmac256Ctr } from './dem.js';\nimport { InvalidCiphertextError, UnsupportedFeatureError } from './error.js';\nimport { BonehFranklinBLS12381Services, DST } from './ibe.js';\nimport { deriveKey, KeyPurpose } from './kdf.js';\nimport type { KeyCacheKey } from './types.js';\nimport { createFullId } from './utils.js';\n\nexport interface DecryptOptions {\n\tencryptedObject: typeof EncryptedObject.$inferType;\n\tkeys: Map<KeyCacheKey, G1Element>;\n}\n\n/**\n * Decrypt the given encrypted bytes with the given cached secret keys for the full ID.\n * It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers\n * otherwise, this will throw an error.\n *\n * @returns - The decrypted plaintext corresponding to ciphertext.\n */\nexport async function decrypt({ encryptedObject, keys }: DecryptOptions): Promise<Uint8Array> {\n\tif (!encryptedObject.encryptedShares.BonehFranklinBLS12381) {\n\t\tthrow new UnsupportedFeatureError('Encryption mode not supported');\n\t}\n\n\tconst fullId = createFullId(DST, encryptedObject.packageId, encryptedObject.id);\n\n\t// Get the indices of the service whose keys are in the keystore.\n\tconst inKeystore = encryptedObject.services\n\t\t.map((_, i) => i)\n\t\t.filter((i) => keys.has(`${fullId}:${encryptedObject.services[i][0]}`));\n\n\tif (inKeystore.length < encryptedObject.threshold) {\n\t\tthrow new Error('Not enough shares. Please fetch more keys.');\n\t}\n\n\tconst encryptedShares = encryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedShares;\n\tif (encryptedShares.length !== encryptedObject.services.length) {\n\t\tthrow new InvalidCiphertextError(\n\t\t\t`Mismatched shares ${encryptedShares.length} and services ${encryptedObject.services.length}`,\n\t\t);\n\t}\n\n\tconst nonce = G2Element.fromBytes(encryptedObject.encryptedShares.BonehFranklinBLS12381.nonce);\n\n\t// Decrypt each share.\n\tconst shares = inKeystore.map((i: number) => {\n\t\tconst [objectId, index] = encryptedObject.services[i];\n\t\t// Use the index as the unique info parameter to allow for multiple shares per key server.\n\t\tconst share = BonehFranklinBLS12381Services.decrypt(\n\t\t\tnonce,\n\t\t\tkeys.get(`${fullId}:${objectId}`)!,\n\t\t\tencryptedShares[i],\n\t\t\tfromHex(fullId),\n\t\t\t[objectId, index],\n\t\t);\n\t\t// The Shamir secret sharing library expects the index/x-coordinate to be at the end of the share.\n\t\treturn { index, share };\n\t});\n\n\t// Combine the decrypted shares into the key.\n\tconst key = await combine(shares);\n\tconst demKey = deriveKey(KeyPurpose.DEM, key);\n\tif (encryptedObject.ciphertext.Aes256Gcm) {\n\t\ttry {\n\t\t\t// Decrypt the ciphertext with the key.\n\t\t\treturn AesGcm256.decrypt(demKey, encryptedObject.ciphertext);\n\t\t} catch {\n\t\t\tthrow new Error('Decryption failed');\n\t\t}\n\t} else if (encryptedObject.ciphertext.Plain) {\n\t\t// In case `Plain` mode is used, return the key.\n\t\treturn demKey;\n\t} else if (encryptedObject.ciphertext.Hmac256Ctr) {\n\t\ttry {\n\t\t\treturn Hmac256Ctr.decrypt(demKey, encryptedObject.ciphertext);\n\t\t} catch {\n\t\t\tthrow new Error('Decryption failed');\n\t\t}\n\t} else {\n\t\tthrow new Error('Invalid encrypted object');\n\t}\n}\n\n/**\n * Helper function that combines the shares into the key.\n * @param shares - The shares to combine.\n * @returns - The combined key.\n */\nasync function combine(shares: { index: number; share: Uint8Array }[]): Promise<Uint8Array> {\n\tif (shares.length === 0) {\n\t\tthrow new Error('Invalid shares length');\n\t} else if (shares.length === 1) {\n\t\t// The Shamir secret sharing library expects at least two shares.\n\t\t// If there is only one and the threshold is 1, the reconstructed secret is the same as the share.\n\t\treturn Promise.resolve(shares[0].share);\n\t}\n\n\t// The Shamir secret sharing library expects the index/x-coordinate to be at the end of the share\n\treturn externalCombine(\n\t\tshares.map(({ index, share }) => {\n\t\t\tconst packedShare = new Uint8Array(share.length + 1);\n\t\t\tpackedShare.set(share, 0);\n\t\t\tpackedShare[share.length] = index;\n\t\t\treturn packedShare;\n\t\t}),\n\t);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAwB;AACxB,mCAA2C;AAI3C,sBAA0B;AAC1B,iBAAsC;AACtC,mBAAgE;AAChE,iBAAmD;AACnD,iBAAsC;AAEtC,mBAA6B;AAc7B,eAAsB,QAAQ,EAAE,iBAAiB,KAAK,GAAwC;AAC7F,MAAI,CAAC,gBAAgB,gBAAgB,uBAAuB;AAC3D,UAAM,IAAI,qCAAwB,+BAA+B;AAAA,EAClE;AAEA,QAAM,aAAS,2BAAa,gBAAK,gBAAgB,WAAW,gBAAgB,EAAE;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AgB,UAAU;AAAA,IAC7D,QAAQ;AACP,YAAM,IAAI,MAAM,mBAAmB;AAAA,IACpC;AAAA,EACD,OAAO;AACN,UAAM,IAAI,MAAM,0BAA0B;AAAA,EAC3C;AACD;AAOA,eAAe,QAAQ,QAAqE;AAC3F,MAAI,OAAO,WAAW,GAAG;AACxB,UAAM,IAAI,MAAM,uBAAuB;AAAA,EACxC,WAAW,OAAO,WAAW,GAAG;AAG/B,WAAO,QAAQ,QAAQ,OAAO,CAAC,EAAE,KAAK;AAAA,EACvC;AAGA,aAAO,6BAAAA;AAAA,IACN,OAAO,IAAI,CAAC,EAAE,OAAO,MAAM,MAAM;AAChC,YAAM,cAAc,IAAI,WAAW,MAAM,SAAS,CAAC;AACnD,kBAAY,IAAI,OAAO,CAAC;AACxB,kBAAY,MAAM,MAAM,IAAI;AAC5B,aAAO;AAAA,IACR,CAAC;AAAA,EACF;AACD;",
6
+ "names": ["externalCombine"]
7
+ }
@@ -0,0 +1,36 @@
1
+ import type { Ciphertext } from './bcs.js';
2
+ export declare const iv: Uint8Array<ArrayBuffer>;
3
+ export interface EncryptionInput {
4
+ encrypt(key: Uint8Array): Promise<typeof Ciphertext.$inferInput>;
5
+ generateKey(): Promise<Uint8Array>;
6
+ }
7
+ export declare class AesGcm256 implements EncryptionInput {
8
+ readonly plaintext: Uint8Array;
9
+ readonly aad: Uint8Array;
10
+ constructor(msg: Uint8Array, aad: Uint8Array);
11
+ generateKey(): Promise<Uint8Array>;
12
+ encrypt(key: Uint8Array): Promise<typeof Ciphertext.$inferInput>;
13
+ static decrypt(key: Uint8Array, ciphertext: typeof Ciphertext.$inferInput): Promise<Uint8Array>;
14
+ }
15
+ export declare class Plain implements EncryptionInput {
16
+ encrypt(_key: Uint8Array): Promise<typeof Ciphertext.$inferInput>;
17
+ generateKey(): Promise<Uint8Array>;
18
+ }
19
+ /**
20
+ * Authenticated encryption using CTR mode with HMAC-SHA3-256 as a PRF.
21
+ * 1. Derive an encryption key, <i>k<sub>1</sub> = <b>hmac</b>(key, 1)</i>.
22
+ * 2. Chunk the message into blocks of 32 bytes, <i>m = m<sub>1</sub> || ... || m<sub>n</sub></i>.
23
+ * 3. Let the ciphertext be defined by <i>c = c<sub>1</sub> || ... || c<sub>n</sub></i> where <i>c<sub>i</sub> = m<sub>i</sub> ⊕ <b>hmac</b>(k<sub>1</sub>, i)</i>.
24
+ * 4. Compute a MAC over the AAD and the ciphertext, <i>mac = <b>hmac</b>(k<sub>2</sub>, aad || c) where k<sub>2</sub> = <b>hmac</b>(key, 2)</i>.
25
+ * 5. Return <i>mac || c</i>.
26
+ */
27
+ export declare class Hmac256Ctr implements EncryptionInput {
28
+ readonly plaintext: Uint8Array;
29
+ readonly aad: Uint8Array;
30
+ constructor(msg: Uint8Array, aad: Uint8Array);
31
+ generateKey(): Promise<Uint8Array>;
32
+ encrypt(key: Uint8Array): Promise<typeof Ciphertext.$inferInput>;
33
+ static decrypt(key: Uint8Array, ciphertext: typeof Ciphertext.$inferInput): Promise<Uint8Array>;
34
+ private static computeMac;
35
+ private static encryptInCtrMode;
36
+ }
@@ -0,0 +1,173 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var dem_exports = {};
20
+ __export(dem_exports, {
21
+ AesGcm256: () => AesGcm256,
22
+ Hmac256Ctr: () => Hmac256Ctr,
23
+ Plain: () => Plain,
24
+ iv: () => iv
25
+ });
26
+ module.exports = __toCommonJS(dem_exports);
27
+ var import_bcs = require("@mysten/bcs");
28
+ var import_utils = require("@noble/curves/abstract/utils");
29
+ var import_hmac = require("@noble/hashes/hmac");
30
+ var import_sha3 = require("@noble/hashes/sha3");
31
+ var import_error = require("./error.js");
32
+ var import_utils2 = require("./utils.js");
33
+ const iv = Uint8Array.from([
34
+ 138,
35
+ 55,
36
+ 153,
37
+ 253,
38
+ 198,
39
+ 46,
40
+ 121,
41
+ 219,
42
+ 160,
43
+ 128,
44
+ 89,
45
+ 7,
46
+ 214,
47
+ 156,
48
+ 148,
49
+ 220
50
+ ]);
51
+ async function generateAesKey() {
52
+ const key = await crypto.subtle.generateKey(
53
+ {
54
+ name: "AES-GCM",
55
+ length: 256
56
+ },
57
+ true,
58
+ ["encrypt", "decrypt"]
59
+ );
60
+ return await crypto.subtle.exportKey("raw", key).then((keyData) => new Uint8Array(keyData));
61
+ }
62
+ class AesGcm256 {
63
+ constructor(msg, aad) {
64
+ this.plaintext = msg;
65
+ this.aad = aad;
66
+ }
67
+ generateKey() {
68
+ return generateAesKey();
69
+ }
70
+ async encrypt(key) {
71
+ const aesCryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);
72
+ const blob = new Uint8Array(
73
+ await crypto.subtle.encrypt(
74
+ {
75
+ name: "AES-GCM",
76
+ iv,
77
+ additionalData: this.aad
78
+ },
79
+ aesCryptoKey,
80
+ this.plaintext
81
+ )
82
+ );
83
+ return {
84
+ Aes256Gcm: {
85
+ blob,
86
+ aad: this.aad ?? []
87
+ }
88
+ };
89
+ }
90
+ static async decrypt(key, ciphertext) {
91
+ if (!("Aes256Gcm" in ciphertext)) {
92
+ throw new import_error.InvalidCiphertextError(`Invalid ciphertext ${ciphertext}`);
93
+ }
94
+ const aesCryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
95
+ return new Uint8Array(
96
+ await crypto.subtle.decrypt(
97
+ {
98
+ name: "AES-GCM",
99
+ iv,
100
+ additionalData: new Uint8Array(ciphertext.Aes256Gcm.aad ?? [])
101
+ },
102
+ aesCryptoKey,
103
+ new Uint8Array(ciphertext.Aes256Gcm.blob)
104
+ )
105
+ );
106
+ }
107
+ }
108
+ class Plain {
109
+ async encrypt(_key) {
110
+ return {
111
+ Plain: {}
112
+ };
113
+ }
114
+ generateKey() {
115
+ return generateAesKey();
116
+ }
117
+ }
118
+ class Hmac256Ctr {
119
+ constructor(msg, aad) {
120
+ this.plaintext = msg;
121
+ this.aad = aad;
122
+ }
123
+ generateKey() {
124
+ return generateAesKey();
125
+ }
126
+ async encrypt(key) {
127
+ const blob = Hmac256Ctr.encryptInCtrMode(key, this.plaintext);
128
+ const mac = Hmac256Ctr.computeMac(key, this.aad, blob);
129
+ return {
130
+ Hmac256Ctr: {
131
+ blob,
132
+ mac,
133
+ aad: this.aad ?? []
134
+ }
135
+ };
136
+ }
137
+ static async decrypt(key, ciphertext) {
138
+ if (!("Hmac256Ctr" in ciphertext)) {
139
+ throw new import_error.InvalidCiphertextError(`Invalid ciphertext ${ciphertext}`);
140
+ }
141
+ const aad = new Uint8Array(ciphertext.Hmac256Ctr.aad ?? []);
142
+ const blob = new Uint8Array(ciphertext.Hmac256Ctr.blob);
143
+ const mac = Hmac256Ctr.computeMac(key, aad, blob);
144
+ if (!(0, import_utils.equalBytes)(mac, new Uint8Array(ciphertext.Hmac256Ctr.mac))) {
145
+ throw new import_error.InvalidCiphertextError(`Invalid MAC ${mac}`);
146
+ }
147
+ return Hmac256Ctr.encryptInCtrMode(key, blob);
148
+ }
149
+ static computeMac(key, aad, ciphertext) {
150
+ const macKey = (0, import_hmac.hmac)(import_sha3.sha3_256, key, MacKeyTag);
151
+ const macInput = new Uint8Array([...toBytes(aad.length), ...aad, ...ciphertext]);
152
+ const mac = (0, import_hmac.hmac)(import_sha3.sha3_256, macKey, macInput);
153
+ return mac;
154
+ }
155
+ static encryptInCtrMode(key, msg) {
156
+ const blockSize = 32;
157
+ let result = Uint8Array.from({ length: msg.length }, () => 0);
158
+ const encryptionKey = (0, import_hmac.hmac)(import_sha3.sha3_256, key, EncryptionKeyTag);
159
+ for (let i = 0; i * blockSize < msg.length; i++) {
160
+ const block = msg.slice(i * blockSize, (i + 1) * blockSize);
161
+ let mask = (0, import_hmac.hmac)(import_sha3.sha3_256, encryptionKey, toBytes(i));
162
+ const encryptedBlock = (0, import_utils2.xorUnchecked)(block, mask);
163
+ result.set(encryptedBlock, i * blockSize);
164
+ }
165
+ return result;
166
+ }
167
+ }
168
+ function toBytes(n) {
169
+ return import_bcs.bcs.u64().serialize(n).toBytes();
170
+ }
171
+ const EncryptionKeyTag = new Uint8Array([1]);
172
+ const MacKeyTag = new Uint8Array([2]);
173
+ //# sourceMappingURL=dem.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/dem.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { bcs } from '@mysten/bcs';\nimport { equalBytes } from '@noble/curves/abstract/utils';\nimport { hmac } from '@noble/hashes/hmac';\nimport { sha3_256 } from '@noble/hashes/sha3';\n\nimport type { Ciphertext } from './bcs.js';\nimport { InvalidCiphertextError } from './error.js';\nimport { xorUnchecked } from './utils.js';\n\n// Use a fixed IV for AES.\nexport const iv = Uint8Array.from([\n\t138, 55, 153, 253, 198, 46, 121, 219, 160, 128, 89, 7, 214, 156, 148, 220,\n]);\n\nasync function generateAesKey(): Promise<Uint8Array> {\n\tconst key = await crypto.subtle.generateKey(\n\t\t{\n\t\t\tname: 'AES-GCM',\n\t\t\tlength: 256,\n\t\t},\n\t\ttrue,\n\t\t['encrypt', 'decrypt'],\n\t);\n\treturn await crypto.subtle.exportKey('raw', key).then((keyData) => new Uint8Array(keyData));\n}\n\nexport interface EncryptionInput {\n\tencrypt(key: Uint8Array): Promise<typeof Ciphertext.$inferInput>;\n\tgenerateKey(): Promise<Uint8Array>;\n}\n\nexport class AesGcm256 implements EncryptionInput {\n\treadonly plaintext: Uint8Array;\n\treadonly aad: Uint8Array;\n\n\tconstructor(msg: Uint8Array, aad: Uint8Array) {\n\t\tthis.plaintext = msg;\n\t\tthis.aad = aad;\n\t}\n\n\tgenerateKey(): Promise<Uint8Array> {\n\t\treturn generateAesKey();\n\t}\n\n\tasync encrypt(key: Uint8Array): Promise<typeof Ciphertext.$inferInput> {\n\t\tconst aesCryptoKey = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt']);\n\n\t\tconst blob = new Uint8Array(\n\t\t\tawait crypto.subtle.encrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv,\n\t\t\t\t\tadditionalData: this.aad,\n\t\t\t\t},\n\t\t\t\taesCryptoKey,\n\t\t\t\tthis.plaintext,\n\t\t\t),\n\t\t);\n\n\t\treturn {\n\t\t\tAes256Gcm: {\n\t\t\t\tblob,\n\t\t\t\taad: this.aad ?? [],\n\t\t\t},\n\t\t};\n\t}\n\n\tstatic async decrypt(\n\t\tkey: Uint8Array,\n\t\tciphertext: typeof Ciphertext.$inferInput,\n\t): Promise<Uint8Array> {\n\t\tif (!('Aes256Gcm' in ciphertext)) {\n\t\t\tthrow new InvalidCiphertextError(`Invalid ciphertext ${ciphertext}`);\n\t\t}\n\n\t\tconst aesCryptoKey = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['decrypt']);\n\n\t\treturn new Uint8Array(\n\t\t\tawait crypto.subtle.decrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv,\n\t\t\t\t\tadditionalData: new Uint8Array(ciphertext.Aes256Gcm.aad ?? []),\n\t\t\t\t},\n\t\t\t\taesCryptoKey,\n\t\t\t\tnew Uint8Array(ciphertext.Aes256Gcm.blob),\n\t\t\t),\n\t\t);\n\t}\n}\n\nexport class Plain implements EncryptionInput {\n\tasync encrypt(_key: Uint8Array): Promise<typeof Ciphertext.$inferInput> {\n\t\treturn {\n\t\t\tPlain: {},\n\t\t};\n\t}\n\n\tgenerateKey(): Promise<Uint8Array> {\n\t\treturn generateAesKey();\n\t}\n}\n\n/**\n * Authenticated encryption using CTR mode with HMAC-SHA3-256 as a PRF.\n * 1. Derive an encryption key, <i>k<sub>1</sub> = <b>hmac</b>(key, 1)</i>.\n * 2. Chunk the message into blocks of 32 bytes, <i>m = m<sub>1</sub> || ... || m<sub>n</sub></i>.\n * 3. Let the ciphertext be defined by <i>c = c<sub>1</sub> || ... || c<sub>n</sub></i> where <i>c<sub>i</sub> = m<sub>i</sub> \u2295 <b>hmac</b>(k<sub>1</sub>, i)</i>.\n * 4. Compute a MAC over the AAD and the ciphertext, <i>mac = <b>hmac</b>(k<sub>2</sub>, aad || c) where k<sub>2</sub> = <b>hmac</b>(key, 2)</i>.\n * 5. Return <i>mac || c</i>.\n */\nexport class Hmac256Ctr implements EncryptionInput {\n\treadonly plaintext: Uint8Array;\n\treadonly aad: Uint8Array;\n\n\tconstructor(msg: Uint8Array, aad: Uint8Array) {\n\t\tthis.plaintext = msg;\n\t\tthis.aad = aad;\n\t}\n\n\tgenerateKey(): Promise<Uint8Array> {\n\t\treturn generateAesKey();\n\t}\n\n\tasync encrypt(key: Uint8Array): Promise<typeof Ciphertext.$inferInput> {\n\t\tconst blob = Hmac256Ctr.encryptInCtrMode(key, this.plaintext);\n\t\tconst mac = Hmac256Ctr.computeMac(key, this.aad, blob);\n\t\treturn {\n\t\t\tHmac256Ctr: {\n\t\t\t\tblob,\n\t\t\t\tmac,\n\t\t\t\taad: this.aad ?? [],\n\t\t\t},\n\t\t};\n\t}\n\n\tstatic async decrypt(\n\t\tkey: Uint8Array,\n\t\tciphertext: typeof Ciphertext.$inferInput,\n\t): Promise<Uint8Array> {\n\t\tif (!('Hmac256Ctr' in ciphertext)) {\n\t\t\tthrow new InvalidCiphertextError(`Invalid ciphertext ${ciphertext}`);\n\t\t}\n\t\tconst aad = new Uint8Array(ciphertext.Hmac256Ctr.aad ?? []);\n\t\tconst blob = new Uint8Array(ciphertext.Hmac256Ctr.blob);\n\t\tconst mac = Hmac256Ctr.computeMac(key, aad, blob);\n\t\tif (!equalBytes(mac, new Uint8Array(ciphertext.Hmac256Ctr.mac))) {\n\t\t\tthrow new InvalidCiphertextError(`Invalid MAC ${mac}`);\n\t\t}\n\t\treturn Hmac256Ctr.encryptInCtrMode(key, blob);\n\t}\n\n\tprivate static computeMac(key: Uint8Array, aad: Uint8Array, ciphertext: Uint8Array): Uint8Array {\n\t\tconst macKey = hmac(sha3_256, key, MacKeyTag);\n\t\tconst macInput = new Uint8Array([...toBytes(aad.length), ...aad, ...ciphertext]);\n\t\tconst mac = hmac(sha3_256, macKey, macInput);\n\t\treturn mac;\n\t}\n\n\tprivate static encryptInCtrMode(key: Uint8Array, msg: Uint8Array): Uint8Array {\n\t\tconst blockSize = 32;\n\t\tlet result = Uint8Array.from({ length: msg.length }, () => 0);\n\t\tconst encryptionKey = hmac(sha3_256, key, EncryptionKeyTag);\n\t\tfor (let i = 0; i * blockSize < msg.length; i++) {\n\t\t\tconst block = msg.slice(i * blockSize, (i + 1) * blockSize);\n\t\t\tlet mask = hmac(sha3_256, encryptionKey, toBytes(i));\n\t\t\tconst encryptedBlock = xorUnchecked(block, mask);\n\t\t\tresult.set(encryptedBlock, i * blockSize);\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Convert a u64 to bytes using little-endian representation.\n */\nfunction toBytes(n: number): Uint8Array {\n\treturn bcs.u64().serialize(n).toBytes();\n}\n\nconst EncryptionKeyTag = new Uint8Array([1]);\nconst MacKeyTag = new Uint8Array([2]);\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAoB;AACpB,mBAA2B;AAC3B,kB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License-Identifier: Apache-2.0\n\nimport { G1Element, G2Element, Scalar } from './bls12381.js';\n\n/**\n * Decrypt a ciphertext with a given secret key. The secret key must be a 32-byte scalar.\n * The ciphertext is a pair of G1Elements (48 bytes).\n */\nexport function elgamalDecrypt(sk: Uint8Array, ciphertext: [Uint8Array, Uint8Array]): Uint8Array {\n\treturn decrypt(Scalar.fromBytes(sk), [\n\t\tG1Element.fromBytes(ciphertext[0]),\n\t\tG1Element.fromBytes(ciphertext[1]),\n\t]).toBytes();\n}\n\n/**\n * Decrypt a ciphertext with a given secret key. The secret key must be a 32-byte scalar.\n * The ciphertext is a pair of G1Elements (48 bytes).\n */\nfunction decrypt(sk: Scalar, encryption: [G1Element, G1Element]): G1Element {\n\treturn encryption[1].subtract(encryption[0].multiply(sk));\n}\n\n// /**\n// * Encrypt a message with a given public key. Both the public key and the message must a compressed G1Element (48 bytes).\n// */\n// function elgamal_encrypt(pk: Uint8Array, message: Uint8Array): [Uint8Array, Uint8Array] {\n// \tconst ciphertext = encrypt(G1Element.fromBytes(pk), G1Element.fromBytes(message));\n// \treturn [ciphertext[0].toBytes(), ciphertext[1].toBytes()];\n// }\n\n// /**\n// * Encrypt a message with a given public key. Both the public key and the message must a compressed G1Element (48 bytes).\n// */\n// function encrypt(pk: G1Element, message: G1Element): [G1Element, G1Element] {\n// \tconst r = Scalar.random();\n// \treturn [G1Element.generator().multiply(r), pk.multiply(r).add(message)];\n// }\n\n/** Generate a random secret key. */\nexport function generateSecretKey(): Uint8Array {\n\treturn Scalar.random().toBytes();\n}\n\n/** Derive the BLS public key for a given secret key. */\nexport function toPublicKey(sk: Uint8Array): Uint8Array {\n\treturn G1Element.generator().multiply(Scalar.fromBytes(sk)).toBytes();\n}\n\n/** Derive the BLS verification key for a given secret key. */\nexport function toVerificationKey(sk: Uint8Array): Uint8Array {\n\treturn G2Element.generator().multiply(Scalar.fromBytes(sk)).toBytes();\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,sBAA6C;AAMtC,SAAS,eAAe,IAAgB,YAAkD;AAChG,SAAO,QAAQ,uBAAO,UAAU,EAAE,GAAG;AAAA,IACpC,0BAAU,UAAU,WAAW,CAAC,CAAC;AAAA,IACjC,0BAAU,UAAU,WAAW,CAAC,CAAC;AAAA,EAClC,CAAC,EAAE,QAAQ;AACZ;AAMA,SAAS,QAAQ,IAAY,YAA+C;AAC3E,SAAO,WAAW,CAAC,EAAE,SAAS,WAAW,CAAC,EAAE,SAAS,EAAE,CAAC;AACzD;AAmBO,SAAS,oBAAgC;AAC/C,SAAO,uBAAO,OAAO,EAAE,QAAQ;AAChC;AAGO,SAAS,YAAY,IAA4B;AACvD,SAAO,0BAAU,UAAU,EAAE,SAAS,uBAAO,UAAU,EAAE,CAAC,EAAE,QAAQ;AACrE;AAGO,SAAS,kBAAkB,IAA4B;AAC7D,SAAO,0BAAU,UAAU,EAAE,SAAS,uBAAO,UAAU,EAAE,CAAC,EAAE,QAAQ;AACrE;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { G1Element, G2Element, Scalar } from './bls12381.js';\n\n/**\n * Decrypt a ciphertext with a given secret key. The secret key must be a 32-byte scalar.\n * The ciphertext is a pair of G1Elements (48 bytes).\n */\nexport function elgamalDecrypt(sk: Uint8Array, ciphertext: [Uint8Array, Uint8Array]): Uint8Array {\n\treturn decrypt(Scalar.fromBytes(sk), [\n\t\tG1Element.fromBytes(ciphertext[0]),\n\t\tG1Element.fromBytes(ciphertext[1]),\n\t]).toBytes();\n}\n\n/**\n * Decrypt a ciphertext with a given secret key. The secret key must be a 32-byte scalar.\n * The ciphertext is a pair of G1Elements (48 bytes).\n */\nfunction decrypt(sk: Scalar, encryption: [G1Element, G1Element]): G1Element {\n\treturn encryption[1].subtract(encryption[0].multiply(sk));\n}\n\n/** Generate a random secret key. */\nexport function generateSecretKey(): Uint8Array {\n\treturn Scalar.random().toBytes();\n}\n\n/** Derive the BLS public key for a given secret key. */\nexport function toPublicKey(sk: Uint8Array): Uint8Array {\n\treturn G1Element.generator().multiply(Scalar.fromBytes(sk)).toBytes();\n}\n\n/** Derive the BLS verification key for a given secret key. */\nexport function toVerificationKey(sk: Uint8Array): Uint8Array {\n\treturn G2Element.generator().multiply(Scalar.fromBytes(sk)).toBytes();\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,sBAA6C;AAMtC,SAAS,eAAe,IAAgB,YAAkD;AAChG,SAAO,QAAQ,uBAAO,UAAU,EAAE,GAAG;AAAA,IACpC,0BAAU,UAAU,WAAW,CAAC,CAAC;AAAA,IACjC,0BAAU,UAAU,WAAW,CAAC,CAAC;AAAA,EAClC,CAAC,EAAE,QAAQ;AACZ;AAMA,SAAS,QAAQ,IAAY,YAA+C;AAC3E,SAAO,WAAW,CAAC,EAAE,SAAS,WAAW,CAAC,EAAE,SAAS,EAAE,CAAC;AACzD;AAGO,SAAS,oBAAgC;AAC/C,SAAO,uBAAO,OAAO,EAAE,QAAQ;AAChC;AAGO,SAAS,YAAY,IAA4B;AACvD,SAAO,0BAAU,UAAU,EAAE,SAAS,uBAAO,UAAU,EAAE,CAAC,EAAE,QAAQ;AACrE;AAGO,SAAS,kBAAkB,IAA4B;AAC7D,SAAO,0BAAU,UAAU,EAAE,SAAS,uBAAO,UAAU,EAAE,CAAC,EAAE,QAAQ;AACrE;",
6
6
  "names": []
7
7
  }
@@ -1,10 +1,11 @@
1
- import type { EncryptionInput } from './aes.js';
1
+ import type { EncryptionInput } from './dem.js';
2
2
  import type { KeyServer } from './key-server.js';
3
3
  export declare const MAX_U8 = 255;
4
4
  /**
5
5
  * Given full ID and what key servers to use, return the encrypted message under the identity and return the bcs bytes of the encrypted object.
6
6
  *
7
7
  * @param keyServers - A list of KeyServers (same server can be used multiple times)
8
+ * @param kemType - The type of KEM to use.
8
9
  * @param packageId - packageId
9
10
  * @param id - id
10
11
  * @param encryptionInput - Input to the encryption. Should be one of the EncryptionInput types, AesGcmEncryptionInput or Plain.
@@ -12,13 +13,21 @@ export declare const MAX_U8 = 255;
12
13
  * @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.
13
14
  * Since the key can be used to decrypt, it should not be shared but can be used eg. for backup.
14
15
  */
15
- export declare function encrypt<Input extends EncryptionInput>({ keyServers, threshold, packageId, id, encryptionInput, }: {
16
+ export declare function encrypt({ keyServers, kemType, threshold, packageId, id, encryptionInput, }: {
16
17
  keyServers: KeyServer[];
18
+ kemType: KemType;
17
19
  threshold: number;
18
- packageId: Uint8Array;
19
- id: Uint8Array;
20
- encryptionInput: Input;
20
+ packageId: string;
21
+ id: string;
22
+ encryptionInput: EncryptionInput;
21
23
  }): Promise<{
22
24
  encryptedObject: Uint8Array;
23
25
  key: Uint8Array;
24
26
  }>;
27
+ export declare enum KemType {
28
+ BonehFranklinBLS12381DemCCA = 0
29
+ }
30
+ export declare enum DemType {
31
+ AesGcm256 = 0,
32
+ Hmac256Ctr = 1
33
+ }
@@ -18,58 +18,88 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var encrypt_exports = {};
20
20
  __export(encrypt_exports, {
21
+ DemType: () => DemType,
22
+ KemType: () => KemType,
21
23
  MAX_U8: () => MAX_U8,
22
24
  encrypt: () => encrypt
23
25
  });
24
26
  module.exports = __toCommonJS(encrypt_exports);
27
+ var import_bcs = require("@mysten/bcs");
28
+ var import_utils = require("@mysten/sui/utils");
25
29
  var import_shamir_secret_sharing = require("shamir-secret-sharing");
30
+ var import_bcs2 = require("./bcs.js");
31
+ var import_error = require("./error.js");
26
32
  var import_ibe = require("./ibe.js");
27
- var import_key_server = require("./key-server.js");
28
- var import_types = require("./types.js");
29
- var import_utils = require("./utils.js");
33
+ var import_kdf = require("./kdf.js");
34
+ var import_utils2 = require("./utils.js");
30
35
  const MAX_U8 = 255;
31
36
  async function encrypt({
32
37
  keyServers,
38
+ kemType,
33
39
  threshold,
34
40
  packageId,
35
41
  id,
36
42
  encryptionInput
37
43
  }) {
38
- if (keyServers.length < threshold || threshold === 0 || keyServers.length > MAX_U8 || threshold > MAX_U8 || packageId.length !== 32) {
39
- throw new Error("Invalid input");
44
+ if (keyServers.length < threshold || threshold === 0 || keyServers.length > MAX_U8 || threshold > MAX_U8 || !(0, import_utils.isValidSuiObjectId)(packageId)) {
45
+ throw new import_error.UserError(
46
+ `Invalid key servers or threshold ${threshold} for ${keyServers.length} key servers for package ${packageId}`
47
+ );
40
48
  }
41
- if (keyServers.some((server) => server.keyType !== import_key_server.KeyServerType.BonehFranklinBLS12381)) {
42
- throw new Error("Key type is not supported");
43
- }
44
- const ibeServers = new import_ibe.BonehFranklinBLS12381Services(keyServers);
45
49
  const key = await encryptionInput.generateKey();
46
- const ciphertext = await encryptionInput.encrypt(key);
47
- const shares = await split(key, ibeServers.size(), threshold);
48
- const fullId = (0, import_utils.createFullId)(import_ibe.DST, packageId, id);
49
- const encrypted_shares = ibeServers.encryptBatched(
50
- fullId,
50
+ const demKey = (0, import_kdf.deriveKey)(import_kdf.KeyPurpose.DEM, key);
51
+ const ciphertext = await encryptionInput.encrypt(demKey);
52
+ const shares = await split(key, keyServers.length, threshold);
53
+ const fullId = (0, import_utils2.createFullId)(import_ibe.DST, packageId, id);
54
+ const encryptedShares = encryptBatched(
55
+ keyServers,
56
+ kemType,
57
+ (0, import_bcs.fromHex)(fullId),
51
58
  shares.map(({ share, index }) => ({
52
59
  msg: share,
53
- info: new Uint8Array([index])
54
- }))
60
+ index
61
+ })),
62
+ (0, import_kdf.deriveKey)(import_kdf.KeyPurpose.EncryptedRandomness, key)
55
63
  );
56
- const services = ibeServers.getObjectIds().map((id2, i) => [id2, shares[i].index]);
64
+ const services = keyServers.map((server, i) => [
65
+ server.objectId,
66
+ shares[i].index
67
+ ]);
57
68
  return {
58
- encryptedObject: import_types.EncryptedObject.serialize({
69
+ encryptedObject: import_bcs2.EncryptedObject.serialize({
59
70
  version: 0,
60
- package_id: packageId,
71
+ packageId,
61
72
  id,
62
73
  services,
63
74
  threshold,
64
- encrypted_shares,
75
+ encryptedShares,
65
76
  ciphertext
66
77
  }).toBytes(),
67
- key
78
+ key: demKey
68
79
  };
69
80
  }
81
+ var KemType = /* @__PURE__ */ ((KemType2) => {
82
+ KemType2[KemType2["BonehFranklinBLS12381DemCCA"] = 0] = "BonehFranklinBLS12381DemCCA";
83
+ return KemType2;
84
+ })(KemType || {});
85
+ var DemType = /* @__PURE__ */ ((DemType2) => {
86
+ DemType2[DemType2["AesGcm256"] = 0] = "AesGcm256";
87
+ DemType2[DemType2["Hmac256Ctr"] = 1] = "Hmac256Ctr";
88
+ return DemType2;
89
+ })(DemType || {});
90
+ function encryptBatched(keyServers, kemType, id, shares, randomnessKey) {
91
+ switch (kemType) {
92
+ case 0 /* BonehFranklinBLS12381DemCCA */:
93
+ return new import_ibe.BonehFranklinBLS12381Services(keyServers).encryptBatched(
94
+ id,
95
+ shares,
96
+ randomnessKey
97
+ );
98
+ }
99
+ }
70
100
  async function split(secret, n, threshold) {
71
101
  if (n === 0 || threshold === 0 || threshold > n) {
72
- throw new Error("Invalid input");
102
+ throw new Error("Invalid threshold or number of shares");
73
103
  } else if (threshold === 1) {
74
104
  const result = [];
75
105
  for (let i = 0; i < n; i++) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/encrypt.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { split as externalSplit } from 'shamir-secret-sharing';\n\nimport type { EncryptionInput } from './aes.js';\nimport { BonehFranklinBLS12381Services, DST } from './ibe.js';\nimport type { KeyServer } from './key-server.js';\nimport { KeyServerType } from './key-server.js';\nimport { EncryptedObject } from './types.js';\nimport { createFullId } from './utils.js';\n\nexport const MAX_U8 = 255;\n\n/**\n * Given full ID and what key servers to use, return the encrypted message under the identity and return the bcs bytes of the encrypted object.\n *\n * @param keyServers - A list of KeyServers (same server can be used multiple times)\n * @param packageId - packageId\n * @param id - id\n * @param encryptionInput - Input to the encryption. Should be one of the EncryptionInput types, AesGcmEncryptionInput or Plain.\n * @param threshold - The threshold for the TSS encryption.\n * @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.\n * Since the key can be used to decrypt, it should not be shared but can be used eg. for backup.\n */\nexport async function encrypt<Input extends EncryptionInput>({\n\tkeyServers,\n\tthreshold,\n\tpackageId,\n\tid,\n\tencryptionInput,\n}: {\n\tkeyServers: KeyServer[];\n\tthreshold: number;\n\tpackageId: Uint8Array;\n\tid: Uint8Array;\n\tencryptionInput: Input;\n}): Promise<{\n\tencryptedObject: Uint8Array;\n\tkey: Uint8Array;\n}> {\n\t// Check inputs\n\tif (\n\t\tkeyServers.length < threshold ||\n\t\tthreshold === 0 ||\n\t\tkeyServers.length > MAX_U8 ||\n\t\tthreshold > MAX_U8 ||\n\t\tpackageId.length !== 32\n\t) {\n\t\tthrow new Error('Invalid input');\n\t}\n\tif (keyServers.some((server) => server.keyType !== KeyServerType.BonehFranklinBLS12381)) {\n\t\tthrow new Error('Key type is not supported');\n\t}\n\tconst ibeServers = new BonehFranklinBLS12381Services(keyServers);\n\n\t// Generate a random symmetric key and encrypt the encryption input using this key.\n\tconst key = await encryptionInput.generateKey();\n\tconst ciphertext = await encryptionInput.encrypt(key);\n\n\t// Split the symmetric key into shares and encrypt each share with the public keys of the key servers.\n\tconst shares = await split(key, ibeServers.size(), threshold);\n\n\t// Encrypt the shares with the public keys of the key servers.\n\tconst fullId = createFullId(DST, packageId, id);\n\tconst encrypted_shares = ibeServers.encryptBatched(\n\t\tfullId,\n\t\tshares.map(({ share, index }) => ({\n\t\t\tmsg: share,\n\t\t\tinfo: new Uint8Array([index]),\n\t\t})),\n\t);\n\n\t// Services and indices of their shares are stored as a tuple\n\tconst services: [Uint8Array, number][] = ibeServers\n\t\t.getObjectIds()\n\t\t.map((id, i) => [id, shares[i].index]);\n\n\treturn {\n\t\tencryptedObject: EncryptedObject.serialize({\n\t\t\tversion: 0,\n\t\t\tpackage_id: packageId,\n\t\t\tid,\n\t\t\tservices,\n\t\t\tthreshold,\n\t\t\tencrypted_shares,\n\t\t\tciphertext,\n\t\t}).toBytes(),\n\t\tkey,\n\t};\n}\n\nasync function split(\n\tsecret: Uint8Array,\n\tn: number,\n\tthreshold: number,\n): Promise<{ index: number; share: Uint8Array }[]> {\n\t// The externalSplit function is from the 'shamir-secret-sharing' package and requires t > 1 and n >= 2.\n\t// So we handle the special cases here.\n\tif (n === 0 || threshold === 0 || threshold > n) {\n\t\tthrow new Error('Invalid input');\n\t} else if (threshold === 1) {\n\t\t// If the threshold is 1, the secret is not split.\n\t\tconst result = [];\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\t// The shared polynomial is a constant in this case, so the index doesn't matter.\n\t\t\t// To make sure they are unique, we use a counter.\n\t\t\tresult.push({ share: secret, index: i });\n\t\t}\n\t\treturn Promise.resolve(result);\n\t}\n\n\treturn externalSplit(secret, n, threshold).then((share) =>\n\t\tshare.map((s) => ({\n\t\t\tshare: s.subarray(0, s.length - 1),\n\t\t\t// split() returns the share index in the last byte\n\t\t\tindex: s[s.length - 1],\n\t\t})),\n\t);\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mCAAuC;AAGvC,iBAAmD;AAEnD,wBAA8B;AAC9B,mBAAgC;AAChC,mBAA6B;AAEtB,MAAM,SAAS;AAatB,eAAsB,QAAuC;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,GASG;AAEF,MACC,WAAW,SAAS,aACpB,cAAc,KACd,WAAW,SAAS,UACpB,YAAY,UACZ,UAAU,WAAW,IAC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AAG,SAAS,EAAE;AAAA,IAAK,CAAC,UAChD,MAAM,IAAI,CAAC,OAAO;AAAA,MACjB,OAAO,EAAE,SAAS,GAAG,EAAE,SAAS,CAAC;AAAA;AAAA,MAEjC,OAAO,EAAE,EAAE,SAAS,CAAC;AAAA,IACtB,EAAE;AAAA,EACH;AACD;",
6
- "names": ["id", "externalSplit"]
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromHex } from '@mysten/bcs';\nimport { isValidSuiObjectId } from '@mysten/sui/utils';\nimport { split as externalSplit } from 'shamir-secret-sharing';\n\nimport type { IBEEncryptions } from './bcs.js';\nimport { EncryptedObject } from './bcs.js';\nimport type { EncryptionInput } from './dem.js';\nimport { UserError } from './error.js';\nimport { BonehFranklinBLS12381Services, DST } from './ibe.js';\nimport { deriveKey, KeyPurpose } from './kdf.js';\nimport type { KeyServer } from './key-server.js';\nimport { createFullId } from './utils.js';\n\nexport const MAX_U8 = 255;\n\n/**\n * Given full ID and what key servers to use, return the encrypted message under the identity and return the bcs bytes of the encrypted object.\n *\n * @param keyServers - A list of KeyServers (same server can be used multiple times)\n * @param kemType - The type of KEM to use.\n * @param packageId - packageId\n * @param id - id\n * @param encryptionInput - Input to the encryption. Should be one of the EncryptionInput types, AesGcmEncryptionInput or Plain.\n * @param threshold - The threshold for the TSS encryption.\n * @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.\n * Since the key can be used to decrypt, it should not be shared but can be used eg. for backup.\n */\nexport async function encrypt({\n\tkeyServers,\n\tkemType,\n\tthreshold,\n\tpackageId,\n\tid,\n\tencryptionInput,\n}: {\n\tkeyServers: KeyServer[];\n\tkemType: KemType;\n\tthreshold: number;\n\tpackageId: string;\n\tid: string;\n\tencryptionInput: EncryptionInput;\n}): Promise<{\n\tencryptedObject: Uint8Array;\n\tkey: Uint8Array;\n}> {\n\t// Check inputs\n\tif (\n\t\tkeyServers.length < threshold ||\n\t\tthreshold === 0 ||\n\t\tkeyServers.length > MAX_U8 ||\n\t\tthreshold > MAX_U8 ||\n\t\t!isValidSuiObjectId(packageId)\n\t) {\n\t\tthrow new UserError(\n\t\t\t`Invalid key servers or threshold ${threshold} for ${keyServers.length} key servers for package ${packageId}`,\n\t\t);\n\t}\n\n\t// Generate a random symmetric key and encrypt the encryption input using this key.\n\tconst key = await encryptionInput.generateKey();\n\tconst demKey = deriveKey(KeyPurpose.DEM, key);\n\tconst ciphertext = await encryptionInput.encrypt(demKey);\n\n\t// Split the symmetric key into shares and encrypt each share with the public keys of the key servers.\n\tconst shares = await split(key, keyServers.length, threshold);\n\n\t// Encrypt the shares with the public keys of the key servers.\n\tconst fullId = createFullId(DST, packageId, id);\n\tconst encryptedShares = encryptBatched(\n\t\tkeyServers,\n\t\tkemType,\n\t\tfromHex(fullId),\n\t\tshares.map(({ share, index }) => ({\n\t\t\tmsg: share,\n\t\t\tindex,\n\t\t})),\n\t\tderiveKey(KeyPurpose.EncryptedRandomness, key),\n\t);\n\n\t// Services and indices of their shares are stored as a tuple\n\tconst services: [string, number][] = keyServers.map((server, i) => [\n\t\tserver.objectId,\n\t\tshares[i].index,\n\t]);\n\n\treturn {\n\t\tencryptedObject: EncryptedObject.serialize({\n\t\t\tversion: 0,\n\t\t\tpackageId,\n\t\t\tid,\n\t\t\tservices,\n\t\t\tthreshold,\n\t\t\tencryptedShares,\n\t\t\tciphertext,\n\t\t}).toBytes(),\n\t\tkey: demKey,\n\t};\n}\n\nexport enum KemType {\n\tBonehFranklinBLS12381DemCCA = 0,\n}\n\nexport enum DemType {\n\tAesGcm256 = 0,\n\tHmac256Ctr = 1,\n}\n\nfunction encryptBatched(\n\tkeyServers: KeyServer[],\n\tkemType: KemType,\n\tid: Uint8Array,\n\tshares: { msg: Uint8Array; index: number }[],\n\trandomnessKey: Uint8Array,\n): typeof IBEEncryptions.$inferType {\n\tswitch (kemType) {\n\t\tcase KemType.BonehFranklinBLS12381DemCCA:\n\t\t\treturn new BonehFranklinBLS12381Services(keyServers).encryptBatched(\n\t\t\t\tid,\n\t\t\t\tshares,\n\t\t\t\trandomnessKey,\n\t\t\t);\n\t}\n}\n\nasync function split(\n\tsecret: Uint8Array,\n\tn: number,\n\tthreshold: number,\n): Promise<{ index: number; share: Uint8Array }[]> {\n\t// The externalSplit function is from the 'shamir-secret-sharing' package and requires t > 1 and n >= 2.\n\t// So we handle the special cases here.\n\tif (n === 0 || threshold === 0 || threshold > n) {\n\t\tthrow new Error('Invalid threshold or number of shares');\n\t} else if (threshold === 1) {\n\t\t// If the threshold is 1, the secret is not split.\n\t\tconst result = [];\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\t// The shared polynomial is a constant in this case, so the index doesn't matter.\n\t\t\t// To make sure they are unique, we use a counter.\n\t\t\tresult.push({ share: secret, index: i });\n\t\t}\n\t\treturn Promise.resolve(result);\n\t}\n\n\treturn externalSplit(secret, n, threshold).then((share) =>\n\t\tshare.map((s) => ({\n\t\t\tshare: s.subarray(0, s.length - 1),\n\t\t\t// split() returns the share index in the last byte\n\t\t\tindex: s[s.length - 1],\n\t\t})),\n\t);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAwB;AACxB,mBAAmC;AACnC,mCAAuC;AAGvC,IAAAA,cAAgC;AAEhC,mBAA0B;AAC1B,iBAAmD;AACnD,iBAAsC;AAEtC,IAAAC,gBAA6B;AAEtB,MAAM,SAAS;AActB,eAAsB,QAAQ;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,GAUG;AAEF,MACC,WAAW,SAAS,aACpB,cAAc,KACd,WAAW,SAAS,UACpB,YAAY,UACZ,KAAC,iCAAmB,SAAS,GAC5B;AACD,UAAM,IAAI;AAAA,MACT,oCAAoC,SAAS,QAAQ,WAAW,MAAM,4BAA4B,SAAS;AAAA,IAC5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AAK,YAAY,GAAG;AAChD,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACxD,WAAW,cAAc,GAAG;AAE3B,UAAM,SAAS,CAAC;AAChB,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAG3B,aAAO,KAAK,EAAE,OAAO,QAAQ,OAAO,EAAE,CAAC;AAAA,IACxC;AACA,WAAO,QAAQ,QAAQ,MAAM;AAAA,EAC9B;AAEA,aAAO,6BAAAC,OAAc,QAAQ,GAAG,SAAS,EAAE;AAAA,IAAK,CAAC,UAChD,MAAM,IAAI,CAAC,OAAO;AAAA,MACjB,OAAO,EAAE,SAAS,GAAG,EAAE,SAAS,CAAC;AAAA;AAAA,MAEjC,OAAO,EAAE,EAAE,SAAS,CAAC;AAAA,IACtB,EAAE;AAAA,EACH;AACD;",
6
+ "names": ["import_bcs", "import_utils", "KemType", "DemType", "externalSplit"]
7
7
  }
@@ -0,0 +1,58 @@
1
+ export declare class SealError extends Error {
2
+ }
3
+ export declare class UserError extends SealError {
4
+ }
5
+ export declare class SealAPIError extends SealError {
6
+ #private;
7
+ requestId?: string | undefined;
8
+ status?: number | undefined;
9
+ constructor(message: string, requestId?: string | undefined, status?: number | undefined);
10
+ static assertResponse(response: Response, requestId: string): Promise<void>;
11
+ }
12
+ export declare class InvalidPTBError extends SealAPIError {
13
+ constructor(requestId?: string);
14
+ }
15
+ export declare class InvalidPackageError extends SealAPIError {
16
+ constructor(requestId?: string);
17
+ }
18
+ export declare class OldPackageError extends SealAPIError {
19
+ constructor(requestId?: string);
20
+ }
21
+ export declare class InvalidUserSignatureError extends SealAPIError {
22
+ constructor(requestId?: string);
23
+ }
24
+ export declare class InvalidSessionKeySignatureError extends SealAPIError {
25
+ constructor(requestId?: string);
26
+ }
27
+ /** Server error indicating that the user does not have access to one or more of the requested keys */
28
+ export declare class NoAccessError extends SealAPIError {
29
+ constructor(requestId?: string);
30
+ }
31
+ /** Server error indicating that the session key has expired */
32
+ export declare class ExpiredSessionKeyError extends SealAPIError {
33
+ constructor(requestId?: string);
34
+ }
35
+ /** Internal server error, caller should retry */
36
+ export declare class InternalError extends SealAPIError {
37
+ constructor(requestId?: string);
38
+ }
39
+ /** General server errors that are not specific to the Seal API (e.g., 404 "Not Found") */
40
+ export declare class GeneralError extends SealAPIError {
41
+ }
42
+ export declare class InvalidPersonalMessageSignatureError extends UserError {
43
+ }
44
+ export declare class InvalidGetObjectError extends UserError {
45
+ }
46
+ export declare class UnsupportedFeatureError extends UserError {
47
+ }
48
+ export declare class UnsupportedNetworkError extends UserError {
49
+ }
50
+ export declare class InvalidKeyServerError extends UserError {
51
+ }
52
+ export declare class InvalidCiphertextError extends UserError {
53
+ }
54
+ export declare class InvalidThresholdError extends UserError {
55
+ }
56
+ export declare class InconsistentKeyServersError extends UserError {
57
+ }
58
+ export declare function toMajorityError(errors: Error[]): Error;