@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,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/client.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { SuiClient } from '@mysten/sui/client';\n\nimport { EncryptedObject } from './bcs.js';\nimport { G1Element, G2Element } from './bls12381.js';\nimport { decrypt } from './decrypt.js';\nimport type { EncryptionInput } from './dem.js';\nimport { AesGcm256, Hmac256Ctr } from './dem.js';\nimport { DemType, encrypt, KemType } from './encrypt.js';\nimport {\n\tInconsistentKeyServersError,\n\tInvalidKeyServerError,\n\tInvalidThresholdError,\n\ttoMajorityError,\n} from './error.js';\nimport { BonehFranklinBLS12381Services, DST } from './ibe.js';\nimport { KeyServerType, retrieveKeyServers, verifyKeyServer } from './key-server.js';\nimport type { KeyServer } from './key-server.js';\nimport { fetchKeysForAllIds } from './keys.js';\nimport type { SessionKey } from './session-key.js';\nimport type { KeyCacheKey } from './types.js';\nimport { createFullId } from './utils.js';\n\n/**\n * Configuration options for initializing a SealClient\n * @property serverObjectIds: Array of object IDs for the key servers to use.\n * @property verifyKeyServers: Whether to verify the key servers' authenticity.\n * \t Should be false if servers are pre-verified (e.g., getAllowlistedKeyServers).\n * \t Defaults to true.\n * @property timeout: Timeout in milliseconds for network requests. Defaults to 10 seconds.\n */\nexport interface SealClientOptions {\n\tsuiClient: SuiClient;\n\tserverObjectIds: string[];\n\tverifyKeyServers?: boolean;\n\ttimeout?: number;\n}\n\nexport class SealClient {\n\t#suiClient: SuiClient;\n\t#serverObjectIds: string[];\n\t#verifyKeyServers: boolean;\n\t#keyServers: Promise<KeyServer[]> | null = null;\n\t// A caching map for: fullId:object_id -> partial key.\n\t#cachedKeys = new Map<KeyCacheKey, G1Element>();\n\t#timeout: number;\n\n\tconstructor(options: SealClientOptions) {\n\t\tthis.#suiClient = options.suiClient;\n\t\tthis.#serverObjectIds = options.serverObjectIds;\n\t\tthis.#verifyKeyServers = options.verifyKeyServers ?? true;\n\t\tthis.#timeout = options.timeout ?? 10_000;\n\t}\n\n\t/**\n\t * Return an encrypted message under the identity.\n\t *\n\t * @param kemType - The type of KEM to use.\n\t * @param demType - The type of DEM to use.\n\t * @param threshold - The threshold for the TSS encryption.\n\t * @param packageId - the packageId namespace.\n\t * @param id - the identity to use.\n\t * @param data - the data to encrypt.\n\t * @param aad - optional additional authenticated data.\n\t * @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\t * \tSince the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.\n\t */\n\tasync encrypt({\n\t\tkemType = KemType.BonehFranklinBLS12381DemCCA,\n\t\tdemType = DemType.AesGcm256,\n\t\tthreshold,\n\t\tpackageId,\n\t\tid,\n\t\tdata,\n\t\taad = new Uint8Array(),\n\t}: {\n\t\tkemType?: KemType;\n\t\tdemType?: DemType;\n\t\tthreshold: number;\n\t\tpackageId: string;\n\t\tid: string;\n\t\tdata: Uint8Array;\n\t\taad?: Uint8Array;\n\t}) {\n\t\t// TODO: Verify that packageId is first version of its package (else throw error).\n\t\treturn encrypt({\n\t\t\tkeyServers: await this.getKeyServers(),\n\t\t\tkemType,\n\t\t\tthreshold,\n\t\t\tpackageId,\n\t\t\tid,\n\t\t\tencryptionInput: this.#createEncryptionInput(demType, data, aad),\n\t\t});\n\t}\n\n\t#createEncryptionInput(type: DemType, data: Uint8Array, aad: Uint8Array): EncryptionInput {\n\t\tswitch (type) {\n\t\t\tcase DemType.AesGcm256:\n\t\t\t\treturn new AesGcm256(data, aad);\n\t\t\tcase DemType.Hmac256Ctr:\n\t\t\t\treturn new Hmac256Ctr(data, aad);\n\t\t}\n\t}\n\n\t/**\n\t * Decrypt the given encrypted bytes using cached keys.\n\t * Calls fetchKeys in case one or more of the required keys is not cached yet.\n\t * The function throws an error if the client's key servers are not a subset of\n\t * the encrypted object's key servers (including the same weights) or if the\n\t * threshold cannot be met.\n\t *\n\t * @param data - The encrypted bytes to decrypt.\n\t * @param sessionKey - The session key to use.\n\t * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).\n\t * @returns - The decrypted plaintext corresponding to ciphertext.\n\t */\n\tasync decrypt({\n\t\tdata,\n\t\tsessionKey,\n\t\ttxBytes,\n\t}: {\n\t\tdata: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t\ttxBytes: Uint8Array;\n\t}) {\n\t\tconst encryptedObject = EncryptedObject.parse(data);\n\n\t\tthis.#validateEncryptionServices(\n\t\t\tencryptedObject.services.map((s) => s[0]),\n\t\t\tencryptedObject.threshold,\n\t\t);\n\n\t\tawait this.fetchKeys({\n\t\t\tids: [encryptedObject.id],\n\t\t\ttxBytes,\n\t\t\tsessionKey,\n\t\t\tthreshold: encryptedObject.threshold,\n\t\t});\n\n\t\treturn decrypt({ encryptedObject, keys: this.#cachedKeys });\n\t}\n\n\t#validateEncryptionServices(services: string[], threshold: number) {\n\t\t// Check that the client's key servers are a subset of the encrypted object's key servers.\n\t\tconst serverObjectIdsMap = new Map<string, number>();\n\t\tfor (const objectId of this.#serverObjectIds) {\n\t\t\tserverObjectIdsMap.set(objectId, (serverObjectIdsMap.get(objectId) ?? 0) + 1);\n\t\t}\n\t\tconst servicesMap = new Map<string, number>();\n\t\tfor (const service of services) {\n\t\t\tservicesMap.set(service, (servicesMap.get(service) ?? 0) + 1);\n\t\t}\n\t\tfor (const [objectId, count] of serverObjectIdsMap) {\n\t\t\tif (servicesMap.get(objectId) !== count) {\n\t\t\t\tthrow new InconsistentKeyServersError(\n\t\t\t\t\t`Client's key servers must be a subset of the encrypted object's key servers`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t// Check that the threshold can be met with the client's key servers.\n\t\tif (threshold > this.#serverObjectIds.length) {\n\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t`Invalid threshold ${threshold} for ${this.#serverObjectIds.length} servers`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync getKeyServers() {\n\t\tif (!this.#keyServers) {\n\t\t\tthis.#keyServers = this.#loadKeyServers().catch((error) => {\n\t\t\t\tthis.#keyServers = null;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\n\t\treturn this.#keyServers;\n\t}\n\n\tasync #loadKeyServers(): Promise<KeyServer[]> {\n\t\tconst keyServers = await retrieveKeyServers({\n\t\t\tobjectIds: this.#serverObjectIds,\n\t\t\tclient: this.#suiClient,\n\t\t});\n\n\t\tif (keyServers.length === 0) {\n\t\t\tthrow new InvalidKeyServerError('No key servers found');\n\t\t}\n\n\t\tif (this.#verifyKeyServers) {\n\t\t\tawait Promise.all(\n\t\t\t\tkeyServers.map(async (server) => {\n\t\t\t\t\tif (!(await verifyKeyServer(server, this.#timeout))) {\n\t\t\t\t\t\tthrow new InvalidKeyServerError(`Key server ${server.objectId} is not valid`);\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\treturn keyServers;\n\t}\n\n\t/**\n\t * Fetch keys from the key servers and update the cache.\n\t *\n\t * It is recommended to call this function once for all ids of all encrypted obejcts if\n\t * there are multiple, then call decrypt for each object. This avoids calling fetchKey\n\t * individually for each decrypt.\n\t *\n\t * @param ids - The ids of the encrypted objects.\n\t * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).\n\t * @param sessionKey - The session key to use.\n\t * @param threshold - The threshold for the TSS encryptions. The function returns when a threshold of key servers had returned keys for all ids.\n\t */\n\tasync fetchKeys({\n\t\tids,\n\t\ttxBytes,\n\t\tsessionKey,\n\t\tthreshold,\n\t}: {\n\t\tids: string[];\n\t\ttxBytes: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t\tthreshold: number;\n\t}) {\n\t\tconst keyServers = await this.getKeyServers();\n\t\tif (threshold > keyServers.length || threshold < 1 || keyServers.length < 1) {\n\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t`Invalid threshold ${threshold} for ${keyServers.length} servers`,\n\t\t\t);\n\t\t}\n\n\t\tlet completedServerCount = 0;\n\t\tconst remainingKeyServers = new Set<KeyServer>();\n\t\tconst fullIds = ids.map((id) => createFullId(DST, sessionKey.getPackageId(), id));\n\n\t\t// Count a server as completed if it has keys for all fullIds.\n\t\t// Duplicated key server ids will be counted towards the threshold.\n\t\tfor (const server of keyServers) {\n\t\t\tlet hasAllKeys = true;\n\t\t\tfor (const fullId of fullIds) {\n\t\t\t\tif (!this.#cachedKeys.has(`${fullId}:${server.objectId}`)) {\n\t\t\t\t\thasAllKeys = false;\n\t\t\t\t\tremainingKeyServers.add(server);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasAllKeys) {\n\t\t\t\tcompletedServerCount++;\n\t\t\t}\n\t\t}\n\n\t\t// Return early if we have enough keys from cache.\n\t\tif (completedServerCount >= threshold) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Check server validities.\n\t\tfor (const server of remainingKeyServers) {\n\t\t\tif (server.keyType !== KeyServerType.BonehFranklinBLS12381) {\n\t\t\t\tthrow new InvalidKeyServerError(\n\t\t\t\t\t`Server ${server.objectId} has invalid key type: ${server.keyType}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst cert = await sessionKey.getCertificate();\n\t\tconst signedRequest = await sessionKey.createRequestParams(txBytes);\n\n\t\tconst controller = new AbortController();\n\t\tconst errors: Error[] = [];\n\n\t\tconst keyFetches = [...remainingKeyServers].map(async (server) => {\n\t\t\ttry {\n\t\t\t\tconst allKeys = await fetchKeysForAllIds(\n\t\t\t\t\tserver.url,\n\t\t\t\t\tsignedRequest.requestSignature,\n\t\t\t\t\ttxBytes,\n\t\t\t\t\tsignedRequest.decryptionKey,\n\t\t\t\t\tcert,\n\t\t\t\t\tthis.#timeout,\n\t\t\t\t\tcontroller.signal,\n\t\t\t\t);\n\t\t\t\t// Check validity of the keys and add them to the cache.\n\t\t\t\tlet receivedIds = new Set<string>();\n\t\t\t\tfor (const { fullId, key } of allKeys) {\n\t\t\t\t\tconst keyElement = G1Element.fromBytes(key);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!BonehFranklinBLS12381Services.verifyUserSecretKey(\n\t\t\t\t\t\t\tkeyElement,\n\t\t\t\t\t\t\tfullId,\n\t\t\t\t\t\t\tG2Element.fromBytes(server.pk),\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconsole.warn('Received invalid key from key server ' + server.objectId);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthis.#cachedKeys.set(`${fullId}:${server.objectId}`, keyElement);\n\t\t\t\t\treceivedIds.add(fullId);\n\t\t\t\t}\n\n\t\t\t\t// Check if all the receivedIds are consistent with the requested fullIds.\n\t\t\t\t// If so, consider the key server got all keys and mark as completed.\n\t\t\t\tconst expectedIds = new Set(fullIds);\n\t\t\t\tconst hasAllKeys =\n\t\t\t\t\treceivedIds.size === expectedIds.size &&\n\t\t\t\t\t[...receivedIds].every((id) => expectedIds.has(id));\n\n\t\t\t\t// Return early if the completed servers is more than threshold.\n\t\t\t\tif (hasAllKeys) {\n\t\t\t\t\tcompletedServerCount++;\n\t\t\t\t\tif (completedServerCount >= threshold) {\n\t\t\t\t\t\tcontroller.abort();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\terrors.push(error as Error);\n\t\t\t\t}\n\t\t\t\t// If there are too many errors that the threshold is not attainable, return early with error.\n\t\t\t\tif (remainingKeyServers.size - errors.length < threshold - completedServerCount) {\n\t\t\t\t\tcontroller.abort(error);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tawait Promise.allSettled(keyFetches);\n\n\t\tif (completedServerCount < threshold) {\n\t\t\tthrow toMajorityError(errors);\n\t\t}\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;AAAA;AAKA,SAAS,uBAAuB;AAChC,SAAS,WAAW,iBAAiB;AACrC,SAAS,eAAe;AAExB,SAAS,WAAW,kBAAkB;AACtC,SAAS,SAAS,SAAS,eAAe;AAC1C;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,+BAA+B,WAAW;AACnD,SAAS,eAAe,oBAAoB,uBAAuB;AAEnE,SAAS,0BAA0B;AAGnC,SAAS,oBAAoB;AAiBtB,MAAM,WAAW;AAAA,EASvB,YAAY,SAA4B;AATlC;AACN;AACA;AACA;AACA,oCAA2C;AAE3C;AAAA,oCAAc,oBAAI,IAA4B;AAC9C;AAGC,uBAAK,YAAa,QAAQ;AAC1B,uBAAK,kBAAmB,QAAQ;AAChC,uBAAK,mBAAoB,QAAQ,oBAAoB;AACrD,uBAAK,UAAW,QAAQ,WAAW;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeA,M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A,EAC7E;AACA,QAAM,cAAc,oBAAI,IAAoB;AAC5C,aAAW,WAAW,UAAU;AAC/B,gBAAY,IAAI,UAAU,YAAY,IAAI,OAAO,KAAK,KAAK,CAAC;AAAA,EAC7D;AACA,aAAW,CAAC,UAAU,KAAK,KAAK,oBAAoB;AACnD,QAAI,YAAY,IAAI,QAAQ,MAAM,OAAO;AACxC,YAAM,IAAI;AAAA,QACT;AAAA,MACD;AAAA,IACD;AAAA,EACD;AAEA,MAAI,YAAY,mBAAK,kBAAiB,QAAQ;AAC7C,UAAM,IAAI;AAAA,MACT,qBAAqB,SAAS,QAAQ,mBAAK,kBAAiB,MAAM;AAAA,IACnE;AAAA,EACD;AACD;AAaM,oBAAe,iBAAyB;AAC7C,QAAM,aAAa,MAAM,mBAAmB;AAAA,IAC3C,WAAW,mBAAK;AAAA,IAChB,QAAQ,mBAAK;AAAA,EACd,CAAC;AAED,MAAI,WAAW,WAAW,GAAG;AAC5B,UAAM,IAAI,sBAAsB,sBAAsB;AAAA,EACvD;AAEA,MAAI,mBAAK,oBAAmB;AAC3B,UAAM,QAAQ;AAAA,MACb,WAAW,IAAI,OAAO,WAAW;AAChC,YAAI,CAAE,MAAM,gBAAgB,QAAQ,mBAAK,SAAQ,GAAI;AACpD,gBAAM,IAAI,sBAAsB,cAAc,OAAO,QAAQ,eAAe;AAAA,QAC7E;AAAA,MACD,CAAC;AAAA,IACF;AAAA,EACD;AAEA,SAAO;AACR;",
6
+ "names": []
7
+ }
@@ -0,0 +1,15 @@
1
+ import type { EncryptedObject } from './bcs.js';
2
+ import type { G1Element } from './bls12381.js';
3
+ import type { KeyCacheKey } from './types.js';
4
+ export interface DecryptOptions {
5
+ encryptedObject: typeof EncryptedObject.$inferType;
6
+ keys: Map<KeyCacheKey, G1Element>;
7
+ }
8
+ /**
9
+ * Decrypt the given encrypted bytes with the given cached secret keys for the full ID.
10
+ * It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers
11
+ * otherwise, this will throw an error.
12
+ *
13
+ * @returns - The decrypted plaintext corresponding to ciphertext.
14
+ */
15
+ export declare function decrypt({ encryptedObject, keys }: DecryptOptions): Promise<Uint8Array>;
@@ -0,0 +1,74 @@
1
+ import { fromHex } from "@mysten/bcs";
2
+ import { combine as externalCombine } from "shamir-secret-sharing";
3
+ import { G2Element } from "./bls12381.js";
4
+ import { AesGcm256, Hmac256Ctr } from "./dem.js";
5
+ import { InvalidCiphertextError, UnsupportedFeatureError } from "./error.js";
6
+ import { BonehFranklinBLS12381Services, DST } from "./ibe.js";
7
+ import { deriveKey, KeyPurpose } from "./kdf.js";
8
+ import { createFullId } from "./utils.js";
9
+ async function decrypt({ encryptedObject, keys }) {
10
+ if (!encryptedObject.encryptedShares.BonehFranklinBLS12381) {
11
+ throw new UnsupportedFeatureError("Encryption mode not supported");
12
+ }
13
+ const fullId = createFullId(DST, encryptedObject.packageId, encryptedObject.id);
14
+ const inKeystore = encryptedObject.services.map((_, i) => i).filter((i) => keys.has(`${fullId}:${encryptedObject.services[i][0]}`));
15
+ if (inKeystore.length < encryptedObject.threshold) {
16
+ throw new Error("Not enough shares. Please fetch more keys.");
17
+ }
18
+ const encryptedShares = encryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedShares;
19
+ if (encryptedShares.length !== encryptedObject.services.length) {
20
+ throw new InvalidCiphertextError(
21
+ `Mismatched shares ${encryptedShares.length} and services ${encryptedObject.services.length}`
22
+ );
23
+ }
24
+ const nonce = G2Element.fromBytes(encryptedObject.encryptedShares.BonehFranklinBLS12381.nonce);
25
+ const shares = inKeystore.map((i) => {
26
+ const [objectId, index] = encryptedObject.services[i];
27
+ const share = BonehFranklinBLS12381Services.decrypt(
28
+ nonce,
29
+ keys.get(`${fullId}:${objectId}`),
30
+ encryptedShares[i],
31
+ fromHex(fullId),
32
+ [objectId, index]
33
+ );
34
+ return { index, share };
35
+ });
36
+ const key = await combine(shares);
37
+ const demKey = deriveKey(KeyPurpose.DEM, key);
38
+ if (encryptedObject.ciphertext.Aes256Gcm) {
39
+ try {
40
+ return AesGcm256.decrypt(demKey, encryptedObject.ciphertext);
41
+ } catch {
42
+ throw new Error("Decryption failed");
43
+ }
44
+ } else if (encryptedObject.ciphertext.Plain) {
45
+ return demKey;
46
+ } else if (encryptedObject.ciphertext.Hmac256Ctr) {
47
+ try {
48
+ return Hmac256Ctr.decrypt(demKey, encryptedObject.ciphertext);
49
+ } catch {
50
+ throw new Error("Decryption failed");
51
+ }
52
+ } else {
53
+ throw new Error("Invalid encrypted object");
54
+ }
55
+ }
56
+ async function combine(shares) {
57
+ if (shares.length === 0) {
58
+ throw new Error("Invalid shares length");
59
+ } else if (shares.length === 1) {
60
+ return Promise.resolve(shares[0].share);
61
+ }
62
+ return externalCombine(
63
+ shares.map(({ index, share }) => {
64
+ const packedShare = new Uint8Array(share.length + 1);
65
+ packedShare.set(share, 0);
66
+ packedShare[share.length] = index;
67
+ return packedShare;
68
+ })
69
+ );
70
+ }
71
+ export {
72
+ decrypt
73
+ };
74
+ //# 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": "AAGA,SAAS,eAAe;AACxB,SAAS,WAAW,uBAAuB;AAI3C,SAAS,iBAAiB;AAC1B,SAAS,WAAW,kBAAkB;AACtC,SAAS,wBAAwB,+BAA+B;AAChE,SAAS,+BAA+B,WAAW;AACnD,SAAS,WAAW,kBAAkB;AAEtC,SAAS,oBAAoB;AAc7B,eAAsB,QAAQ,EAAE,iBAAiB,KAAK,GAAwC;AAC7F,MAAI,CAAC,gBAAgB,gBAAgB,uBAAuB;AAC3D,UAAM,IAAI,wBAAwB,+BAA+B;AAAA,EAClE;AAEA,QAAM,SAAS,aAAa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AAO,WAAW,QAAQ,QAAQ,gBAAgB,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,SAAO;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": []
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,153 @@
1
+ import { bcs } from "@mysten/bcs";
2
+ import { equalBytes } from "@noble/curves/abstract/utils";
3
+ import { hmac } from "@noble/hashes/hmac";
4
+ import { sha3_256 } from "@noble/hashes/sha3";
5
+ import { InvalidCiphertextError } from "./error.js";
6
+ import { xorUnchecked } from "./utils.js";
7
+ const iv = Uint8Array.from([
8
+ 138,
9
+ 55,
10
+ 153,
11
+ 253,
12
+ 198,
13
+ 46,
14
+ 121,
15
+ 219,
16
+ 160,
17
+ 128,
18
+ 89,
19
+ 7,
20
+ 214,
21
+ 156,
22
+ 148,
23
+ 220
24
+ ]);
25
+ async function generateAesKey() {
26
+ const key = await crypto.subtle.generateKey(
27
+ {
28
+ name: "AES-GCM",
29
+ length: 256
30
+ },
31
+ true,
32
+ ["encrypt", "decrypt"]
33
+ );
34
+ return await crypto.subtle.exportKey("raw", key).then((keyData) => new Uint8Array(keyData));
35
+ }
36
+ class AesGcm256 {
37
+ constructor(msg, aad) {
38
+ this.plaintext = msg;
39
+ this.aad = aad;
40
+ }
41
+ generateKey() {
42
+ return generateAesKey();
43
+ }
44
+ async encrypt(key) {
45
+ const aesCryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);
46
+ const blob = new Uint8Array(
47
+ await crypto.subtle.encrypt(
48
+ {
49
+ name: "AES-GCM",
50
+ iv,
51
+ additionalData: this.aad
52
+ },
53
+ aesCryptoKey,
54
+ this.plaintext
55
+ )
56
+ );
57
+ return {
58
+ Aes256Gcm: {
59
+ blob,
60
+ aad: this.aad ?? []
61
+ }
62
+ };
63
+ }
64
+ static async decrypt(key, ciphertext) {
65
+ if (!("Aes256Gcm" in ciphertext)) {
66
+ throw new InvalidCiphertextError(`Invalid ciphertext ${ciphertext}`);
67
+ }
68
+ const aesCryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
69
+ return new Uint8Array(
70
+ await crypto.subtle.decrypt(
71
+ {
72
+ name: "AES-GCM",
73
+ iv,
74
+ additionalData: new Uint8Array(ciphertext.Aes256Gcm.aad ?? [])
75
+ },
76
+ aesCryptoKey,
77
+ new Uint8Array(ciphertext.Aes256Gcm.blob)
78
+ )
79
+ );
80
+ }
81
+ }
82
+ class Plain {
83
+ async encrypt(_key) {
84
+ return {
85
+ Plain: {}
86
+ };
87
+ }
88
+ generateKey() {
89
+ return generateAesKey();
90
+ }
91
+ }
92
+ class Hmac256Ctr {
93
+ constructor(msg, aad) {
94
+ this.plaintext = msg;
95
+ this.aad = aad;
96
+ }
97
+ generateKey() {
98
+ return generateAesKey();
99
+ }
100
+ async encrypt(key) {
101
+ const blob = Hmac256Ctr.encryptInCtrMode(key, this.plaintext);
102
+ const mac = Hmac256Ctr.computeMac(key, this.aad, blob);
103
+ return {
104
+ Hmac256Ctr: {
105
+ blob,
106
+ mac,
107
+ aad: this.aad ?? []
108
+ }
109
+ };
110
+ }
111
+ static async decrypt(key, ciphertext) {
112
+ if (!("Hmac256Ctr" in ciphertext)) {
113
+ throw new InvalidCiphertextError(`Invalid ciphertext ${ciphertext}`);
114
+ }
115
+ const aad = new Uint8Array(ciphertext.Hmac256Ctr.aad ?? []);
116
+ const blob = new Uint8Array(ciphertext.Hmac256Ctr.blob);
117
+ const mac = Hmac256Ctr.computeMac(key, aad, blob);
118
+ if (!equalBytes(mac, new Uint8Array(ciphertext.Hmac256Ctr.mac))) {
119
+ throw new InvalidCiphertextError(`Invalid MAC ${mac}`);
120
+ }
121
+ return Hmac256Ctr.encryptInCtrMode(key, blob);
122
+ }
123
+ static computeMac(key, aad, ciphertext) {
124
+ const macKey = hmac(sha3_256, key, MacKeyTag);
125
+ const macInput = new Uint8Array([...toBytes(aad.length), ...aad, ...ciphertext]);
126
+ const mac = hmac(sha3_256, macKey, macInput);
127
+ return mac;
128
+ }
129
+ static encryptInCtrMode(key, msg) {
130
+ const blockSize = 32;
131
+ let result = Uint8Array.from({ length: msg.length }, () => 0);
132
+ const encryptionKey = hmac(sha3_256, key, EncryptionKeyTag);
133
+ for (let i = 0; i * blockSize < msg.length; i++) {
134
+ const block = msg.slice(i * blockSize, (i + 1) * blockSize);
135
+ let mask = hmac(sha3_256, encryptionKey, toBytes(i));
136
+ const encryptedBlock = xorUnchecked(block, mask);
137
+ result.set(encryptedBlock, i * blockSize);
138
+ }
139
+ return result;
140
+ }
141
+ }
142
+ function toBytes(n) {
143
+ return bcs.u64().serialize(n).toBytes();
144
+ }
145
+ const EncryptionKeyTag = new Uint8Array([1]);
146
+ const MacKeyTag = new Uint8Array([2]);
147
+ export {
148
+ AesGcm256,
149
+ Hmac256Ctr,
150
+ Plain,
151
+ iv
152
+ };
153
+ //# 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": "AAGA,SAAS,WAAW;AACpB,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAGzB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAGtB,MAAM,KAAK,WAAW,KAAK;AAAA,EACjC;AAAA,EAAK;AAAA,EAAI;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AAAA,EAAI;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AAAA,EAAI;AAAA,EAAG;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AACvE,CAAC;AAED,eAAe,iBAAsC;AACpD,QAAM,MAAM,MAAM,OAAO,OAAO;AAAA,IAC/B;AAAA,MACC,MAAM;AAAA,MACN,QAAQ;AAAA,IACT;AAAA,IACA;AAAA,IACA,CAAC,WAAW,SAAS;AAAA,EACtB;AACA,SAAO,MAAM,OAAO,OAAO,UAAU,OAAO,GAAG,EAAE,KAAK,CAAC,YAAY,IAAI,WAAW,OAAO,CAAC;AAC3F;AAOO,MAAM,UAAqC;AAAA,EAIjD,YAAY,KAAiB,KAAiB;AAC7C,SAAK,YAAY;AACjB,SAAK,MAAM;AAAA,EACZ;AAAA,EAEA,cAAmC;AAClC,WAAO,eAAe;AAAA,EACvB;AAAA,EAEA,MAAM,QAA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AAU,eAAe,QAAQ,CAAC,CAAC;AACnD,YAAM,iBAAiB,aAAa,OAAO,IAAI;AAC/C,aAAO,IAAI,gBAAgB,IAAI,SAAS;AAAA,IACzC;AACA,WAAO;AAAA,EACR;AACD;AAKA,SAAS,QAAQ,GAAuB;AACvC,SAAO,IAAI,IAAI,EAAE,UAAU,CAAC,EAAE,QAAQ;AACvC;AAEA,MAAM,mBAAmB,IAAI,WAAW,CAAC,CAAC,CAAC;AAC3C,MAAM,YAAY,IAAI,WAAW,CAAC,CAAC,CAAC;",
6
+ "names": []
7
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/elgamal.ts"],
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// /**\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": "AAGA,SAAS,WAAW,WAAW,cAAc;AAMtC,SAAS,eAAe,IAAgB,YAAkD;AAChG,SAAO,QAAQ,OAAO,UAAU,EAAE,GAAG;AAAA,IACpC,UAAU,UAAU,WAAW,CAAC,CAAC;AAAA,IACjC,UAAU,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,OAAO,OAAO,EAAE,QAAQ;AAChC;AAGO,SAAS,YAAY,IAA4B;AACvD,SAAO,UAAU,UAAU,EAAE,SAAS,OAAO,UAAU,EAAE,CAAC,EAAE,QAAQ;AACrE;AAGO,SAAS,kBAAkB,IAA4B;AAC7D,SAAO,UAAU,UAAU,EAAE,SAAS,OAAO,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": "AAGA,SAAS,WAAW,WAAW,cAAc;AAMtC,SAAS,eAAe,IAAgB,YAAkD;AAChG,SAAO,QAAQ,OAAO,UAAU,EAAE,GAAG;AAAA,IACpC,UAAU,UAAU,WAAW,CAAC,CAAC;AAAA,IACjC,UAAU,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,OAAO,OAAO,EAAE,QAAQ;AAChC;AAGO,SAAS,YAAY,IAA4B;AACvD,SAAO,UAAU,UAAU,EAAE,SAAS,OAAO,UAAU,EAAE,CAAC,EAAE,QAAQ;AACrE;AAGO,SAAS,kBAAkB,IAA4B;AAC7D,SAAO,UAAU,UAAU,EAAE,SAAS,OAAO,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
+ }
@@ -1,51 +1,79 @@
1
+ import { fromHex } from "@mysten/bcs";
2
+ import { isValidSuiObjectId } from "@mysten/sui/utils";
1
3
  import { split as externalSplit } from "shamir-secret-sharing";
