@decryption/curves 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +75 -0
- package/abstract/bls.d.ts +410 -0
- package/abstract/bls.js +433 -0
- package/abstract/curve.d.ts +441 -0
- package/abstract/curve.js +622 -0
- package/abstract/edwards.d.ts +319 -0
- package/abstract/edwards.js +697 -0
- package/abstract/fft.d.ts +438 -0
- package/abstract/fft.js +580 -0
- package/abstract/frost.d.ts +292 -0
- package/abstract/frost.js +705 -0
- package/abstract/hash-to-curve.d.ts +238 -0
- package/abstract/hash-to-curve.js +353 -0
- package/abstract/modular.d.ts +550 -0
- package/abstract/modular.js +872 -0
- package/abstract/montgomery.d.ts +95 -0
- package/abstract/montgomery.js +180 -0
- package/abstract/oprf.d.ts +354 -0
- package/abstract/oprf.js +358 -0
- package/abstract/poseidon.d.ts +198 -0
- package/abstract/poseidon.js +471 -0
- package/abstract/tower.d.ts +213 -0
- package/abstract/tower.js +963 -0
- package/abstract/weierstrass.d.ts +587 -0
- package/abstract/weierstrass.js +1421 -0
- package/bls12-381.d.ts +23 -0
- package/bls12-381.js +680 -0
- package/bn254.d.ts +74 -0
- package/bn254.js +248 -0
- package/ed25519.d.ts +211 -0
- package/ed25519.js +626 -0
- package/ed448.d.ts +184 -0
- package/ed448.js +596 -0
- package/esm/abstract/bls.js +429 -0
- package/esm/abstract/curve.js +610 -0
- package/esm/abstract/edwards.js +691 -0
- package/esm/abstract/fft.js +567 -0
- package/esm/abstract/frost.js +702 -0
- package/esm/abstract/hash-to-curve.js +345 -0
- package/esm/abstract/modular.js +849 -0
- package/esm/abstract/montgomery.js +177 -0
- package/esm/abstract/oprf.js +355 -0
- package/esm/abstract/poseidon.js +462 -0
- package/esm/abstract/tower.js +925 -0
- package/esm/abstract/weierstrass.js +1411 -0
- package/esm/bls12-381.js +677 -0
- package/esm/bn254.js +244 -0
- package/esm/ed25519.js +622 -0
- package/esm/ed448.js +593 -0
- package/esm/index.js +38 -0
- package/esm/misc.js +211 -0
- package/esm/nist.js +266 -0
- package/esm/secp256k1.js +465 -0
- package/esm/utils.js +597 -0
- package/esm/webcrypto.js +362 -0
- package/index.d.ts +0 -0
- package/index.js +38 -0
- package/misc.d.ts +113 -0
- package/misc.js +216 -0
- package/nist.d.ts +136 -0
- package/nist.js +269 -0
- package/package.json +46 -0
- package/secp256k1.d.ts +152 -0
- package/secp256k1.js +468 -0
- package/utils.d.ts +535 -0
- package/utils.js +626 -0
- package/webcrypto.d.ts +240 -0
- package/webcrypto.js +365 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Montgomery curve methods. It's not really whole montgomery curve,
|
|
3
|
+
* just bunch of very specific methods for X25519 / X448 from
|
|
4
|
+
* [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
8
|
+
import { abytes, aInRange, bytesToNumberLE, copyBytes, numberToBytesLE, randomBytes, validateObject, } from '../utils';
|
|
9
|
+
import { createKeygen } from './curve';
|
|
10
|
+
import { mod } from './modular';
|
|
11
|
+
const _0n = BigInt(0);
|
|
12
|
+
const _1n = BigInt(1);
|
|
13
|
+
const _2n = BigInt(2);
|
|
14
|
+
function validateOpts(curve) {
|
|
15
|
+
// Validate constructor config eagerly, but do not call user-provided hooks here:
|
|
16
|
+
// `randomBytes` may be transcript-backed or otherwise contextual. Runtime type checks are
|
|
17
|
+
// enough to fail fast on malformed configs without consuming user state.
|
|
18
|
+
validateObject(curve, {
|
|
19
|
+
P: 'bigint',
|
|
20
|
+
type: 'string',
|
|
21
|
+
adjustScalarBytes: 'function',
|
|
22
|
+
powPminus2: 'function',
|
|
23
|
+
}, {
|
|
24
|
+
randomBytes: 'function',
|
|
25
|
+
});
|
|
26
|
+
return Object.freeze({ ...curve });
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* @param curveDef - Montgomery curve definition.
|
|
30
|
+
* @returns ECDH helper namespace.
|
|
31
|
+
* @throws If the curve definition or derived shared point is invalid. {@link Error}
|
|
32
|
+
* @example
|
|
33
|
+
* Perform one X25519 key exchange through the generic Montgomery helper.
|
|
34
|
+
*
|
|
35
|
+
* ```ts
|
|
36
|
+
* import { x25519 } from '../ed25519';
|
|
37
|
+
* const alice = x25519.keygen();
|
|
38
|
+
* const shared = x25519.getSharedSecret(alice.secretKey, alice.publicKey);
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export function montgomery(curveDef) {
|
|
42
|
+
const CURVE = validateOpts(curveDef);
|
|
43
|
+
const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;
|
|
44
|
+
const is25519 = type === 'x25519';
|
|
45
|
+
if (!is25519 && type !== 'x448')
|
|
46
|
+
throw new Error('invalid type');
|
|
47
|
+
const randomBytes_ = rand === undefined ? randomBytes : rand;
|
|
48
|
+
const montgomeryBits = is25519 ? 255 : 448;
|
|
49
|
+
const fieldLen = is25519 ? 32 : 56;
|
|
50
|
+
const Gu = is25519 ? BigInt(9) : BigInt(5);
|
|
51
|
+
// RFC 7748 #5:
|
|
52
|
+
// The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and
|
|
53
|
+
// (156326 - 2) / 4 = 39081 for curve448/X448
|
|
54
|
+
// const a = is25519 ? 486662n : 156326n;
|
|
55
|
+
const a24 = is25519 ? BigInt(121665) : BigInt(39081);
|
|
56
|
+
// RFC: x25519 "the resulting integer is of the form 2^254 plus
|
|
57
|
+
// eight times a value between 0 and 2^251 - 1 (inclusive)"
|
|
58
|
+
// x448: "2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)"
|
|
59
|
+
const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);
|
|
60
|
+
const maxAdded = is25519
|
|
61
|
+
? BigInt(8) * _2n ** BigInt(251) - _1n
|
|
62
|
+
: BigInt(4) * _2n ** BigInt(445) - _1n;
|
|
63
|
+
const maxScalar = minScalar + maxAdded + _1n; // (inclusive)
|
|
64
|
+
const modP = (n) => mod(n, P);
|
|
65
|
+
const GuBytes = encodeU(Gu);
|
|
66
|
+
function encodeU(u) {
|
|
67
|
+
return numberToBytesLE(modP(u), fieldLen);
|
|
68
|
+
}
|
|
69
|
+
function decodeU(u) {
|
|
70
|
+
const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate'));
|
|
71
|
+
// RFC: When receiving such an array, implementations of X25519
|
|
72
|
+
// (but not X448) MUST mask the most significant bit in the final byte.
|
|
73
|
+
if (is25519)
|
|
74
|
+
_u[31] &= 127; // 0b0111_1111
|
|
75
|
+
// RFC: Implementations MUST accept non-canonical values and process them as
|
|
76
|
+
// if they had been reduced modulo the field prime. The non-canonical
|
|
77
|
+
// values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224
|
|
78
|
+
// - 1 through 2^448 - 1 for X448.
|
|
79
|
+
return modP(bytesToNumberLE(_u));
|
|
80
|
+
}
|
|
81
|
+
function decodeScalar(scalar) {
|
|
82
|
+
return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar'))));
|
|
83
|
+
}
|
|
84
|
+
function scalarMult(scalar, u) {
|
|
85
|
+
const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
|
|
86
|
+
// Some public keys are useless, of low-order. Curve author doesn't think
|
|
87
|
+
// it needs to be validated, but we do it nonetheless.
|
|
88
|
+
// https://cr.yp.to/ecdh.html#validate
|
|
89
|
+
if (pu === _0n)
|
|
90
|
+
throw new Error('invalid private or public key received');
|
|
91
|
+
return encodeU(pu);
|
|
92
|
+
}
|
|
93
|
+
// Computes public key from private. By doing scalar multiplication of base point.
|
|
94
|
+
function scalarMultBase(scalar) {
|
|
95
|
+
return scalarMult(scalar, GuBytes);
|
|
96
|
+
}
|
|
97
|
+
const getPublicKey = scalarMultBase;
|
|
98
|
+
const getSharedSecret = scalarMult;
|
|
99
|
+
// cswap from RFC7748 "example code"
|
|
100
|
+
function cswap(swap, x_2, x_3) {
|
|
101
|
+
// dummy = mask(swap) AND (x_2 XOR x_3)
|
|
102
|
+
// Where mask(swap) is the all-1 or all-0 word of the same length as x_2
|
|
103
|
+
// and x_3, computed, e.g., as mask(swap) = 0 - swap.
|
|
104
|
+
const dummy = modP(swap * (x_2 - x_3));
|
|
105
|
+
x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy
|
|
106
|
+
x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy
|
|
107
|
+
return { x_2, x_3 };
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Montgomery x-only multiplication ladder for the selected X25519/X448 curve.
|
|
111
|
+
* @param pointU - decoded Montgomery u coordinate for the selected curve
|
|
112
|
+
* @param scalar - decoded clamped scalar by which the point is multiplied
|
|
113
|
+
* @returns resulting Montgomery u coordinate for the selected curve
|
|
114
|
+
*/
|
|
115
|
+
function montgomeryLadder(u, scalar) {
|
|
116
|
+
aInRange('u', u, _0n, P);
|
|
117
|
+
aInRange('scalar', scalar, minScalar, maxScalar);
|
|
118
|
+
const k = scalar;
|
|
119
|
+
const x_1 = u;
|
|
120
|
+
let x_2 = _1n;
|
|
121
|
+
let z_2 = _0n;
|
|
122
|
+
let x_3 = u;
|
|
123
|
+
let z_3 = _1n;
|
|
124
|
+
let swap = _0n;
|
|
125
|
+
for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {
|
|
126
|
+
const k_t = (k >> t) & _1n;
|
|
127
|
+
swap ^= k_t;
|
|
128
|
+
({ x_2, x_3 } = cswap(swap, x_2, x_3));
|
|
129
|
+
({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
|
|
130
|
+
swap = k_t;
|
|
131
|
+
const A = x_2 + z_2;
|
|
132
|
+
const AA = modP(A * A);
|
|
133
|
+
const B = x_2 - z_2;
|
|
134
|
+
const BB = modP(B * B);
|
|
135
|
+
const E = AA - BB;
|
|
136
|
+
const C = x_3 + z_3;
|
|
137
|
+
const D = x_3 - z_3;
|
|
138
|
+
const DA = modP(D * A);
|
|
139
|
+
const CB = modP(C * B);
|
|
140
|
+
const dacb = DA + CB;
|
|
141
|
+
const da_cb = DA - CB;
|
|
142
|
+
x_3 = modP(dacb * dacb);
|
|
143
|
+
z_3 = modP(x_1 * modP(da_cb * da_cb));
|
|
144
|
+
x_2 = modP(AA * BB);
|
|
145
|
+
z_2 = modP(E * (AA + modP(a24 * E)));
|
|
146
|
+
}
|
|
147
|
+
({ x_2, x_3 } = cswap(swap, x_2, x_3));
|
|
148
|
+
({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
|
|
149
|
+
const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent
|
|
150
|
+
return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))
|
|
151
|
+
}
|
|
152
|
+
const lengths = {
|
|
153
|
+
secretKey: fieldLen,
|
|
154
|
+
publicKey: fieldLen,
|
|
155
|
+
seed: fieldLen,
|
|
156
|
+
};
|
|
157
|
+
const randomSecretKey = (seed) => {
|
|
158
|
+
seed = seed === undefined ? randomBytes_(fieldLen) : seed;
|
|
159
|
+
abytes(seed, lengths.seed, 'seed');
|
|
160
|
+
// Reuse caller-supplied seed bytes verbatim; clamping is deferred until
|
|
161
|
+
// decodeScalar(...) when the secret key is actually used.
|
|
162
|
+
return seed;
|
|
163
|
+
};
|
|
164
|
+
const utils = { randomSecretKey };
|
|
165
|
+
Object.freeze(lengths);
|
|
166
|
+
Object.freeze(utils);
|
|
167
|
+
return Object.freeze({
|
|
168
|
+
keygen: createKeygen(randomSecretKey, getPublicKey),
|
|
169
|
+
getSharedSecret,
|
|
170
|
+
getPublicKey,
|
|
171
|
+
scalarMult,
|
|
172
|
+
scalarMultBase,
|
|
173
|
+
utils,
|
|
174
|
+
GuBytes: GuBytes.slice(),
|
|
175
|
+
lengths,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RFC 9497: Oblivious Pseudorandom Functions (OPRFs) Using Prime-Order Groups.
|
|
3
|
+
* https://www.rfc-editor.org/rfc/rfc9497
|
|
4
|
+
*
|
|
5
|
+
|
|
6
|
+
OPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`:
|
|
7
|
+
|
|
8
|
+
- Server cannot calculate Output by itself: it doesn't know Input
|
|
9
|
+
- Client cannot calculate Output by itself: it doesn't know server secretKey
|
|
10
|
+
- An attacker interception the communication can't restore Input/Output/serverSecretKey and can't
|
|
11
|
+
link Input to some value.
|
|
12
|
+
|
|
13
|
+
## Issues
|
|
14
|
+
|
|
15
|
+
- Low-entropy inputs (e.g. password '123') enable brute-forced dictionary attacks by the server
|
|
16
|
+
(solveable by domain separation in POPRF)
|
|
17
|
+
- High-level protocol needs to be constructed on top, because OPRF is low-level
|
|
18
|
+
|
|
19
|
+
## Use cases
|
|
20
|
+
|
|
21
|
+
1. **Password-Authenticated Key Exchange (PAKE):** Enables secure password login (e.g., OPAQUE)
|
|
22
|
+
without revealing the password to the server.
|
|
23
|
+
2. **Private Set Intersection (PSI):** Allows two parties to compute the intersection of their
|
|
24
|
+
private sets without revealing non-intersecting elements.
|
|
25
|
+
3. **Anonymous Credential Systems:** Supports issuance of anonymous, unlinkable credentials
|
|
26
|
+
(e.g., Privacy Pass) using blind OPRF evaluation.
|
|
27
|
+
4. **Private Information Retrieval (PIR):** Helps users query databases without revealing which
|
|
28
|
+
item they accessed.
|
|
29
|
+
5. **Encrypted Search / Secure Indexing:** Enables keyword search over encrypted data while keeping
|
|
30
|
+
queries private.
|
|
31
|
+
6. **Spam Prevention and Rate-Limiting:** Issues anonymous tokens to prevent abuse
|
|
32
|
+
(e.g., CAPTCHA bypass) without compromising user privacy.
|
|
33
|
+
|
|
34
|
+
## Modes
|
|
35
|
+
|
|
36
|
+
- OPRF: simple mode, client doesn't need to know server public key
|
|
37
|
+
- VOPRF: verifiable mode. It lets the client verify that the server used the
|
|
38
|
+
secret key corresponding to a known public key
|
|
39
|
+
- POPRF: partially oblivious mode, VOPRF + domain separation
|
|
40
|
+
|
|
41
|
+
There is also non-interactive mode (Evaluate), which creates Output
|
|
42
|
+
non-interactively with knowledge of the secret key.
|
|
43
|
+
|
|
44
|
+
Flow:
|
|
45
|
+
- (once) Server generates secret and public keys, distributes public keys to clients
|
|
46
|
+
- deterministically: `deriveKeyPair` or just random: `generateKeyPair`
|
|
47
|
+
- Client blinds input: `blind(secretInput)`
|
|
48
|
+
- Server evaluates blinded input: `blindEvaluate` generated by client, sends result to client
|
|
49
|
+
- Client creates output using result of evaluation via 'finalize'
|
|
50
|
+
|
|
51
|
+
* @module
|
|
52
|
+
*/
|
|
53
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
54
|
+
import { abytes, asciiToBytes, bytesToNumberBE, bytesToNumberLE, concatBytes, numberToBytesBE, randomBytes, validateObject, } from '../utils';
|
|
55
|
+
import { pippenger, validatePointCons } from './curve';
|
|
56
|
+
import { _DST_scalar } from './hash-to-curve';
|
|
57
|
+
import { getMinHashLength, mapHashToField } from './modular';
|
|
58
|
+
const _DST_scalarBytes = /* @__PURE__ */ asciiToBytes(_DST_scalar);
|
|
59
|
+
// welcome to generic hell
|
|
60
|
+
/**
|
|
61
|
+
* @param opts - OPRF ciphersuite options. See {@link OPRFOpts}.
|
|
62
|
+
* @returns OPRF helper namespace.
|
|
63
|
+
* @example
|
|
64
|
+
* Instantiate an OPRF suite from curve-specific hashing hooks.
|
|
65
|
+
*
|
|
66
|
+
* ```ts
|
|
67
|
+
* import { createOPRF } from './oprf';
|
|
68
|
+
* import { p256, p256_hasher } from '../nist';
|
|
69
|
+
* import { sha256 } from '@decryption/hashes/sha2';
|
|
70
|
+
* const oprf = createOPRF({
|
|
71
|
+
* name: 'P256-SHA256',
|
|
72
|
+
* Point: p256.Point,
|
|
73
|
+
* hash: sha256,
|
|
74
|
+
* hashToGroup: p256_hasher.hashToCurve,
|
|
75
|
+
* hashToScalar: p256_hasher.hashToScalar,
|
|
76
|
+
* });
|
|
77
|
+
* const keys = oprf.oprf.generateKeyPair();
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export function createOPRF(opts) {
|
|
81
|
+
validateObject(opts, {
|
|
82
|
+
name: 'string',
|
|
83
|
+
hash: 'function',
|
|
84
|
+
hashToScalar: 'function',
|
|
85
|
+
hashToGroup: 'function',
|
|
86
|
+
});
|
|
87
|
+
// Cheap constructor-surface sanity check only: this verifies the generic static hooks/fields that
|
|
88
|
+
// OPRF consumes, but it does not certify point semantics like BASE/ZERO correctness.
|
|
89
|
+
validatePointCons(opts.Point);
|
|
90
|
+
const { name, Point, hash } = opts;
|
|
91
|
+
const { Fn } = Point;
|
|
92
|
+
const hashToGroup = (msg, ctx) => opts.hashToGroup(msg, {
|
|
93
|
+
DST: concatBytes(asciiToBytes('HashToGroup-'), ctx),
|
|
94
|
+
});
|
|
95
|
+
const hashToScalarPrefixed = (msg, ctx) => opts.hashToScalar(msg, { DST: concatBytes(_DST_scalarBytes, ctx) });
|
|
96
|
+
const randomScalar = (rng = randomBytes) => {
|
|
97
|
+
// RFC 9497 §2.1 defines RandomScalar as nonzero; blind inversion and generated public keys
|
|
98
|
+
// both rely on keeping this helper in the `1..n-1` range.
|
|
99
|
+
const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE);
|
|
100
|
+
// We cannot use Fn.fromBytes here, because field
|
|
101
|
+
// can have different number of bytes (like ed448)
|
|
102
|
+
return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);
|
|
103
|
+
};
|
|
104
|
+
const msm = (points, scalars) => pippenger(Point, points, scalars);
|
|
105
|
+
const getCtx = (mode) => concatBytes(asciiToBytes('OPRFV1-'), new Uint8Array([mode]), asciiToBytes('-' + name));
|
|
106
|
+
const ctxOPRF = getCtx(0x00);
|
|
107
|
+
const ctxVOPRF = getCtx(0x01);
|
|
108
|
+
const ctxPOPRF = getCtx(0x02);
|
|
109
|
+
function encode(...args) {
|
|
110
|
+
const res = [];
|
|
111
|
+
for (const a of args) {
|
|
112
|
+
if (typeof a === 'number')
|
|
113
|
+
res.push(numberToBytesBE(a, 2));
|
|
114
|
+
else if (typeof a === 'string')
|
|
115
|
+
res.push(asciiToBytes(a));
|
|
116
|
+
else {
|
|
117
|
+
abytes(a);
|
|
118
|
+
res.push(numberToBytesBE(a.length, 2), a);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
// No wipe here, since will modify actual bytes
|
|
122
|
+
return concatBytes(...res);
|
|
123
|
+
}
|
|
124
|
+
const inputBytes = (title, bytes) => {
|
|
125
|
+
abytes(bytes, undefined, title);
|
|
126
|
+
// RFC 9497 §1.2 limits PrivateInput/PublicInput to 2^16 - 1 bytes because these values are
|
|
127
|
+
// length-prefixed with two bytes before use throughout the protocol.
|
|
128
|
+
if (bytes.length > 0xffff)
|
|
129
|
+
throw new Error(`"${title}" expected Uint8Array of length <= 65535, got length=${bytes.length}`);
|
|
130
|
+
return bytes;
|
|
131
|
+
};
|
|
132
|
+
const hashInput = (...bytes) => hash(encode(...bytes, 'Finalize'));
|
|
133
|
+
function getTranscripts(B, C, D, ctx) {
|
|
134
|
+
const Bm = B.toBytes();
|
|
135
|
+
const seed = hash(encode(Bm, concatBytes(asciiToBytes('Seed-'), ctx)));
|
|
136
|
+
const res = [];
|
|
137
|
+
for (let i = 0; i < C.length; i++) {
|
|
138
|
+
const Ci = C[i].toBytes();
|
|
139
|
+
const Di = D[i].toBytes();
|
|
140
|
+
const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, 'Composite'), ctx);
|
|
141
|
+
res.push(di);
|
|
142
|
+
}
|
|
143
|
+
return res;
|
|
144
|
+
}
|
|
145
|
+
function computeComposites(B, C, D, ctx) {
|
|
146
|
+
const T = getTranscripts(B, C, D, ctx);
|
|
147
|
+
const M = msm(C, T);
|
|
148
|
+
const Z = msm(D, T);
|
|
149
|
+
return { M, Z };
|
|
150
|
+
}
|
|
151
|
+
function computeCompositesFast(k, B, C, D, ctx) {
|
|
152
|
+
const T = getTranscripts(B, C, D, ctx);
|
|
153
|
+
const M = msm(C, T);
|
|
154
|
+
// RFC 9497 §2.2.1 ComputeCompositesFast derives weights from both C and D in getTranscripts(),
|
|
155
|
+
// then uses the server shortcut Z = k * M instead of a second MSM over D.
|
|
156
|
+
const Z = M.multiply(k);
|
|
157
|
+
return { M, Z };
|
|
158
|
+
}
|
|
159
|
+
function challengeTranscript(B, M, Z, t2, t3, ctx) {
|
|
160
|
+
const [Bm, a0, a1, a2, a3] = [B, M, Z, t2, t3].map((i) => i.toBytes());
|
|
161
|
+
return hashToScalarPrefixed(encode(Bm, a0, a1, a2, a3, 'Challenge'), ctx);
|
|
162
|
+
}
|
|
163
|
+
function generateProof(ctx, k, B, C, D, rng) {
|
|
164
|
+
const { M, Z } = computeCompositesFast(k, B, C, D, ctx);
|
|
165
|
+
const r = randomScalar(rng);
|
|
166
|
+
const t2 = Point.BASE.multiply(r);
|
|
167
|
+
const t3 = M.multiply(r);
|
|
168
|
+
const c = challengeTranscript(B, M, Z, t2, t3, ctx);
|
|
169
|
+
const s = Fn.sub(r, Fn.mul(c, k)); // r - c*k
|
|
170
|
+
return concatBytes(...[c, s].map((i) => Fn.toBytes(i)));
|
|
171
|
+
}
|
|
172
|
+
function verifyProof(ctx, B, C, D, proof) {
|
|
173
|
+
abytes(proof, 2 * Fn.BYTES);
|
|
174
|
+
const { M, Z } = computeComposites(B, C, D, ctx);
|
|
175
|
+
const [c, s] = [proof.subarray(0, Fn.BYTES), proof.subarray(Fn.BYTES)].map((f) => Fn.fromBytes(f));
|
|
176
|
+
const t2 = Point.BASE.multiply(s).add(B.multiply(c)); // s*G + c*B
|
|
177
|
+
const t3 = M.multiply(s).add(Z.multiply(c)); // s*M + c*Z
|
|
178
|
+
const expectedC = challengeTranscript(B, M, Z, t2, t3, ctx);
|
|
179
|
+
if (!Fn.eql(c, expectedC))
|
|
180
|
+
throw new Error('proof verification failed');
|
|
181
|
+
}
|
|
182
|
+
function generateKeyPair() {
|
|
183
|
+
const skS = randomScalar();
|
|
184
|
+
const pkS = Point.BASE.multiply(skS);
|
|
185
|
+
return { secretKey: Fn.toBytes(skS), publicKey: pkS.toBytes() };
|
|
186
|
+
}
|
|
187
|
+
function deriveKeyPair(ctx, seed, info) {
|
|
188
|
+
// RFC 9497 §3.2.1 defines `seed[32]`; reject other sizes here because this public API already
|
|
189
|
+
// documents a 32-byte seed instead of generic input keying material.
|
|
190
|
+
abytes(seed, 32, 'seed');
|
|
191
|
+
info = inputBytes('keyInfo', info);
|
|
192
|
+
const dst = concatBytes(asciiToBytes('DeriveKeyPair'), ctx);
|
|
193
|
+
const msg = concatBytes(seed, encode(info), Uint8Array.of(0));
|
|
194
|
+
for (let counter = 0; counter <= 255; counter++) {
|
|
195
|
+
msg[msg.length - 1] = counter;
|
|
196
|
+
const skS = opts.hashToScalar(msg, { DST: dst });
|
|
197
|
+
if (Fn.is0(skS))
|
|
198
|
+
continue; // should not happen
|
|
199
|
+
return {
|
|
200
|
+
secretKey: Fn.toBytes(skS),
|
|
201
|
+
publicKey: Point.BASE.multiply(skS).toBytes(),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
throw new Error('Cannot derive key');
|
|
205
|
+
}
|
|
206
|
+
const wirePoint = (label, bytes) => {
|
|
207
|
+
const point = Point.fromBytes(bytes);
|
|
208
|
+
// RFC 9497 §3.3 says applications MUST reject group-identity Elements received over the wire
|
|
209
|
+
// after deserialization, even if the suite decoder itself accepts the identity encoding.
|
|
210
|
+
if (point.equals(Point.ZERO))
|
|
211
|
+
throw new Error(label + ' point at infinity');
|
|
212
|
+
return point;
|
|
213
|
+
};
|
|
214
|
+
function blind(ctx, input, rng = randomBytes) {
|
|
215
|
+
input = inputBytes('input', input);
|
|
216
|
+
const blind = randomScalar(rng);
|
|
217
|
+
const inputPoint = hashToGroup(input, ctx);
|
|
218
|
+
if (inputPoint.equals(Point.ZERO))
|
|
219
|
+
throw new Error('Input point at infinity');
|
|
220
|
+
const blinded = inputPoint.multiply(blind);
|
|
221
|
+
return { blind: Fn.toBytes(blind), blinded: blinded.toBytes() };
|
|
222
|
+
}
|
|
223
|
+
function evaluate(ctx, secretKey, input) {
|
|
224
|
+
input = inputBytes('input', input);
|
|
225
|
+
const skS = Fn.fromBytes(secretKey);
|
|
226
|
+
const inputPoint = hashToGroup(input, ctx);
|
|
227
|
+
if (inputPoint.equals(Point.ZERO))
|
|
228
|
+
throw new Error('Input point at infinity');
|
|
229
|
+
const unblinded = inputPoint.multiply(skS).toBytes();
|
|
230
|
+
return hashInput(input, unblinded);
|
|
231
|
+
}
|
|
232
|
+
const oprf = Object.freeze({
|
|
233
|
+
generateKeyPair,
|
|
234
|
+
deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxOPRF, seed, keyInfo),
|
|
235
|
+
blind: (input, rng = randomBytes) => blind(ctxOPRF, input, rng),
|
|
236
|
+
blindEvaluate(secretKey, blindedPoint) {
|
|
237
|
+
const skS = Fn.fromBytes(secretKey);
|
|
238
|
+
const elm = wirePoint('blinded', blindedPoint);
|
|
239
|
+
return elm.multiply(skS).toBytes();
|
|
240
|
+
},
|
|
241
|
+
finalize(input, blindBytes, evaluatedBytes) {
|
|
242
|
+
input = inputBytes('input', input);
|
|
243
|
+
const blind = Fn.fromBytes(blindBytes);
|
|
244
|
+
const evalPoint = wirePoint('evaluated', evaluatedBytes);
|
|
245
|
+
const unblinded = evalPoint.multiply(Fn.inv(blind)).toBytes();
|
|
246
|
+
return hashInput(input, unblinded);
|
|
247
|
+
},
|
|
248
|
+
evaluate: (secretKey, input) => evaluate(ctxOPRF, secretKey, input),
|
|
249
|
+
});
|
|
250
|
+
const voprf = Object.freeze({
|
|
251
|
+
generateKeyPair,
|
|
252
|
+
deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxVOPRF, seed, keyInfo),
|
|
253
|
+
blind: (input, rng = randomBytes) => blind(ctxVOPRF, input, rng),
|
|
254
|
+
blindEvaluateBatch(secretKey, publicKey, blinded, rng = randomBytes) {
|
|
255
|
+
if (!Array.isArray(blinded))
|
|
256
|
+
throw new Error('expected array');
|
|
257
|
+
const skS = Fn.fromBytes(secretKey);
|
|
258
|
+
const pkS = wirePoint('public key', publicKey);
|
|
259
|
+
const blindedPoints = blinded.map((i) => wirePoint('blinded', i));
|
|
260
|
+
const evaluated = blindedPoints.map((i) => i.multiply(skS));
|
|
261
|
+
const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng);
|
|
262
|
+
return { evaluated: evaluated.map((i) => i.toBytes()), proof };
|
|
263
|
+
},
|
|
264
|
+
blindEvaluate(secretKey, publicKey, blinded, rng = randomBytes) {
|
|
265
|
+
const res = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng);
|
|
266
|
+
return { evaluated: res.evaluated[0], proof: res.proof };
|
|
267
|
+
},
|
|
268
|
+
finalizeBatch(items, publicKey, proof) {
|
|
269
|
+
if (!Array.isArray(items))
|
|
270
|
+
throw new Error('expected array');
|
|
271
|
+
const pkS = wirePoint('public key', publicKey);
|
|
272
|
+
const blindedPoints = items.map((i) => wirePoint('blinded', i.blinded));
|
|
273
|
+
const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated));
|
|
274
|
+
verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof);
|
|
275
|
+
return items.map((i) => oprf.finalize(i.input, i.blind, i.evaluated));
|
|
276
|
+
},
|
|
277
|
+
finalize(input, blind, evaluated, blinded, publicKey, proof) {
|
|
278
|
+
return this.finalizeBatch([{ input, blind, evaluated, blinded }], publicKey, proof)[0];
|
|
279
|
+
},
|
|
280
|
+
evaluate: (secretKey, input) => evaluate(ctxVOPRF, secretKey, input),
|
|
281
|
+
});
|
|
282
|
+
// NOTE: info is domain separation
|
|
283
|
+
const poprf = (info) => {
|
|
284
|
+
info = inputBytes('info', info);
|
|
285
|
+
const m = hashToScalarPrefixed(encode('Info', info), ctxPOPRF);
|
|
286
|
+
const T = Point.BASE.multiply(m);
|
|
287
|
+
return Object.freeze({
|
|
288
|
+
generateKeyPair,
|
|
289
|
+
deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxPOPRF, seed, keyInfo),
|
|
290
|
+
blind(input, publicKey, rng = randomBytes) {
|
|
291
|
+
input = inputBytes('input', input);
|
|
292
|
+
const pkS = wirePoint('public key', publicKey);
|
|
293
|
+
const tweakedKey = T.add(pkS);
|
|
294
|
+
if (tweakedKey.equals(Point.ZERO))
|
|
295
|
+
throw new Error('tweakedKey point at infinity');
|
|
296
|
+
const blind = randomScalar(rng);
|
|
297
|
+
const inputPoint = hashToGroup(input, ctxPOPRF);
|
|
298
|
+
if (inputPoint.equals(Point.ZERO))
|
|
299
|
+
throw new Error('Input point at infinity');
|
|
300
|
+
const blindedPoint = inputPoint.multiply(blind);
|
|
301
|
+
return {
|
|
302
|
+
blind: Fn.toBytes(blind),
|
|
303
|
+
blinded: blindedPoint.toBytes(),
|
|
304
|
+
tweakedKey: tweakedKey.toBytes(),
|
|
305
|
+
};
|
|
306
|
+
},
|
|
307
|
+
blindEvaluateBatch(secretKey, blinded, rng = randomBytes) {
|
|
308
|
+
if (!Array.isArray(blinded))
|
|
309
|
+
throw new Error('expected array');
|
|
310
|
+
const skS = Fn.fromBytes(secretKey);
|
|
311
|
+
const t = Fn.add(skS, m);
|
|
312
|
+
// "Hence, this error can be a signal for the server to replace its
|
|
313
|
+
// private key". We throw inside; this should be impossible.
|
|
314
|
+
const invT = Fn.inv(t);
|
|
315
|
+
const blindedPoints = blinded.map((i) => wirePoint('blinded', i));
|
|
316
|
+
const evalPoints = blindedPoints.map((i) => i.multiply(invT));
|
|
317
|
+
const tweakedKey = Point.BASE.multiply(t);
|
|
318
|
+
const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng);
|
|
319
|
+
return { evaluated: evalPoints.map((i) => i.toBytes()), proof };
|
|
320
|
+
},
|
|
321
|
+
blindEvaluate(secretKey, blinded, rng = randomBytes) {
|
|
322
|
+
const res = this.blindEvaluateBatch(secretKey, [blinded], rng);
|
|
323
|
+
return { evaluated: res.evaluated[0], proof: res.proof };
|
|
324
|
+
},
|
|
325
|
+
finalizeBatch(items, proof, tweakedKey) {
|
|
326
|
+
if (!Array.isArray(items))
|
|
327
|
+
throw new Error('expected array');
|
|
328
|
+
const inputs = items.map((i) => inputBytes('input', i.input));
|
|
329
|
+
const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated));
|
|
330
|
+
verifyProof(ctxPOPRF, wirePoint('tweakedKey', tweakedKey), evalPoints, items.map((i) => wirePoint('blinded', i.blinded)), proof);
|
|
331
|
+
return items.map((i, j) => {
|
|
332
|
+
const blind = Fn.fromBytes(i.blind);
|
|
333
|
+
const point = evalPoints[j].multiply(Fn.inv(blind)).toBytes();
|
|
334
|
+
return hashInput(inputs[j], info, point);
|
|
335
|
+
});
|
|
336
|
+
},
|
|
337
|
+
finalize(input, blind, evaluated, blinded, proof, tweakedKey) {
|
|
338
|
+
return this.finalizeBatch([{ input, blind, evaluated, blinded }], proof, tweakedKey)[0];
|
|
339
|
+
},
|
|
340
|
+
evaluate(secretKey, input) {
|
|
341
|
+
input = inputBytes('input', input);
|
|
342
|
+
const skS = Fn.fromBytes(secretKey);
|
|
343
|
+
const inputPoint = hashToGroup(input, ctxPOPRF);
|
|
344
|
+
if (inputPoint.equals(Point.ZERO))
|
|
345
|
+
throw new Error('Input point at infinity');
|
|
346
|
+
const t = Fn.add(skS, m);
|
|
347
|
+
const invT = Fn.inv(t);
|
|
348
|
+
const unblinded = inputPoint.multiply(invT).toBytes();
|
|
349
|
+
return hashInput(input, info, unblinded);
|
|
350
|
+
},
|
|
351
|
+
});
|
|
352
|
+
};
|
|
353
|
+
const res = { name, oprf, voprf, poprf, __tests: Object.freeze({ Fn }) };
|
|
354
|
+
return Object.freeze(res);
|
|
355
|
+
}
|