@haneullabs/seal 0.1.0 → 1.1.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.
- package/CHANGELOG.md +118 -57
- package/dist/bcs.d.mts +39 -0
- package/dist/bcs.d.mts.map +1 -0
- package/dist/bcs.mjs +86 -0
- package/dist/bcs.mjs.map +1 -0
- package/dist/bls12381.d.mts +29 -0
- package/dist/bls12381.d.mts.map +1 -0
- package/dist/bls12381.mjs +135 -0
- package/dist/bls12381.mjs.map +1 -0
- package/dist/client.d.mts +105 -0
- package/dist/client.d.mts.map +1 -0
- package/dist/client.mjs +274 -0
- package/dist/client.mjs.map +1 -0
- package/dist/decrypt.mjs +53 -0
- package/dist/decrypt.mjs.map +1 -0
- package/dist/dem.d.mts +1 -0
- package/dist/dem.mjs +134 -0
- package/dist/dem.mjs.map +1 -0
- package/dist/elgamal.mjs +35 -0
- package/dist/elgamal.mjs.map +1 -0
- package/dist/encrypt.d.mts +14 -0
- package/dist/encrypt.d.mts.map +1 -0
- package/dist/encrypt.mjs +61 -0
- package/dist/encrypt.mjs.map +1 -0
- package/dist/error.d.mts +75 -0
- package/dist/error.d.mts.map +1 -0
- package/dist/error.mjs +150 -0
- package/dist/error.mjs.map +1 -0
- package/dist/ibe.mjs +176 -0
- package/dist/ibe.mjs.map +1 -0
- package/dist/index.d.mts +7 -0
- package/dist/index.mjs +7 -0
- package/dist/kdf.mjs +81 -0
- package/dist/kdf.mjs.map +1 -0
- package/dist/key-server.d.mts +22 -0
- package/dist/key-server.d.mts.map +1 -0
- package/dist/key-server.mjs +195 -0
- package/dist/key-server.mjs.map +1 -0
- package/dist/session-key.d.mts +82 -0
- package/dist/session-key.d.mts.map +1 -0
- package/dist/session-key.mjs +171 -0
- package/dist/session-key.mjs.map +1 -0
- package/dist/shamir.mjs +730 -0
- package/dist/shamir.mjs.map +1 -0
- package/dist/types.d.mts +79 -0
- package/dist/types.d.mts.map +1 -0
- package/dist/utils.mjs +89 -0
- package/dist/utils.mjs.map +1 -0
- package/dist/version.mjs +6 -0
- package/dist/version.mjs.map +1 -0
- package/docs/index.md +84 -0
- package/docs/llms-index.md +6 -0
- package/package.json +29 -25
- package/dist/cjs/bcs.d.ts +0 -71
- package/dist/cjs/bcs.js +0 -74
- package/dist/cjs/bcs.js.map +0 -7
- package/dist/cjs/bls12381.d.ts +0 -44
- package/dist/cjs/bls12381.js +0 -151
- package/dist/cjs/bls12381.js.map +0 -7
- package/dist/cjs/client.d.ts +0 -84
- package/dist/cjs/client.js +0 -414
- package/dist/cjs/client.js.map +0 -7
- package/dist/cjs/decrypt.d.ts +0 -22
- package/dist/cjs/decrypt.js +0 -109
- package/dist/cjs/decrypt.js.map +0 -7
- package/dist/cjs/dem.d.ts +0 -38
- package/dist/cjs/dem.js +0 -185
- package/dist/cjs/dem.js.map +0 -7
- package/dist/cjs/elgamal.d.ts +0 -13
- package/dist/cjs/elgamal.js +0 -46
- package/dist/cjs/elgamal.js.map +0 -7
- package/dist/cjs/encrypt.d.ts +0 -32
- package/dist/cjs/encrypt.js +0 -104
- package/dist/cjs/encrypt.js.map +0 -7
- package/dist/cjs/error.d.ts +0 -86
- package/dist/cjs/error.js +0 -239
- package/dist/cjs/error.js.map +0 -7
- package/dist/cjs/ibe.d.ts +0 -98
- package/dist/cjs/ibe.js +0 -167
- package/dist/cjs/ibe.js.map +0 -7
- package/dist/cjs/index.d.ts +0 -6
- package/dist/cjs/index.js +0 -33
- package/dist/cjs/index.js.map +0 -7
- package/dist/cjs/kdf.d.ts +0 -30
- package/dist/cjs/kdf.js +0 -97
- package/dist/cjs/kdf.js.map +0 -7
- package/dist/cjs/key-server.d.ts +0 -98
- package/dist/cjs/key-server.js +0 -171
- package/dist/cjs/key-server.js.map +0 -7
- package/dist/cjs/package.json +0 -5
- package/dist/cjs/session-key.d.ts +0 -74
- package/dist/cjs/session-key.js +0 -245
- package/dist/cjs/session-key.js.map +0 -7
- package/dist/cjs/shamir.d.ts +0 -91
- package/dist/cjs/shamir.js +0 -770
- package/dist/cjs/shamir.js.map +0 -7
- package/dist/cjs/types.d.ts +0 -83
- package/dist/cjs/types.js +0 -17
- package/dist/cjs/types.js.map +0 -7
- package/dist/cjs/utils.d.ts +0 -47
- package/dist/cjs/utils.js +0 -106
- package/dist/cjs/utils.js.map +0 -7
- package/dist/cjs/version.d.ts +0 -1
- package/dist/cjs/version.js +0 -25
- package/dist/cjs/version.js.map +0 -7
- package/dist/esm/bcs.d.ts +0 -71
- package/dist/esm/bcs.js +0 -54
- package/dist/esm/bcs.js.map +0 -7
- package/dist/esm/bls12381.d.ts +0 -44
- package/dist/esm/bls12381.js +0 -131
- package/dist/esm/bls12381.js.map +0 -7
- package/dist/esm/client.d.ts +0 -84
- package/dist/esm/client.js +0 -407
- package/dist/esm/client.js.map +0 -7
- package/dist/esm/decrypt.d.ts +0 -22
- package/dist/esm/decrypt.js +0 -94
- package/dist/esm/decrypt.js.map +0 -7
- package/dist/esm/dem.d.ts +0 -38
- package/dist/esm/dem.js +0 -165
- package/dist/esm/dem.js.map +0 -7
- package/dist/esm/elgamal.d.ts +0 -13
- package/dist/esm/elgamal.js +0 -26
- package/dist/esm/elgamal.js.map +0 -7
- package/dist/esm/encrypt.d.ts +0 -32
- package/dist/esm/encrypt.js +0 -84
- package/dist/esm/encrypt.js.map +0 -7
- package/dist/esm/error.d.ts +0 -86
- package/dist/esm/error.js +0 -219
- package/dist/esm/error.js.map +0 -7
- package/dist/esm/ibe.d.ts +0 -98
- package/dist/esm/ibe.js +0 -147
- package/dist/esm/ibe.js.map +0 -7
- package/dist/esm/index.d.ts +0 -6
- package/dist/esm/index.js +0 -12
- package/dist/esm/index.js.map +0 -7
- package/dist/esm/kdf.d.ts +0 -30
- package/dist/esm/kdf.js +0 -83
- package/dist/esm/kdf.js.map +0 -7
- package/dist/esm/key-server.d.ts +0 -98
- package/dist/esm/key-server.js +0 -151
- package/dist/esm/key-server.js.map +0 -7
- package/dist/esm/package.json +0 -5
- package/dist/esm/session-key.d.ts +0 -74
- package/dist/esm/session-key.js +0 -230
- package/dist/esm/session-key.js.map +0 -7
- package/dist/esm/shamir.d.ts +0 -91
- package/dist/esm/shamir.js +0 -750
- package/dist/esm/shamir.js.map +0 -7
- package/dist/esm/types.d.ts +0 -83
- package/dist/esm/types.js +0 -1
- package/dist/esm/types.js.map +0 -7
- package/dist/esm/utils.d.ts +0 -47
- package/dist/esm/utils.js +0 -86
- package/dist/esm/utils.js.map +0 -7
- package/dist/esm/version.d.ts +0 -1
- package/dist/esm/version.js +0 -5
- package/dist/esm/version.js.map +0 -7
- package/dist/tsconfig.esm.tsbuildinfo +0 -1
- package/dist/tsconfig.tsbuildinfo +0 -1
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { bls12_381 } from "@noble/curves/bls12-381.js";
|
|
2
|
+
import { bytesToNumberBE, bytesToNumberLE, numberToBytesBE } from "@noble/curves/utils.js";
|
|
3
|
+
|
|
4
|
+
//#region src/bls12381.ts
|
|
5
|
+
var G1Element = class G1Element {
|
|
6
|
+
static {
|
|
7
|
+
this.SIZE = 48;
|
|
8
|
+
}
|
|
9
|
+
constructor(point) {
|
|
10
|
+
this.point = point;
|
|
11
|
+
}
|
|
12
|
+
static generator() {
|
|
13
|
+
return new G1Element(bls12_381.G1.Point.BASE);
|
|
14
|
+
}
|
|
15
|
+
static fromBytes(bytes) {
|
|
16
|
+
try {
|
|
17
|
+
return new G1Element(bls12_381.G1.Point.fromBytes(bytes));
|
|
18
|
+
} catch {
|
|
19
|
+
throw new Error("Invalid G1 point");
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
toBytes() {
|
|
23
|
+
return this.point.toBytes();
|
|
24
|
+
}
|
|
25
|
+
multiply(scalar) {
|
|
26
|
+
return new G1Element(this.point.multiply(scalar.scalar));
|
|
27
|
+
}
|
|
28
|
+
add(other) {
|
|
29
|
+
return new G1Element(this.point.add(other.point));
|
|
30
|
+
}
|
|
31
|
+
subtract(other) {
|
|
32
|
+
return new G1Element(this.point.subtract(other.point));
|
|
33
|
+
}
|
|
34
|
+
static hashToCurve(data) {
|
|
35
|
+
return new G1Element(bls12_381.G1.Point.fromAffine(bls12_381.G1.hashToCurve(data).toAffine()));
|
|
36
|
+
}
|
|
37
|
+
pairing(other) {
|
|
38
|
+
return new GTElement(bls12_381.pairing(this.point, other.point));
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
var G2Element = class G2Element {
|
|
42
|
+
static {
|
|
43
|
+
this.SIZE = 96;
|
|
44
|
+
}
|
|
45
|
+
constructor(point) {
|
|
46
|
+
this.point = point;
|
|
47
|
+
}
|
|
48
|
+
static generator() {
|
|
49
|
+
return new G2Element(bls12_381.G2.Point.BASE);
|
|
50
|
+
}
|
|
51
|
+
static fromBytes(bytes) {
|
|
52
|
+
try {
|
|
53
|
+
return new G2Element(bls12_381.G2.Point.fromBytes(bytes));
|
|
54
|
+
} catch {
|
|
55
|
+
throw new Error("Invalid G2 point");
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
toBytes() {
|
|
59
|
+
return this.point.toBytes();
|
|
60
|
+
}
|
|
61
|
+
multiply(scalar) {
|
|
62
|
+
return new G2Element(this.point.multiply(scalar.scalar));
|
|
63
|
+
}
|
|
64
|
+
add(other) {
|
|
65
|
+
return new G2Element(this.point.add(other.point));
|
|
66
|
+
}
|
|
67
|
+
static hashToCurve(data) {
|
|
68
|
+
return new G2Element(bls12_381.G2.Point.fromAffine(bls12_381.G2.hashToCurve(data).toAffine()));
|
|
69
|
+
}
|
|
70
|
+
equals(other) {
|
|
71
|
+
return this.point.equals(other.point);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
var GTElement = class GTElement {
|
|
75
|
+
static {
|
|
76
|
+
this.SIZE = 576;
|
|
77
|
+
}
|
|
78
|
+
constructor(element) {
|
|
79
|
+
this.element = element;
|
|
80
|
+
}
|
|
81
|
+
toBytes() {
|
|
82
|
+
const P = [
|
|
83
|
+
0,
|
|
84
|
+
3,
|
|
85
|
+
1,
|
|
86
|
+
4,
|
|
87
|
+
2,
|
|
88
|
+
5
|
|
89
|
+
];
|
|
90
|
+
const PAIR_SIZE = GTElement.SIZE / P.length;
|
|
91
|
+
const bytes = bls12_381.fields.Fp12.toBytes(this.element);
|
|
92
|
+
const result = new Uint8Array(GTElement.SIZE);
|
|
93
|
+
for (let i = 0; i < P.length; i++) {
|
|
94
|
+
const sourceStart = P[i] * PAIR_SIZE;
|
|
95
|
+
const sourceEnd = sourceStart + PAIR_SIZE;
|
|
96
|
+
const targetStart = i * PAIR_SIZE;
|
|
97
|
+
result.set(bytes.subarray(sourceStart, sourceEnd), targetStart);
|
|
98
|
+
}
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
equals(other) {
|
|
102
|
+
return bls12_381.fields.Fp12.eql(this.element, other.element);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
var Scalar = class Scalar {
|
|
106
|
+
static {
|
|
107
|
+
this.SIZE = 32;
|
|
108
|
+
}
|
|
109
|
+
constructor(scalar) {
|
|
110
|
+
this.scalar = scalar;
|
|
111
|
+
}
|
|
112
|
+
static fromBigint(scalar) {
|
|
113
|
+
if (scalar < 0n || scalar >= bls12_381.fields.Fr.ORDER) throw new Error("Scalar out of range");
|
|
114
|
+
return new Scalar(scalar);
|
|
115
|
+
}
|
|
116
|
+
static random() {
|
|
117
|
+
const randomSecretKey = bls12_381.utils.randomSecretKey();
|
|
118
|
+
return Scalar.fromBytes(randomSecretKey);
|
|
119
|
+
}
|
|
120
|
+
toBytes() {
|
|
121
|
+
return numberToBytesBE(this.scalar, Scalar.SIZE);
|
|
122
|
+
}
|
|
123
|
+
static fromBytes(bytes) {
|
|
124
|
+
if (bytes.length !== Scalar.SIZE) throw new Error("Invalid scalar length");
|
|
125
|
+
return this.fromBigint(bytesToNumberBE(bytes));
|
|
126
|
+
}
|
|
127
|
+
static fromBytesLE(bytes) {
|
|
128
|
+
if (bytes.length !== Scalar.SIZE) throw new Error("Invalid scalar length");
|
|
129
|
+
return this.fromBigint(bytesToNumberLE(bytes));
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
//#endregion
|
|
134
|
+
export { G1Element, G2Element, Scalar };
|
|
135
|
+
//# sourceMappingURL=bls12381.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bls12381.mjs","names":[],"sources":["../src/bls12381.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Fp2, Fp12 } from '@noble/curves/abstract/tower.js';\nimport type { WeierstrassPoint } from '@noble/curves/abstract/weierstrass.js';\nimport { bls12_381 } from '@noble/curves/bls12-381.js';\nimport { bytesToNumberBE, bytesToNumberLE, numberToBytesBE } from '@noble/curves/utils.js';\n\nexport class G1Element {\n\tpoint: WeierstrassPoint<bigint>;\n\n\tpublic static readonly SIZE = 48;\n\n\tconstructor(point: WeierstrassPoint<bigint>) {\n\t\tthis.point = point;\n\t}\n\n\tstatic generator(): G1Element {\n\t\treturn new G1Element(bls12_381.G1.Point.BASE);\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): G1Element {\n\t\ttry {\n\t\t\treturn new G1Element(bls12_381.G1.Point.fromBytes(bytes));\n\t\t} catch {\n\t\t\tthrow new Error('Invalid G1 point');\n\t\t}\n\t}\n\n\ttoBytes(): Uint8Array<ArrayBuffer> {\n\t\treturn this.point.toBytes() as Uint8Array<ArrayBuffer>;\n\t}\n\n\tmultiply(scalar: Scalar): G1Element {\n\t\treturn new G1Element(this.point.multiply(scalar.scalar));\n\t}\n\n\tadd(other: G1Element): G1Element {\n\t\treturn new G1Element(this.point.add(other.point));\n\t}\n\n\tsubtract(other: G1Element): G1Element {\n\t\treturn new G1Element(this.point.subtract(other.point));\n\t}\n\n\tstatic hashToCurve(data: Uint8Array): G1Element {\n\t\treturn new G1Element(bls12_381.G1.Point.fromAffine(bls12_381.G1.hashToCurve(data).toAffine()));\n\t}\n\n\tpairing(other: G2Element): GTElement {\n\t\treturn new GTElement(bls12_381.pairing(this.point, other.point));\n\t}\n}\n\nexport class G2Element {\n\tpoint: WeierstrassPoint<Fp2>;\n\n\tpublic static readonly SIZE = 96;\n\n\tconstructor(point: WeierstrassPoint<Fp2>) {\n\t\tthis.point = point;\n\t}\n\n\tstatic generator(): G2Element {\n\t\treturn new G2Element(bls12_381.G2.Point.BASE);\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): G2Element {\n\t\ttry {\n\t\t\treturn new G2Element(bls12_381.G2.Point.fromBytes(bytes));\n\t\t} catch {\n\t\t\tthrow new Error('Invalid G2 point');\n\t\t}\n\t}\n\n\ttoBytes(): Uint8Array<ArrayBuffer> {\n\t\treturn this.point.toBytes() as Uint8Array<ArrayBuffer>;\n\t}\n\n\tmultiply(scalar: Scalar): G2Element {\n\t\treturn new G2Element(this.point.multiply(scalar.scalar));\n\t}\n\n\tadd(other: G2Element): G2Element {\n\t\treturn new G2Element(this.point.add(other.point));\n\t}\n\n\tstatic hashToCurve(data: Uint8Array): G2Element {\n\t\treturn new G2Element(bls12_381.G2.Point.fromAffine(bls12_381.G2.hashToCurve(data).toAffine()));\n\t}\n\n\tequals(other: G2Element): boolean {\n\t\treturn this.point.equals(other.point);\n\t}\n}\n\nexport class GTElement {\n\telement: Fp12;\n\n\tpublic static readonly SIZE = 576;\n\n\tconstructor(element: Fp12) {\n\t\tthis.element = element;\n\t}\n\n\ttoBytes(): Uint8Array<ArrayBuffer> {\n\t\t// This permutation reorders the 6 pairs of coefficients of the GT element for compatability with the Rust and Move implementations.\n\t\t//\n\t\t// The permutation P may be computed as:\n\t\t// for i in 0..3 {\n\t\t// for j in 0..2 {\n\t\t// P[2 * i + j] = i + 3 * j;\n\t\t// }\n\t\t// }\n\t\tconst P = [0, 3, 1, 4, 2, 5];\n\t\tconst PAIR_SIZE = GTElement.SIZE / P.length;\n\n\t\tconst bytes = bls12_381.fields.Fp12.toBytes(this.element);\n\t\tconst result = new Uint8Array(GTElement.SIZE);\n\n\t\tfor (let i = 0; i < P.length; i++) {\n\t\t\tconst sourceStart = P[i] * PAIR_SIZE;\n\t\t\tconst sourceEnd = sourceStart + PAIR_SIZE;\n\t\t\tconst targetStart = i * PAIR_SIZE;\n\t\t\tresult.set(bytes.subarray(sourceStart, sourceEnd), targetStart);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tequals(other: GTElement): boolean {\n\t\treturn bls12_381.fields.Fp12.eql(this.element, other.element);\n\t}\n}\n\nexport class Scalar {\n\tscalar: bigint;\n\n\tpublic static readonly SIZE = 32;\n\n\tconstructor(scalar: bigint) {\n\t\tthis.scalar = scalar;\n\t}\n\n\tstatic fromBigint(scalar: bigint): Scalar {\n\t\tif (scalar < 0n || scalar >= bls12_381.fields.Fr.ORDER) {\n\t\t\tthrow new Error('Scalar out of range');\n\t\t}\n\t\treturn new Scalar(scalar);\n\t}\n\n\tstatic random(): Scalar {\n\t\tconst randomSecretKey = bls12_381.utils.randomSecretKey();\n\t\treturn Scalar.fromBytes(randomSecretKey)!;\n\t}\n\n\ttoBytes(): Uint8Array {\n\t\treturn numberToBytesBE(this.scalar, Scalar.SIZE);\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): Scalar {\n\t\tif (bytes.length !== Scalar.SIZE) {\n\t\t\tthrow new Error('Invalid scalar length');\n\t\t}\n\t\treturn this.fromBigint(bytesToNumberBE(bytes));\n\t}\n\n\tstatic fromBytesLE(bytes: Uint8Array): Scalar {\n\t\tif (bytes.length !== Scalar.SIZE) {\n\t\t\tthrow new Error('Invalid scalar length');\n\t\t}\n\t\treturn this.fromBigint(bytesToNumberLE(bytes));\n\t}\n}\n"],"mappings":";;;;AAQA,IAAa,YAAb,MAAa,UAAU;;cAGQ;;CAE9B,YAAY,OAAiC;AAC5C,OAAK,QAAQ;;CAGd,OAAO,YAAuB;AAC7B,SAAO,IAAI,UAAU,UAAU,GAAG,MAAM,KAAK;;CAG9C,OA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M,WAAW,OAAO,KAC3B,OAAM,IAAI,MAAM,wBAAwB;AAEzC,SAAO,KAAK,WAAW,gBAAgB,MAAM,CAAC"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { G2Element } from "./bls12381.mjs";
|
|
2
|
+
import { DecryptOptions, EncryptOptions, FetchKeysOptions, GetDerivedKeysOptions, SealClientOptions } from "./types.mjs";
|
|
3
|
+
import { DerivedKey, KeyServer } from "./key-server.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/client.d.ts
|
|
6
|
+
declare class SealClient {
|
|
7
|
+
#private;
|
|
8
|
+
constructor(options: SealClientOptions);
|
|
9
|
+
/**
|
|
10
|
+
* Return an encrypted message under the identity.
|
|
11
|
+
*
|
|
12
|
+
* @param kemType - The type of KEM to use.
|
|
13
|
+
* @param demType - The type of DEM to use.
|
|
14
|
+
* @param threshold - The threshold for the TSS encryption.
|
|
15
|
+
* @param packageId - the packageId namespace.
|
|
16
|
+
* @param id - the identity to use.
|
|
17
|
+
* @param data - the data to encrypt.
|
|
18
|
+
* @param aad - optional additional authenticated data.
|
|
19
|
+
* @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.
|
|
20
|
+
* Since the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.
|
|
21
|
+
*/
|
|
22
|
+
encrypt({
|
|
23
|
+
kemType,
|
|
24
|
+
demType,
|
|
25
|
+
threshold,
|
|
26
|
+
packageId,
|
|
27
|
+
id,
|
|
28
|
+
data,
|
|
29
|
+
aad
|
|
30
|
+
}: EncryptOptions): Promise<{
|
|
31
|
+
encryptedObject: Uint8Array<ArrayBuffer>;
|
|
32
|
+
key: Uint8Array<ArrayBuffer>;
|
|
33
|
+
}>;
|
|
34
|
+
/**
|
|
35
|
+
* Decrypt the given encrypted bytes using cached keys.
|
|
36
|
+
* Calls fetchKeys in case one or more of the required keys is not cached yet.
|
|
37
|
+
* The function throws an error if the client's key servers are not a subset of
|
|
38
|
+
* the encrypted object's key servers or if the threshold cannot be met.
|
|
39
|
+
*
|
|
40
|
+
* If checkShareConsistency is true, the decrypted shares are checked for consistency, meaning that
|
|
41
|
+
* any combination of at least threshold shares should either succesfully combine to the plaintext or fail.
|
|
42
|
+
* This is useful in case the encryptor is not trusted and the decryptor wants to ensure all decryptors
|
|
43
|
+
* receive the same output (e.g., for onchain encrypted voting).
|
|
44
|
+
*
|
|
45
|
+
* @param data - The encrypted bytes to decrypt.
|
|
46
|
+
* @param sessionKey - The session key to use.
|
|
47
|
+
* @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
|
|
48
|
+
* @param checkShareConsistency - If true, the shares are checked for consistency.
|
|
49
|
+
* @param checkLEEncoding - If true, the encryption is also checked using an LE encoded nonce.
|
|
50
|
+
* @returns - The decrypted plaintext corresponding to ciphertext.
|
|
51
|
+
*/
|
|
52
|
+
decrypt({
|
|
53
|
+
data,
|
|
54
|
+
sessionKey,
|
|
55
|
+
txBytes,
|
|
56
|
+
checkShareConsistency,
|
|
57
|
+
checkLEEncoding
|
|
58
|
+
}: DecryptOptions): Promise<Uint8Array<ArrayBufferLike>>;
|
|
59
|
+
getKeyServers(): Promise<Map<string, KeyServer>>;
|
|
60
|
+
/**
|
|
61
|
+
* Get the public keys for the given services.
|
|
62
|
+
* If all public keys are not in the cache, they are retrieved.
|
|
63
|
+
*
|
|
64
|
+
* @param services - The services to get the public keys for.
|
|
65
|
+
* @returns The public keys for the given services in the same order as the given services.
|
|
66
|
+
*/
|
|
67
|
+
getPublicKeys(services: string[]): Promise<G2Element[]>;
|
|
68
|
+
/**
|
|
69
|
+
* Fetch keys from the key servers and update the cache.
|
|
70
|
+
*
|
|
71
|
+
* It is recommended to call this function once for all ids of all encrypted objects if
|
|
72
|
+
* there are multiple, then call decrypt for each object. This avoids calling fetchKey
|
|
73
|
+
* individually for each decrypt.
|
|
74
|
+
*
|
|
75
|
+
* @param ids - The ids of the encrypted objects.
|
|
76
|
+
* @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
|
|
77
|
+
* @param sessionKey - The session key to use.
|
|
78
|
+
* @param threshold - The threshold for the TSS encryptions. The function returns when a threshold of key servers had returned keys for all ids.
|
|
79
|
+
*/
|
|
80
|
+
fetchKeys({
|
|
81
|
+
ids,
|
|
82
|
+
txBytes,
|
|
83
|
+
sessionKey,
|
|
84
|
+
threshold
|
|
85
|
+
}: FetchKeysOptions): Promise<void>;
|
|
86
|
+
/**
|
|
87
|
+
* Get derived keys from the given services.
|
|
88
|
+
*
|
|
89
|
+
* @param id - The id of the encrypted object.
|
|
90
|
+
* @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
|
|
91
|
+
* @param sessionKey - The session key to use.
|
|
92
|
+
* @param threshold - The threshold.
|
|
93
|
+
* @returns - Derived keys for the given services that are in the cache as a "service object ID" -> derived key map. If the call is succesful, exactly threshold keys will be returned.
|
|
94
|
+
*/
|
|
95
|
+
getDerivedKeys({
|
|
96
|
+
kemType,
|
|
97
|
+
id,
|
|
98
|
+
txBytes,
|
|
99
|
+
sessionKey,
|
|
100
|
+
threshold
|
|
101
|
+
}: GetDerivedKeysOptions): Promise<Map<string, DerivedKey>>;
|
|
102
|
+
}
|
|
103
|
+
//#endregion
|
|
104
|
+
export { SealClient };
|
|
105
|
+
//# sourceMappingURL=client.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.mts","names":[],"sources":["../src/client.ts"],"mappings":";;;;;cAmDa,UAAA;EAAA;cAWA,OAAA,EAAS,iBAAA;EAyCpB;;;;;;;;;;;;;EAFK,OAAA,CAAA;IACL,OAAA;IACA,OAAA;IACA,SAAA;IACA,SAAA;IACA,EAAA;IACA,IAAA;IACA;EAAA,GACE,cAAA,GAAc,OAAA;;;;EAyDd;;;;;;;;;;;;;;;;;;EANG,OAAA,CAAA;IACL,IAAA;IACA,UAAA;IACA,OAAA;IACA,qBAAA;IACA;EAAA,GACE,cAAA,GAAc,OAAA,CAAA,UAAA,CAAA,eAAA;EAqDX,aAAA,CAAA,GAAiB,OAAA,CAAQ,GAAA,SAAY,SAAA;EAuNxC;;;;;;;EAtMG,aAAA,CAAc,QAAA,aAAqB,OAAA,CAAQ,SAAA;EA9K5B;;;;;;;;;;;;EAoQf,SAAA,CAAA;IAAY,GAAA;IAAK,OAAA;IAAS,UAAA;IAAY;EAAA,GAAa,gBAAA,GAAgB,OAAA;EAvNxE;;;;;;;;;EAiUK,cAAA,CAAA;IACL,OAAA;IACA,EAAA;IACA,OAAA;IACA,UAAA;IACA;EAAA,GACE,qBAAA,GAAwB,OAAA,CAAQ,GAAA,SAAY,UAAA;AAAA"}
|
package/dist/client.mjs
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import { EncryptedObject } from "./bcs.mjs";
|
|
2
|
+
import { G1Element, G2Element } from "./bls12381.mjs";
|
|
3
|
+
import { InconsistentKeyServersError, InvalidClientOptionsError, InvalidKeyServerError, InvalidPackageError, InvalidThresholdError, TooManyFailedFetchKeyRequestsError, toMajorityError } from "./error.mjs";
|
|
4
|
+
import { count, createFullId } from "./utils.mjs";
|
|
5
|
+
import { AesGcm256, Hmac256Ctr } from "./dem.mjs";
|
|
6
|
+
import { BonehFranklinBLS12381Services } from "./ibe.mjs";
|
|
7
|
+
import { decrypt } from "./decrypt.mjs";
|
|
8
|
+
import { DemType, KemType, encrypt } from "./encrypt.mjs";
|
|
9
|
+
import { BonehFranklinBLS12381DerivedKey, fetchKeysForAllIds, retrieveKeyServers, verifyKeyServer } from "./key-server.mjs";
|
|
10
|
+
|
|
11
|
+
//#region src/client.ts
|
|
12
|
+
var SealClient = class {
|
|
13
|
+
#haneulClient;
|
|
14
|
+
#configs;
|
|
15
|
+
#keyServers = null;
|
|
16
|
+
#verifyKeyServers;
|
|
17
|
+
#cachedKeys = /* @__PURE__ */ new Map();
|
|
18
|
+
#cachedPublicKeys = /* @__PURE__ */ new Map();
|
|
19
|
+
#timeout;
|
|
20
|
+
#totalWeight;
|
|
21
|
+
constructor(options) {
|
|
22
|
+
this.#haneulClient = options.haneulClient;
|
|
23
|
+
if (new Set(options.serverConfigs.map((s) => s.objectId)).size !== options.serverConfigs.length) throw new InvalidClientOptionsError("Duplicate object IDs");
|
|
24
|
+
if (options.serverConfigs.some((s) => s.apiKeyName && !s.apiKey || !s.apiKeyName && s.apiKey)) throw new InvalidClientOptionsError("Both apiKeyName and apiKey must be provided or not provided for all key servers");
|
|
25
|
+
this.#configs = new Map(options.serverConfigs.map((server) => [server.objectId, server]));
|
|
26
|
+
this.#totalWeight = options.serverConfigs.map((server) => server.weight).reduce((sum, term) => sum + term, 0);
|
|
27
|
+
this.#verifyKeyServers = options.verifyKeyServers ?? true;
|
|
28
|
+
this.#timeout = options.timeout ?? 1e4;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Return an encrypted message under the identity.
|
|
32
|
+
*
|
|
33
|
+
* @param kemType - The type of KEM to use.
|
|
34
|
+
* @param demType - The type of DEM to use.
|
|
35
|
+
* @param threshold - The threshold for the TSS encryption.
|
|
36
|
+
* @param packageId - the packageId namespace.
|
|
37
|
+
* @param id - the identity to use.
|
|
38
|
+
* @param data - the data to encrypt.
|
|
39
|
+
* @param aad - optional additional authenticated data.
|
|
40
|
+
* @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.
|
|
41
|
+
* Since the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.
|
|
42
|
+
*/
|
|
43
|
+
async encrypt({ kemType = KemType.BonehFranklinBLS12381DemCCA, demType = DemType.AesGcm256, threshold, packageId, id, data, aad = new Uint8Array() }) {
|
|
44
|
+
const packageObj = await this.#haneulClient.core.getObject({ objectId: packageId });
|
|
45
|
+
if (String(packageObj.object.version) !== "1") throw new InvalidPackageError(`Package ${packageId} is not the first version`);
|
|
46
|
+
return encrypt({
|
|
47
|
+
keyServers: await this.#getWeightedKeyServers(),
|
|
48
|
+
kemType,
|
|
49
|
+
threshold,
|
|
50
|
+
packageId,
|
|
51
|
+
id,
|
|
52
|
+
encryptionInput: this.#createEncryptionInput(demType, data, aad)
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
#createEncryptionInput(type, data, aad) {
|
|
56
|
+
switch (type) {
|
|
57
|
+
case DemType.AesGcm256: return new AesGcm256(data, aad);
|
|
58
|
+
case DemType.Hmac256Ctr: return new Hmac256Ctr(data, aad);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Decrypt the given encrypted bytes using cached keys.
|
|
63
|
+
* Calls fetchKeys in case one or more of the required keys is not cached yet.
|
|
64
|
+
* The function throws an error if the client's key servers are not a subset of
|
|
65
|
+
* the encrypted object's key servers or if the threshold cannot be met.
|
|
66
|
+
*
|
|
67
|
+
* If checkShareConsistency is true, the decrypted shares are checked for consistency, meaning that
|
|
68
|
+
* any combination of at least threshold shares should either succesfully combine to the plaintext or fail.
|
|
69
|
+
* This is useful in case the encryptor is not trusted and the decryptor wants to ensure all decryptors
|
|
70
|
+
* receive the same output (e.g., for onchain encrypted voting).
|
|
71
|
+
*
|
|
72
|
+
* @param data - The encrypted bytes to decrypt.
|
|
73
|
+
* @param sessionKey - The session key to use.
|
|
74
|
+
* @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
|
|
75
|
+
* @param checkShareConsistency - If true, the shares are checked for consistency.
|
|
76
|
+
* @param checkLEEncoding - If true, the encryption is also checked using an LE encoded nonce.
|
|
77
|
+
* @returns - The decrypted plaintext corresponding to ciphertext.
|
|
78
|
+
*/
|
|
79
|
+
async decrypt({ data, sessionKey, txBytes, checkShareConsistency, checkLEEncoding }) {
|
|
80
|
+
const encryptedObject = EncryptedObject.parse(data);
|
|
81
|
+
this.#validateEncryptionServices(encryptedObject.services.map((s) => s[0]), encryptedObject.threshold);
|
|
82
|
+
await this.fetchKeys({
|
|
83
|
+
ids: [encryptedObject.id],
|
|
84
|
+
txBytes,
|
|
85
|
+
sessionKey,
|
|
86
|
+
threshold: encryptedObject.threshold
|
|
87
|
+
});
|
|
88
|
+
if (checkShareConsistency) {
|
|
89
|
+
const publicKeys = await this.getPublicKeys(encryptedObject.services.map(([objectId, _]) => objectId));
|
|
90
|
+
return decrypt({
|
|
91
|
+
encryptedObject,
|
|
92
|
+
keys: this.#cachedKeys,
|
|
93
|
+
publicKeys,
|
|
94
|
+
checkLEEncoding: false
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return decrypt({
|
|
98
|
+
encryptedObject,
|
|
99
|
+
keys: this.#cachedKeys,
|
|
100
|
+
checkLEEncoding
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
#weight(objectId) {
|
|
104
|
+
return this.#configs.get(objectId)?.weight ?? 0;
|
|
105
|
+
}
|
|
106
|
+
#validateEncryptionServices(services, threshold) {
|
|
107
|
+
if (services.some((objectId) => {
|
|
108
|
+
const countInClient = this.#weight(objectId);
|
|
109
|
+
return countInClient > 0 && countInClient !== count(services, objectId);
|
|
110
|
+
})) throw new InconsistentKeyServersError(`Client's key servers must be a subset of the encrypted object's key servers`);
|
|
111
|
+
if (threshold > this.#totalWeight) throw new InvalidThresholdError(`Invalid threshold ${threshold} for ${this.#totalWeight} servers`);
|
|
112
|
+
}
|
|
113
|
+
async getKeyServers() {
|
|
114
|
+
if (!this.#keyServers) this.#keyServers = this.#loadKeyServers().catch((error) => {
|
|
115
|
+
this.#keyServers = null;
|
|
116
|
+
throw error;
|
|
117
|
+
});
|
|
118
|
+
return this.#keyServers;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Get the public keys for the given services.
|
|
122
|
+
* If all public keys are not in the cache, they are retrieved.
|
|
123
|
+
*
|
|
124
|
+
* @param services - The services to get the public keys for.
|
|
125
|
+
* @returns The public keys for the given services in the same order as the given services.
|
|
126
|
+
*/
|
|
127
|
+
async getPublicKeys(services) {
|
|
128
|
+
const keyServers = await this.getKeyServers();
|
|
129
|
+
const missingKeyServers = services.filter((objectId) => !keyServers.has(objectId) && !this.#cachedPublicKeys.has(objectId));
|
|
130
|
+
if (missingKeyServers.length > 0) (await retrieveKeyServers({
|
|
131
|
+
objectIds: missingKeyServers,
|
|
132
|
+
client: this.#haneulClient,
|
|
133
|
+
configs: this.#configs
|
|
134
|
+
})).forEach((keyServer) => this.#cachedPublicKeys.set(keyServer.objectId, G2Element.fromBytes(keyServer.pk)));
|
|
135
|
+
return services.map((objectId) => {
|
|
136
|
+
const keyServer = keyServers.get(objectId);
|
|
137
|
+
if (keyServer) return G2Element.fromBytes(keyServer.pk);
|
|
138
|
+
return this.#cachedPublicKeys.get(objectId);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Returns a list of key servers with multiplicity according to their weights.
|
|
143
|
+
* The list is used for encryption.
|
|
144
|
+
*/
|
|
145
|
+
async #getWeightedKeyServers() {
|
|
146
|
+
const keyServers = await this.getKeyServers();
|
|
147
|
+
const keyServersWithMultiplicity = [];
|
|
148
|
+
for (const [objectId, config] of this.#configs) {
|
|
149
|
+
const keyServer = keyServers.get(objectId);
|
|
150
|
+
for (let i = 0; i < config.weight; i++) keyServersWithMultiplicity.push(keyServer);
|
|
151
|
+
}
|
|
152
|
+
return keyServersWithMultiplicity;
|
|
153
|
+
}
|
|
154
|
+
async #loadKeyServers() {
|
|
155
|
+
const keyServers = await retrieveKeyServers({
|
|
156
|
+
objectIds: [...this.#configs.keys()],
|
|
157
|
+
client: this.#haneulClient,
|
|
158
|
+
configs: this.#configs
|
|
159
|
+
});
|
|
160
|
+
if (keyServers.length === 0) throw new InvalidKeyServerError("No key servers found");
|
|
161
|
+
if (this.#verifyKeyServers) await Promise.all(keyServers.map(async (server) => {
|
|
162
|
+
if (server.serverType === "Committee") return;
|
|
163
|
+
const config = this.#configs.get(server.objectId);
|
|
164
|
+
if (!await verifyKeyServer(server, this.#timeout, config?.apiKeyName, config?.apiKey)) throw new InvalidKeyServerError(`Key server ${server.objectId} is not valid`);
|
|
165
|
+
}));
|
|
166
|
+
return new Map(keyServers.map((server) => [server.objectId, server]));
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Fetch keys from the key servers and update the cache.
|
|
170
|
+
*
|
|
171
|
+
* It is recommended to call this function once for all ids of all encrypted objects if
|
|
172
|
+
* there are multiple, then call decrypt for each object. This avoids calling fetchKey
|
|
173
|
+
* individually for each decrypt.
|
|
174
|
+
*
|
|
175
|
+
* @param ids - The ids of the encrypted objects.
|
|
176
|
+
* @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
|
|
177
|
+
* @param sessionKey - The session key to use.
|
|
178
|
+
* @param threshold - The threshold for the TSS encryptions. The function returns when a threshold of key servers had returned keys for all ids.
|
|
179
|
+
*/
|
|
180
|
+
async fetchKeys({ ids, txBytes, sessionKey, threshold }) {
|
|
181
|
+
if (threshold > this.#totalWeight || threshold < 1) throw new InvalidThresholdError(`Invalid threshold ${threshold} servers with weights ${JSON.stringify(this.#configs)}`);
|
|
182
|
+
const keyServers = await this.getKeyServers();
|
|
183
|
+
const fullIds = ids.map((id) => createFullId(sessionKey.getPackageId(), id));
|
|
184
|
+
let completedWeight = 0;
|
|
185
|
+
const remainingKeyServers = [];
|
|
186
|
+
let remainingKeyServersWeight = 0;
|
|
187
|
+
for (const objectId of keyServers.keys()) if (fullIds.every((fullId) => this.#cachedKeys.has(`${fullId}:${objectId}`))) completedWeight += this.#weight(objectId);
|
|
188
|
+
else {
|
|
189
|
+
remainingKeyServers.push(objectId);
|
|
190
|
+
remainingKeyServersWeight += this.#weight(objectId);
|
|
191
|
+
}
|
|
192
|
+
if (completedWeight >= threshold) return;
|
|
193
|
+
const certificate = await sessionKey.getCertificate();
|
|
194
|
+
const signedRequest = await sessionKey.createRequestParams(txBytes);
|
|
195
|
+
const controller = new AbortController();
|
|
196
|
+
const errors = [];
|
|
197
|
+
const keyFetches = remainingKeyServers.map(async (objectId) => {
|
|
198
|
+
const server = keyServers.get(objectId);
|
|
199
|
+
try {
|
|
200
|
+
const config = this.#configs.get(objectId);
|
|
201
|
+
const allKeys = await fetchKeysForAllIds({
|
|
202
|
+
url: server.url,
|
|
203
|
+
requestSignature: signedRequest.requestSignature,
|
|
204
|
+
transactionBytes: txBytes,
|
|
205
|
+
encKey: signedRequest.encKey,
|
|
206
|
+
encKeyPk: signedRequest.encKeyPk,
|
|
207
|
+
encVerificationKey: signedRequest.encVerificationKey,
|
|
208
|
+
certificate,
|
|
209
|
+
timeout: this.#timeout,
|
|
210
|
+
apiKeyName: config?.apiKeyName,
|
|
211
|
+
apiKey: config?.apiKey,
|
|
212
|
+
signal: controller.signal
|
|
213
|
+
});
|
|
214
|
+
for (const { fullId, key } of allKeys) {
|
|
215
|
+
const keyElement = G1Element.fromBytes(key);
|
|
216
|
+
if (!BonehFranklinBLS12381Services.verifyUserSecretKey(keyElement, fullId, G2Element.fromBytes(server.pk))) {
|
|
217
|
+
console.warn("Received invalid key from key server " + server.objectId);
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
this.#cachedKeys.set(`${fullId}:${server.objectId}`, keyElement);
|
|
221
|
+
}
|
|
222
|
+
if (fullIds.every((fullId) => this.#cachedKeys.has(`${fullId}:${server.objectId}`))) {
|
|
223
|
+
completedWeight += this.#weight(objectId);
|
|
224
|
+
if (completedWeight >= threshold) controller.abort();
|
|
225
|
+
}
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (!controller.signal.aborted) errors.push(error);
|
|
228
|
+
} finally {
|
|
229
|
+
remainingKeyServersWeight -= this.#weight(objectId);
|
|
230
|
+
if (remainingKeyServersWeight < threshold - completedWeight) controller.abort(new TooManyFailedFetchKeyRequestsError());
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
await Promise.allSettled(keyFetches);
|
|
234
|
+
if (completedWeight < threshold) throw toMajorityError(errors);
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Get derived keys from the given services.
|
|
238
|
+
*
|
|
239
|
+
* @param id - The id of the encrypted object.
|
|
240
|
+
* @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
|
|
241
|
+
* @param sessionKey - The session key to use.
|
|
242
|
+
* @param threshold - The threshold.
|
|
243
|
+
* @returns - Derived keys for the given services that are in the cache as a "service object ID" -> derived key map. If the call is succesful, exactly threshold keys will be returned.
|
|
244
|
+
*/
|
|
245
|
+
async getDerivedKeys({ kemType = KemType.BonehFranklinBLS12381DemCCA, id, txBytes, sessionKey, threshold }) {
|
|
246
|
+
switch (kemType) {
|
|
247
|
+
case KemType.BonehFranklinBLS12381DemCCA:
|
|
248
|
+
const keyServers = await this.getKeyServers();
|
|
249
|
+
if (threshold > this.#totalWeight) throw new InvalidThresholdError(`Invalid threshold ${threshold} for ${this.#totalWeight} servers`);
|
|
250
|
+
await this.fetchKeys({
|
|
251
|
+
ids: [id],
|
|
252
|
+
txBytes,
|
|
253
|
+
sessionKey,
|
|
254
|
+
threshold
|
|
255
|
+
});
|
|
256
|
+
const fullId = createFullId(sessionKey.getPackageId(), id);
|
|
257
|
+
const derivedKeys = /* @__PURE__ */ new Map();
|
|
258
|
+
let weight = 0;
|
|
259
|
+
for (const objectId of keyServers.keys()) {
|
|
260
|
+
const cachedKey = this.#cachedKeys.get(`${fullId}:${objectId}`);
|
|
261
|
+
if (cachedKey) {
|
|
262
|
+
derivedKeys.set(objectId, new BonehFranklinBLS12381DerivedKey(cachedKey));
|
|
263
|
+
weight += this.#weight(objectId);
|
|
264
|
+
if (weight >= threshold) break;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return derivedKeys;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
//#endregion
|
|
273
|
+
export { SealClient };
|
|
274
|
+
//# sourceMappingURL=client.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.mjs","names":["#haneulClient","#configs","#totalWeight","#verifyKeyServers","#timeout","#getWeightedKeyServers","#createEncryptionInput","#validateEncryptionServices","#cachedKeys","#weight","#keyServers","#loadKeyServers","#cachedPublicKeys"],"sources":["../src/client.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\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\tInvalidClientOptionsError,\n\tInvalidKeyServerError,\n\tInvalidPackageError,\n\tInvalidThresholdError,\n\ttoMajorityError,\n\tTooManyFailedFetchKeyRequestsError,\n} from './error.js';\nimport { BonehFranklinBLS12381Services } from './ibe.js';\nimport {\n\tBonehFranklinBLS12381DerivedKey,\n\tretrieveKeyServers,\n\tverifyKeyServer,\n\tfetchKeysForAllIds,\n} from './key-server.js';\nimport type { DerivedKey, KeyServer } from './key-server.js';\nimport type {\n\tDecryptOptions,\n\tEncryptOptions,\n\tFetchKeysOptions,\n\tGetDerivedKeysOptions,\n\tKeyCacheKey,\n\tKeyServerConfig,\n\tSealClientOptions,\n\tSealCompatibleClient,\n\tSealOptions,\n} from './types.js';\nimport { createFullId, count } from './utils.js';\n\nexport function seal<Name = 'seal'>({ name = 'seal' as Name, ...options }: SealOptions<Name>) {\n\treturn {\n\t\tname,\n\t\tregister: (client: SealCompatibleClient) => {\n\t\t\treturn new SealClient({\n\t\t\t\thaneulClient: client,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\t};\n}\n\nexport class SealClient {\n\t#haneulClient: SealCompatibleClient;\n\t#configs: Map<string, KeyServerConfig>;\n\t#keyServers: Promise<Map<string, KeyServer>> | null = null;\n\t#verifyKeyServers: boolean;\n\t// A caching map for: fullId:object_id -> partial key.\n\t#cachedKeys = new Map<KeyCacheKey, G1Element>();\n\t#cachedPublicKeys = new Map<string, G2Element>();\n\t#timeout: number;\n\t#totalWeight: number;\n\n\tconstructor(options: SealClientOptions) {\n\t\tthis.#haneulClient = options.haneulClient;\n\n\t\tif (\n\t\t\tnew Set(options.serverConfigs.map((s) => s.objectId)).size !== options.serverConfigs.length\n\t\t) {\n\t\t\tthrow new InvalidClientOptionsError('Duplicate object IDs');\n\t\t}\n\n\t\tif (\n\t\t\toptions.serverConfigs.some((s) => (s.apiKeyName && !s.apiKey) || (!s.apiKeyName && s.apiKey))\n\t\t) {\n\t\t\tthrow new InvalidClientOptionsError(\n\t\t\t\t'Both apiKeyName and apiKey must be provided or not provided for all key servers',\n\t\t\t);\n\t\t}\n\n\t\tthis.#configs = new Map(options.serverConfigs.map((server) => [server.objectId, server]));\n\t\tthis.#totalWeight = options.serverConfigs\n\t\t\t.map((server) => server.weight)\n\t\t\t.reduce((sum, term) => sum + term, 0);\n\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}: EncryptOptions) {\n\t\tconst packageObj = await this.#haneulClient.core.getObject({ objectId: packageId });\n\t\tif (String(packageObj.object.version) !== '1') {\n\t\t\tthrow new InvalidPackageError(`Package ${packageId} is not the first version`);\n\t\t}\n\n\t\treturn encrypt({\n\t\t\tkeyServers: await this.#getWeightedKeyServers(),\n\t\t\tkemType,\n\t\t\tthreshold,\n\t\t\tpackageId,\n\t\t\tid,\n\t\t\tencryptionInput: this.#createEncryptionInput(\n\t\t\t\tdemType,\n\t\t\t\tdata as Uint8Array<ArrayBuffer>,\n\t\t\t\taad as Uint8Array<ArrayBuffer>,\n\t\t\t),\n\t\t});\n\t}\n\n\t#createEncryptionInput(\n\t\ttype: DemType,\n\t\tdata: Uint8Array<ArrayBuffer>,\n\t\taad: Uint8Array<ArrayBuffer>,\n\t): 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 or if the threshold cannot be met.\n\t *\n\t * If checkShareConsistency is true, the decrypted shares are checked for consistency, meaning that\n\t * any combination of at least threshold shares should either succesfully combine to the plaintext or fail.\n\t * This is useful in case the encryptor is not trusted and the decryptor wants to ensure all decryptors\n\t * receive the same output (e.g., for onchain encrypted voting).\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 * @param checkShareConsistency - If true, the shares are checked for consistency.\n\t * @param checkLEEncoding - If true, the encryption is also checked using an LE encoded nonce.\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\tcheckShareConsistency,\n\t\tcheckLEEncoding,\n\t}: DecryptOptions) {\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\tif (checkShareConsistency) {\n\t\t\tconst publicKeys = await this.getPublicKeys(\n\t\t\t\tencryptedObject.services.map(([objectId, _]) => objectId),\n\t\t\t);\n\t\t\treturn decrypt({\n\t\t\t\tencryptedObject,\n\t\t\t\tkeys: this.#cachedKeys,\n\t\t\t\tpublicKeys,\n\t\t\t\tcheckLEEncoding: false, // We intentionally do not support other encodings here\n\t\t\t});\n\t\t}\n\t\treturn decrypt({ encryptedObject, keys: this.#cachedKeys, checkLEEncoding });\n\t}\n\n\t#weight(objectId: string) {\n\t\treturn this.#configs.get(objectId)?.weight ?? 0;\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\tif (\n\t\t\tservices.some((objectId) => {\n\t\t\t\tconst countInClient = this.#weight(objectId);\n\t\t\t\treturn countInClient > 0 && countInClient !== count(services, objectId);\n\t\t\t})\n\t\t) {\n\t\t\tthrow new InconsistentKeyServersError(\n\t\t\t\t`Client's key servers must be a subset of the encrypted object's key servers`,\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.#totalWeight) {\n\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t`Invalid threshold ${threshold} for ${this.#totalWeight} servers`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync getKeyServers(): Promise<Map<string, KeyServer>> {\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\t\treturn this.#keyServers;\n\t}\n\n\t/**\n\t * Get the public keys for the given services.\n\t * If all public keys are not in the cache, they are retrieved.\n\t *\n\t * @param services - The services to get the public keys for.\n\t * @returns The public keys for the given services in the same order as the given services.\n\t */\n\tasync getPublicKeys(services: string[]): Promise<G2Element[]> {\n\t\tconst keyServers = await this.getKeyServers();\n\n\t\t// Collect the key servers not already in store or cache.\n\t\tconst missingKeyServers = services.filter(\n\t\t\t(objectId) => !keyServers.has(objectId) && !this.#cachedPublicKeys.has(objectId),\n\t\t);\n\n\t\t// If there are missing key servers, retrieve them and update the cache.\n\t\tif (missingKeyServers.length > 0) {\n\t\t\t(\n\t\t\t\tawait retrieveKeyServers({\n\t\t\t\t\tobjectIds: missingKeyServers,\n\t\t\t\t\tclient: this.#haneulClient,\n\t\t\t\t\tconfigs: this.#configs,\n\t\t\t\t})\n\t\t\t).forEach((keyServer) =>\n\t\t\t\tthis.#cachedPublicKeys.set(keyServer.objectId, G2Element.fromBytes(keyServer.pk)),\n\t\t\t);\n\t\t}\n\n\t\treturn services.map((objectId) => {\n\t\t\tconst keyServer = keyServers.get(objectId);\n\t\t\tif (keyServer) {\n\t\t\t\treturn G2Element.fromBytes(keyServer.pk);\n\t\t\t}\n\t\t\treturn this.#cachedPublicKeys.get(objectId)!;\n\t\t});\n\t}\n\n\t/**\n\t * Returns a list of key servers with multiplicity according to their weights.\n\t * The list is used for encryption.\n\t */\n\tasync #getWeightedKeyServers() {\n\t\tconst keyServers = await this.getKeyServers();\n\t\tconst keyServersWithMultiplicity = [];\n\t\tfor (const [objectId, config] of this.#configs) {\n\t\t\tconst keyServer = keyServers.get(objectId)!;\n\t\t\tfor (let i = 0; i < config.weight; i++) {\n\t\t\t\tkeyServersWithMultiplicity.push(keyServer);\n\t\t\t}\n\t\t}\n\t\treturn keyServersWithMultiplicity;\n\t}\n\n\tasync #loadKeyServers(): Promise<Map<string, KeyServer>> {\n\t\tconst keyServers = await retrieveKeyServers({\n\t\t\tobjectIds: [...this.#configs.keys()],\n\t\t\tclient: this.#haneulClient,\n\t\t\tconfigs: this.#configs,\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\t// Skip /service verification for committee key server type since the request goes through an aggregator.\n\t\t\t\t\tif (server.serverType === 'Committee') {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst config = this.#configs.get(server.objectId);\n\t\t\t\t\tif (!(await verifyKeyServer(server, this.#timeout, config?.apiKeyName, config?.apiKey))) {\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\t\treturn new Map(keyServers.map((server) => [server.objectId, server]));\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 objects 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({ ids, txBytes, sessionKey, threshold }: FetchKeysOptions) {\n\t\tif (threshold > this.#totalWeight || threshold < 1) {\n\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t`Invalid threshold ${threshold} servers with weights ${JSON.stringify(this.#configs)}`,\n\t\t\t);\n\t\t}\n\t\tconst keyServers = await this.getKeyServers();\n\t\tconst fullIds = ids.map((id) => createFullId(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\tlet completedWeight = 0;\n\t\tconst remainingKeyServers = [];\n\t\tlet remainingKeyServersWeight = 0;\n\t\tfor (const objectId of keyServers.keys()) {\n\t\t\tif (fullIds.every((fullId) => this.#cachedKeys.has(`${fullId}:${objectId}`))) {\n\t\t\t\tcompletedWeight += this.#weight(objectId);\n\t\t\t} else {\n\t\t\t\tremainingKeyServers.push(objectId);\n\t\t\t\tremainingKeyServersWeight += this.#weight(objectId);\n\t\t\t}\n\t\t}\n\n\t\t// Return early if we have enough keys from cache.\n\t\tif (completedWeight >= threshold) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst certificate = 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 (objectId) => {\n\t\t\tconst server = keyServers.get(objectId)!;\n\t\t\ttry {\n\t\t\t\tconst config = this.#configs.get(objectId);\n\t\t\t\tconst allKeys = await fetchKeysForAllIds({\n\t\t\t\t\turl: server.url,\n\t\t\t\t\trequestSignature: signedRequest.requestSignature,\n\t\t\t\t\ttransactionBytes: txBytes,\n\t\t\t\t\tencKey: signedRequest.encKey,\n\t\t\t\t\tencKeyPk: signedRequest.encKeyPk,\n\t\t\t\t\tencVerificationKey: signedRequest.encVerificationKey,\n\t\t\t\t\tcertificate,\n\t\t\t\t\ttimeout: this.#timeout,\n\t\t\t\t\tapiKeyName: config?.apiKeyName,\n\t\t\t\t\tapiKey: config?.apiKey,\n\t\t\t\t\tsignal: controller.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\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}\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\tif (fullIds.every((fullId) => this.#cachedKeys.has(`${fullId}:${server.objectId}`))) {\n\t\t\t\t\tcompletedWeight += this.#weight(objectId);\n\n\t\t\t\t\t// Return early if the completed servers is more than the threshold.\n\t\t\t\t\tif (completedWeight >= 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} finally {\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\tremainingKeyServersWeight -= this.#weight(objectId);\n\t\t\t\tif (remainingKeyServersWeight < threshold - completedWeight) {\n\t\t\t\t\tcontroller.abort(new TooManyFailedFetchKeyRequestsError());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tawait Promise.allSettled(keyFetches);\n\n\t\tif (completedWeight < threshold) {\n\t\t\tthrow toMajorityError(errors);\n\t\t}\n\t}\n\n\t/**\n\t * Get derived keys from the given services.\n\t *\n\t * @param id - The id of the encrypted object.\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.\n\t * @returns - Derived keys for the given services that are in the cache as a \"service object ID\" -> derived key map. If the call is succesful, exactly threshold keys will be returned.\n\t */\n\tasync getDerivedKeys({\n\t\tkemType = KemType.BonehFranklinBLS12381DemCCA,\n\t\tid,\n\t\ttxBytes,\n\t\tsessionKey,\n\t\tthreshold,\n\t}: GetDerivedKeysOptions): Promise<Map<string, DerivedKey>> {\n\t\tswitch (kemType) {\n\t\t\tcase KemType.BonehFranklinBLS12381DemCCA:\n\t\t\t\tconst keyServers = await this.getKeyServers();\n\t\t\t\tif (threshold > this.#totalWeight) {\n\t\t\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t\t\t`Invalid threshold ${threshold} for ${this.#totalWeight} servers`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait this.fetchKeys({\n\t\t\t\t\tids: [id],\n\t\t\t\t\ttxBytes,\n\t\t\t\t\tsessionKey,\n\t\t\t\t\tthreshold,\n\t\t\t\t});\n\n\t\t\t\t// After calling fetchKeys, we can be sure that there are at least `threshold` of the required keys in the cache.\n\t\t\t\t// It is also checked there that the KeyServerType is BonehFranklinBLS12381 for all services.\n\n\t\t\t\tconst fullId = createFullId(sessionKey.getPackageId(), id);\n\n\t\t\t\tconst derivedKeys = new Map();\n\t\t\t\tlet weight = 0;\n\t\t\t\tfor (const objectId of keyServers.keys()) {\n\t\t\t\t\t// The code below assumes that the KeyServerType is BonehFranklinBLS12381.\n\t\t\t\t\tconst cachedKey = this.#cachedKeys.get(`${fullId}:${objectId}`);\n\t\t\t\t\tif (cachedKey) {\n\t\t\t\t\t\tderivedKeys.set(objectId, new BonehFranklinBLS12381DerivedKey(cachedKey));\n\t\t\t\t\t\tweight += this.#weight(objectId);\n\t\t\t\t\t\tif (weight >= threshold) {\n\t\t\t\t\t\t\t// We have enough keys, so we can stop.\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn derivedKeys;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAmDA,IAAa,aAAb,MAAwB;CACvB;CACA;CACA,cAAsD;CACtD;CAEA,8BAAc,IAAI,KAA6B;CAC/C,oCAAoB,IAAI,KAAwB;CAChD;CACA;CAEA,YAAY,SAA4B;AACvC,QAAKA,eAAgB,QAAQ;AAE7B,MACC,IAAI,IAAI,QAAQ,cAAc,KAAK,MAAM,EAAE,SAAS,CAAC,CAAC,SAAS,QAAQ,cAAc,OAErF,OAAM,IAAI,0BAA0B,uBAAuB;AAG5D,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AKC,OAAQ,SAAS;AAGzC,SAAI,mBAAmB,UACtB,YAAW,OAAO;;YAGZ,OAAO;AACf,QAAI,CAAC,WAAW,OAAO,QACtB,QAAO,KAAK,MAAe;aAEnB;AAET,iCAA6B,MAAKA,OAAQ,SAAS;AACnD,QAAI,4BAA4B,YAAY,gBAC3C,YAAW,MAAM,IAAI,oCAAoC,CAAC;;IAG3D;AAEF,QAAM,QAAQ,WAAW,WAAW;AAEpC,MAAI,kBAAkB,UACrB,OAAM,gBAAgB,OAAO;;;;;;;;;;;CAa/B,MAAM,eAAe,EACpB,UAAU,QAAQ,6BAClB,IACA,SACA,YACA,aAC2D;AAC3D,UAAQ,SAAR;GACC,KAAK,QAAQ;IACZ,MAAM,aAAa,MAAM,KAAK,eAAe;AAC7C,QAAI,YAAY,MAAKP,YACpB,OAAM,IAAI,sBACT,qBAAqB,UAAU,OAAO,MAAKA,YAAa,UACxD;AAEF,UAAM,KAAK,UAAU;KACpB,KAAK,CAAC,GAAG;KACT;KACA;KACA;KACA,CAAC;IAKF,MAAM,SAAS,aAAa,WAAW,cAAc,EAAE,GAAG;IAE1D,MAAM,8BAAc,IAAI,KAAK;IAC7B,IAAI,SAAS;AACb,SAAK,MAAM,YAAY,WAAW,MAAM,EAAE;KAEzC,MAAM,YAAY,MAAKM,WAAY,IAAI,GAAG,OAAO,GAAG,WAAW;AAC/D,SAAI,WAAW;AACd,kBAAY,IAAI,UAAU,IAAI,gCAAgC,UAAU,CAAC;AACzE,gBAAU,MAAKC,OAAQ,SAAS;AAChC,UAAI,UAAU,UAEb;;;AAIH,WAAO"}
|
package/dist/decrypt.mjs
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { G2Element } from "./bls12381.mjs";
|
|
2
|
+
import { InvalidCiphertextError, UnsupportedFeatureError } from "./error.mjs";
|
|
3
|
+
import { createFullId, equals } from "./utils.mjs";
|
|
4
|
+
import { AesGcm256, Hmac256Ctr } from "./dem.mjs";
|
|
5
|
+
import { KeyPurpose, deriveKey } from "./kdf.mjs";
|
|
6
|
+
import { BonehFranklinBLS12381Services, decryptRandomness, verifyNonce, verifyNonceWithLE } from "./ibe.mjs";
|
|
7
|
+
import { combine, interpolate } from "./shamir.mjs";
|
|
8
|
+
import { fromHex } from "@haneullabs/bcs";
|
|
9
|
+
|
|
10
|
+
//#region src/decrypt.ts
|
|
11
|
+
/**
|
|
12
|
+
* Decrypt the given encrypted bytes with the given cached secret keys for the full ID.
|
|
13
|
+
* It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers
|
|
14
|
+
* otherwise, this will throw an error.
|
|
15
|
+
* Also, it's assumed that the keys were verified by the caller.
|
|
16
|
+
*
|
|
17
|
+
* If publicKeys are provided, the decrypted shares are checked for consistency, meaning that
|
|
18
|
+
* any combination of at least threshold shares should either succesfully combine to the plaintext or fail.
|
|
19
|
+
*
|
|
20
|
+
* @returns - The decrypted plaintext corresponding to ciphertext.
|
|
21
|
+
*/
|
|
22
|
+
async function decrypt({ encryptedObject, keys, publicKeys, checkLEEncoding }) {
|
|
23
|
+
if (!encryptedObject.encryptedShares.BonehFranklinBLS12381) throw new UnsupportedFeatureError("Encryption mode not supported");
|
|
24
|
+
const fullId = createFullId(encryptedObject.packageId, encryptedObject.id);
|
|
25
|
+
const inKeystore = encryptedObject.services.map((_, i) => i).filter((i) => keys.has(`${fullId}:${encryptedObject.services[i][0]}`));
|
|
26
|
+
if (inKeystore.length < encryptedObject.threshold) throw new Error("Not enough shares. Please fetch more keys.");
|
|
27
|
+
const encryptedShares = encryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedShares;
|
|
28
|
+
if (encryptedShares.length !== encryptedObject.services.length) throw new InvalidCiphertextError(`Mismatched shares ${encryptedShares.length} and services ${encryptedObject.services.length}`);
|
|
29
|
+
const nonce = G2Element.fromBytes(encryptedObject.encryptedShares.BonehFranklinBLS12381.nonce);
|
|
30
|
+
const shares = inKeystore.map((i) => {
|
|
31
|
+
const [objectId, index] = encryptedObject.services[i];
|
|
32
|
+
return {
|
|
33
|
+
index,
|
|
34
|
+
share: BonehFranklinBLS12381Services.decrypt(nonce, keys.get(`${fullId}:${objectId}`), encryptedShares[i], fromHex(fullId), [objectId, index])
|
|
35
|
+
};
|
|
36
|
+
});
|
|
37
|
+
const baseKey = combine(shares);
|
|
38
|
+
const randomnessKey = deriveKey(KeyPurpose.EncryptedRandomness, baseKey, encryptedShares, encryptedObject.threshold, encryptedObject.services.map(([objectIds, _]) => objectIds));
|
|
39
|
+
const randomness = decryptRandomness(encryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedRandomness, randomnessKey);
|
|
40
|
+
if (!(checkLEEncoding ? verifyNonceWithLE(nonce, randomness) : verifyNonce(nonce, randomness))) throw new InvalidCiphertextError("Invalid nonce");
|
|
41
|
+
if (publicKeys !== void 0) {
|
|
42
|
+
const polynomial = interpolate(shares);
|
|
43
|
+
if (BonehFranklinBLS12381Services.decryptAllSharesUsingRandomness(randomness, encryptedShares, encryptedObject.services, publicKeys, nonce, fromHex(fullId)).some(({ index, share }) => !equals(polynomial(index), share))) throw new InvalidCiphertextError("Invalid shares");
|
|
44
|
+
}
|
|
45
|
+
const demKey = deriveKey(KeyPurpose.DEM, baseKey, encryptedShares, encryptedObject.threshold, encryptedObject.services.map(([objectId, _]) => objectId));
|
|
46
|
+
if (encryptedObject.ciphertext.Aes256Gcm) return AesGcm256.decrypt(demKey, encryptedObject.ciphertext);
|
|
47
|
+
else if (encryptedObject.ciphertext.Hmac256Ctr) return Hmac256Ctr.decrypt(demKey, encryptedObject.ciphertext);
|
|
48
|
+
else throw new InvalidCiphertextError("Invalid ciphertext type");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
//#endregion
|
|
52
|
+
export { decrypt };
|
|
53
|
+
//# sourceMappingURL=decrypt.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decrypt.mjs","names":[],"sources":["../src/decrypt.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromHex } from '@haneullabs/bcs';\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 {\n\tBonehFranklinBLS12381Services,\n\tdecryptRandomness,\n\tverifyNonce,\n\tverifyNonceWithLE,\n} from './ibe.js';\nimport { deriveKey, KeyPurpose } from './kdf.js';\nimport type { KeyCacheKey } from './types.js';\nimport { createFullId, equals } from './utils.js';\nimport { combine, interpolate } from './shamir.js';\n\nexport interface DecryptOptions {\n\tencryptedObject: typeof EncryptedObject.$inferType;\n\tkeys: Map<KeyCacheKey, G1Element>;\n\tpublicKeys?: G2Element[];\n\tcheckLEEncoding?: boolean;\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 * Also, it's assumed that the keys were verified by the caller.\n *\n * If publicKeys are provided, the decrypted shares are checked for consistency, meaning that\n * any combination of at least threshold shares should either succesfully combine to the plaintext or fail.\n *\n * @returns - The decrypted plaintext corresponding to ciphertext.\n */\nexport async function decrypt({\n\tencryptedObject,\n\tkeys,\n\tpublicKeys,\n\tcheckLEEncoding,\n}: DecryptOptions): Promise<Uint8Array> {\n\tif (!encryptedObject.encryptedShares.BonehFranklinBLS12381) {\n\t\tthrow new UnsupportedFeatureError('Encryption mode not supported');\n\t}\n\n\tconst fullId = createFullId(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) => {\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) as Uint8Array<ArrayBuffer>;\n\t\treturn { index, share };\n\t});\n\n\t// Combine the decrypted shares into the key\n\tconst baseKey = combine(shares);\n\n\t// Decrypt randomness\n\tconst randomnessKey = deriveKey(\n\t\tKeyPurpose.EncryptedRandomness,\n\t\tbaseKey,\n\t\tencryptedShares,\n\t\tencryptedObject.threshold,\n\t\tencryptedObject.services.map(([objectIds, _]) => objectIds),\n\t);\n\tconst randomness = decryptRandomness(\n\t\tencryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedRandomness,\n\t\trandomnessKey,\n\t);\n\n\t// Verify that the nonce was created with the randomness.\n\tif (!(checkLEEncoding ? verifyNonceWithLE(nonce, randomness) : verifyNonce(nonce, randomness))) {\n\t\tthrow new InvalidCiphertextError('Invalid nonce');\n\t}\n\n\t// If public keys are provided, check consistency of the shares.\n\tconst checkShareConsistency = publicKeys !== undefined;\n\tif (checkShareConsistency) {\n\t\tconst polynomial = interpolate(shares);\n\t\tconst allShares = BonehFranklinBLS12381Services.decryptAllSharesUsingRandomness(\n\t\t\trandomness,\n\t\t\tencryptedShares,\n\t\t\tencryptedObject.services,\n\t\t\tpublicKeys,\n\t\t\tnonce,\n\t\t\tfromHex(fullId),\n\t\t);\n\t\tif (allShares.some(({ index, share }) => !equals(polynomial(index), share))) {\n\t\t\tthrow new InvalidCiphertextError('Invalid shares');\n\t\t}\n\t}\n\n\t// Derive the DEM key\n\tconst demKey = deriveKey(\n\t\tKeyPurpose.DEM,\n\t\tbaseKey,\n\t\tencryptedShares,\n\t\tencryptedObject.threshold,\n\t\tencryptedObject.services.map(([objectId, _]) => objectId),\n\t);\n\n\t// Decrypt the ciphertext\n\tif (encryptedObject.ciphertext.Aes256Gcm) {\n\t\treturn AesGcm256.decrypt(demKey, encryptedObject.ciphertext);\n\t} else if (encryptedObject.ciphertext.Hmac256Ctr) {\n\t\treturn Hmac256Ctr.decrypt(demKey, encryptedObject.ciphertext);\n\t} else {\n\t\tthrow new InvalidCiphertextError('Invalid ciphertext type');\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,eAAsB,QAAQ,EAC7B,iBACA,MACA,YACA,mBACuC;AACvC,KAAI,CAAC,gBAAgB,gBAAgB,sBACpC,OAAM,IAAI,wBAAwB,gCAAgC;CAGnE,MAAM,SAAS,aAAa,gBAAgB,WAAW,gBAAgB,GAAG;CAG1E,MAAM,aAAa,gBAAgB,SACjC,KAAK,GAAG,MAAM,EAAE,CAChB,QAAQ,MAAM,KAAK,IAAI,GAAG,OAAO,GAAG,gBAAgB,SAAS,GAAG,KAAK,CAAC;AAExE,KAAI,WAAW,SAAS,gBAAgB,UACvC,OAAM,IAAI,MAAM,6CAA6C;CAG9D,MAAM,kBAAkB,gBAAgB,gBAAgB,sBAAsB;AAC9E,KAAI,gBAAgB,WAAW,gBAAgB,SAAS,OACvD,OAAM,IAAI,uBACT,qBAAqB,gBAAgB,OAAO,gBAAgB,gBAAgB,SAAS,SACrF;CAGF,MAAM,QAAQ,UAAU,UAAU,gBAAgB,gBAAgB,sBAAsB,MAAM;CAG9F,MAAM,SAAS,WAAW,KAAK,MAAM;EACpC,MAAM,CAAC,UAAU,SAAS,gBAAgB,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