4
+ import { EncryptedObject } from "./bcs.js";
5
+ import { UserError } from "./error.js";
2
6
  import { BonehFranklinBLS12381Services, DST } from "./ibe.js";
3
- import { KeyServerType } from "./key-server.js";
4
- import { EncryptedObject } from "./types.js";
7
+ import { deriveKey, KeyPurpose } from "./kdf.js";
5
8
  import { createFullId } from "./utils.js";
6
9
  const MAX_U8 = 255;
7
10
  async function encrypt({
8
11
  keyServers,
12
+ kemType,
9
13
  threshold,
10
14
  packageId,
11
15
  id,
12
16
  encryptionInput
13
17
  }) {
14
- if (keyServers.length < threshold || threshold === 0 || keyServers.length > MAX_U8 || threshold > MAX_U8 || packageId.length !== 32) {
15
- throw new Error("Invalid input");
18
+ if (keyServers.length < threshold || threshold === 0 || keyServers.length > MAX_U8 || threshold > MAX_U8 || !isValidSuiObjectId(packageId)) {
19
+ throw new UserError(
20
+ `Invalid key servers or threshold ${threshold} for ${keyServers.length} key servers for package ${packageId}`
21
+ );
16
22
  }
17
- if (keyServers.some((server) => server.keyType !== KeyServerType.BonehFranklinBLS12381)) {
18
- throw new Error("Key type is not supported");
19
- }
20
- const ibeServers = new BonehFranklinBLS12381Services(keyServers);
21
23
  const key = await encryptionInput.generateKey();
22
- const ciphertext = await encryptionInput.encrypt(key);
23
- const shares = await split(key, ibeServers.size(), threshold);
24
+ const demKey = deriveKey(KeyPurpose.DEM, key);
25
+ const ciphertext = await encryptionInput.encrypt(demKey);
26
+ const shares = await split(key, keyServers.length, threshold);
24
27
  const fullId = createFullId(DST, packageId, id);
25
- const encrypted_shares = ibeServers.encryptBatched(
26
- fullId,
28
+ const encryptedShares = encryptBatched(
29
+ keyServers,
30
+ kemType,
31
+ fromHex(fullId),
27
32
  shares.map(({ share, index }) => ({
28
33
  msg: share,
29
- info: new Uint8Array([index])
30
- }))
34
+ index
35
+ })),
36
+ deriveKey(KeyPurpose.EncryptedRandomness, key)
31
37
  );
32
- const services = ibeServers.getObjectIds().map((id2, i) => [id2, shares[i].index]);
38
+ const services = keyServers.map((server, i) => [
39
+ server.objectId,
40
+ shares[i].index
41
+ ]);
33
42
  return {
34
43
  encryptedObject: EncryptedObject.serialize({
35
44
  version: 0,
36
- package_id: packageId,
45
+ packageId,
37
46
  id,
38
47
  services,
39
48
  threshold,
40
- encrypted_shares,
49
+ encryptedShares,
41
50
  ciphertext
42
51
  }).toBytes(),
43
- key
52
+ key: demKey
44
53
  };
45
54
  }
55
+ var KemType = /* @__PURE__ */ ((KemType2) => {
56
+ KemType2[KemType2["BonehFranklinBLS12381DemCCA"] = 0] = "BonehFranklinBLS12381DemCCA";
57
+ return KemType2;
58
+ })(KemType || {});
59
+ var DemType = /* @__PURE__ */ ((DemType2) => {
60
+ DemType2[DemType2["AesGcm256"] = 0] = "AesGcm256";
61
+ DemType2[DemType2["Hmac256Ctr"] = 1] = "Hmac256Ctr";
62
+ return DemType2;
63
+ })(DemType || {});
64
+ function encryptBatched(keyServers, kemType, id, shares, randomnessKey) {
65
+ switch (kemType) {
66
+ case 0 /* BonehFranklinBLS12381DemCCA */:
67
+ return new BonehFranklinBLS12381Services(keyServers).encryptBatched(
68
+ id,
69
+ shares,
70
+ randomnessKey
71
+ );
72
+ }
73
+ }
46
74
  async function split(secret, n, threshold) {
47
75
  if (n === 0 || threshold === 0 || threshold > n) {
48
- throw new Error("Invalid input");
76
+ throw new Error("Invalid threshold or number of shares");
49
77
  } else if (threshold === 1) {
50
78
  const result = [];
51
79
  for (let i = 0; i < n; i++) {
@@ -62,6 +90,8 @@ async function split(secret, n, threshold) {
62
90
  );
63
91
  }
64
92
  export {
93
+ DemType,
94
+ KemType,
65
95
  MAX_U8,
66
96
  encrypt
67
97
  };
@@ -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": "AAGA,SAAS,SAAS,qBAAqB;AAGvC,SAAS,+BAA+B,WAAW;AAEnD,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;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,SAA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A,SAAO,cAAc,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": ["id"]
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": "AAGA,SAAS,eAAe;AACxB,SAAS,0BAA0B;AACnC,SAAS,SAAS,qBAAqB;AAGvC,SAAS,uBAAuB;AAEhC,SAAS,iBAAiB;AAC1B,SAAS,+BAA+B,WAAW;AACnD,SAAS,WAAW,kBAAkB;AAEtC,SAAS,oBAAoB;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,CAAC,mBAAmB,SAAS,GAC5B;AACD,UAAM,IAAI;AAAA,MACT,oCAAoC,SAAS,QAAQ,WAAW,MAAM,4BAA4B,SAAS;AAAA,IAC5G;AA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AG;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,SAAO,cAAc,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": ["KemType", "DemType"]
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;