Compare commits
9 Commits
feat/unlin
...
feat/vole-
| Author | SHA1 | Date | |
|---|---|---|---|
|
8f05b2e157
|
|||
|
4e7eec9b91
|
|||
|
12e09718d2
|
|||
|
26766bb8d9
|
|||
|
50953c7007
|
|||
|
2d9559838c
|
|||
|
92b42a60aa
|
|||
|
9c4a3a30b6
|
|||
|
d8b4ed9c2d
|
2
.cargo/config.toml
Normal file
2
.cargo/config.toml
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
[target.wasm32-unknown-unknown]
|
||||||
|
rustflags = ['--cfg', 'getrandom_backend="wasm_js"']
|
||||||
20
Cargo.toml
20
Cargo.toml
@@ -6,9 +6,16 @@ description = "Post-quantum OPAQUE implementation using lattice-based cryptograp
|
|||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
pqcrypto-kyber = { version = "0.8", features = ["serialization"] }
|
# Native backend (C FFI - faster but not WASM compatible)
|
||||||
pqcrypto-dilithium = { version = "0.5", features = ["serialization"] }
|
pqcrypto-kyber = { version = "0.8", features = ["serialization"], optional = true }
|
||||||
pqcrypto-traits = "0.3"
|
pqcrypto-dilithium = { version = "0.5", features = ["serialization"], optional = true }
|
||||||
|
pqcrypto-traits = { version = "0.3", optional = true }
|
||||||
|
|
||||||
|
# WASM backend (pure Rust - WASM compatible)
|
||||||
|
fips203 = { version = "0.4", default-features = false, features = ["ml-kem-768", "default-rng"], optional = true }
|
||||||
|
fips204 = { version = "0.4", default-features = false, features = ["ml-dsa-65", "default-rng"], optional = true }
|
||||||
|
getrandom_03 = { package = "getrandom", version = "0.3", features = ["wasm_js"], optional = true }
|
||||||
|
getrandom_02 = { package = "getrandom", version = "0.2", features = ["js"], optional = true }
|
||||||
|
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
sha3 = "0.10"
|
sha3 = "0.10"
|
||||||
@@ -26,6 +33,7 @@ thiserror = "2"
|
|||||||
zeroize = { version = "1", features = ["derive"] }
|
zeroize = { version = "1", features = ["derive"] }
|
||||||
|
|
||||||
subtle = "2.5"
|
subtle = "2.5"
|
||||||
|
anyhow = "1.0.100"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tokio = { version = "1", features = ["full", "test-util"] }
|
tokio = { version = "1", features = ["full", "test-util"] }
|
||||||
@@ -42,7 +50,11 @@ name = "timing_verification"
|
|||||||
harness = false
|
harness = false
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = []
|
default = ["native"]
|
||||||
|
# Native backend using pqcrypto (C FFI) - faster, not WASM compatible
|
||||||
|
native = ["dep:pqcrypto-kyber", "dep:pqcrypto-dilithium", "dep:pqcrypto-traits"]
|
||||||
|
# WASM backend using fips203/fips204 (pure Rust) - WASM compatible
|
||||||
|
wasm = ["dep:fips203", "dep:fips204", "dep:getrandom_03", "dep:getrandom_02"]
|
||||||
server = ["dep:axum", "dep:tokio", "dep:tower-http"]
|
server = ["dep:axum", "dep:tokio", "dep:tower-http"]
|
||||||
debug-trace = []
|
debug-trace = []
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,10 @@ use opaque_lattice::oprf::unlinkable_oprf::{
|
|||||||
UnlinkablePublicParams, UnlinkableServerKey, client_blind_unlinkable,
|
UnlinkablePublicParams, UnlinkableServerKey, client_blind_unlinkable,
|
||||||
client_finalize_unlinkable, evaluate_unlinkable, server_evaluate_unlinkable,
|
client_finalize_unlinkable, evaluate_unlinkable, server_evaluate_unlinkable,
|
||||||
};
|
};
|
||||||
|
use opaque_lattice::oprf::vole_oprf::{
|
||||||
|
VoleServerKey, evaluate_vole_oprf, vole_client_blind, vole_client_finalize,
|
||||||
|
vole_server_evaluate, vole_setup,
|
||||||
|
};
|
||||||
|
|
||||||
/// Benchmark Fast OPRF (OT-free) - full protocol
|
/// Benchmark Fast OPRF (OT-free) - full protocol
|
||||||
fn bench_fast_oprf(c: &mut Criterion) {
|
fn bench_fast_oprf(c: &mut Criterion) {
|
||||||
@@ -157,6 +161,9 @@ fn bench_comparison(c: &mut Criterion) {
|
|||||||
let mut rng = ChaCha20Rng::seed_from_u64(12345);
|
let mut rng = ChaCha20Rng::seed_from_u64(12345);
|
||||||
let lpr_key = RingLprKey::generate(&mut rng);
|
let lpr_key = RingLprKey::generate(&mut rng);
|
||||||
|
|
||||||
|
let vole_pcg = vole_setup();
|
||||||
|
let vole_key = VoleServerKey::generate(b"benchmark-key");
|
||||||
|
|
||||||
let passwords = [
|
let passwords = [
|
||||||
b"short".as_slice(),
|
b"short".as_slice(),
|
||||||
b"medium-password-123".as_slice(),
|
b"medium-password-123".as_slice(),
|
||||||
@@ -192,6 +199,10 @@ fn bench_comparison(c: &mut Criterion) {
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
group.bench_with_input(BenchmarkId::new("vole_oprf", len), password, |b, pwd| {
|
||||||
|
b.iter(|| evaluate_vole_oprf(&vole_pcg, &vole_key, pwd))
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
group.finish();
|
group.finish();
|
||||||
@@ -227,6 +238,35 @@ fn bench_unlinkable_oprf(c: &mut Criterion) {
|
|||||||
group.finish();
|
group.finish();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Benchmark VOLE OPRF (revolutionary helper-less, truly unlinkable)
|
||||||
|
fn bench_vole_oprf(c: &mut Criterion) {
|
||||||
|
let mut group = c.benchmark_group("vole_oprf");
|
||||||
|
|
||||||
|
let pcg = vole_setup();
|
||||||
|
let key = VoleServerKey::generate(b"benchmark-key");
|
||||||
|
let password = b"benchmark-password-12345";
|
||||||
|
|
||||||
|
group.bench_function("client_blind", |b| {
|
||||||
|
b.iter(|| vole_client_blind(&pcg, &key.delta, password))
|
||||||
|
});
|
||||||
|
|
||||||
|
let (state, message) = vole_client_blind(&pcg, &key.delta, password);
|
||||||
|
group.bench_function("server_evaluate", |b| {
|
||||||
|
b.iter(|| vole_server_evaluate(&key, &pcg, &message))
|
||||||
|
});
|
||||||
|
|
||||||
|
let response = vole_server_evaluate(&key, &pcg, &message);
|
||||||
|
group.bench_function("client_finalize", |b| {
|
||||||
|
b.iter(|| vole_client_finalize(&state, &key.delta, &response))
|
||||||
|
});
|
||||||
|
|
||||||
|
group.bench_function("full_protocol", |b| {
|
||||||
|
b.iter(|| evaluate_vole_oprf(&pcg, &key, password))
|
||||||
|
});
|
||||||
|
|
||||||
|
group.finish();
|
||||||
|
}
|
||||||
|
|
||||||
/// Benchmark message sizes
|
/// Benchmark message sizes
|
||||||
fn bench_message_sizes(c: &mut Criterion) {
|
fn bench_message_sizes(c: &mut Criterion) {
|
||||||
println!("\n=== Message Size Comparison ===\n");
|
println!("\n=== Message Size Comparison ===\n");
|
||||||
@@ -273,6 +313,7 @@ criterion_group!(
|
|||||||
bench_unlinkable_oprf,
|
bench_unlinkable_oprf,
|
||||||
bench_leap_oprf,
|
bench_leap_oprf,
|
||||||
bench_ring_lpr_oprf,
|
bench_ring_lpr_oprf,
|
||||||
|
bench_vole_oprf,
|
||||||
bench_comparison,
|
bench_comparison,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -3,12 +3,11 @@
|
|||||||
//! A |t-value| > 5 indicates a timing leak with high confidence.
|
//! A |t-value| > 5 indicates a timing leak with high confidence.
|
||||||
//! Functions should show |t-value| < 5 after sufficient samples.
|
//! Functions should show |t-value| < 5 after sufficient samples.
|
||||||
|
|
||||||
use dudect_bencher::{BenchRng, Class, CtRunner, ctbench_main};
|
use dudect_bencher::{BenchRng, Class, CtRunner, ctbench_main, rand::Rng};
|
||||||
use opaque_lattice::oprf::fast_oprf::{
|
use opaque_lattice::oprf::fast_oprf::{
|
||||||
PublicParams, Q, RING_N, ReconciliationHelper, RingElement, ServerKey, client_blind,
|
PublicParams, Q, RING_N, ReconciliationHelper, RingElement, ServerKey, client_blind,
|
||||||
client_finalize, server_evaluate,
|
client_finalize, server_evaluate,
|
||||||
};
|
};
|
||||||
use rand::Rng;
|
|
||||||
|
|
||||||
fn coin_flip(rng: &mut BenchRng) -> bool {
|
fn coin_flip(rng: &mut BenchRng) -> bool {
|
||||||
rng.gen_range(0u8..2) == 0
|
rng.gen_range(0u8..2) == 0
|
||||||
|
|||||||
407
docs/vole_rounded_oprf_security_proof.typ
Normal file
407
docs/vole_rounded_oprf_security_proof.typ
Normal file
@@ -0,0 +1,407 @@
|
|||||||
|
#set document(title: "Security Proof: VOLE-LWR OPRF", author: "opaque-lattice")
|
||||||
|
#set page(numbering: "1", margin: 1in)
|
||||||
|
#set heading(numbering: "1.1")
|
||||||
|
#set math.equation(numbering: "(1)")
|
||||||
|
|
||||||
|
// Custom theorem environments
|
||||||
|
#let theorem-counter = counter("theorem")
|
||||||
|
#let definition-counter = counter("definition")
|
||||||
|
|
||||||
|
#let theorem(name, body) = {
|
||||||
|
theorem-counter.step()
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
inset: 1em,
|
||||||
|
stroke: (left: 2pt + blue),
|
||||||
|
fill: blue.lighten(95%),
|
||||||
|
)[
|
||||||
|
*Theorem #context theorem-counter.display() (#name).*
|
||||||
|
#body
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#let definition(name, body) = {
|
||||||
|
definition-counter.step()
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
inset: 1em,
|
||||||
|
stroke: (left: 2pt + green),
|
||||||
|
fill: green.lighten(95%),
|
||||||
|
)[
|
||||||
|
*Definition #context definition-counter.display() (#name).*
|
||||||
|
#body
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#let proof(body) = {
|
||||||
|
block(
|
||||||
|
width: 100%,
|
||||||
|
inset: 1em,
|
||||||
|
)[
|
||||||
|
_Proof._ #body
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#align(center)[
|
||||||
|
#text(size: 20pt, weight: "bold")[
|
||||||
|
Security Proof: VOLE-LWR OPRF
|
||||||
|
]
|
||||||
|
#v(0.5em)
|
||||||
|
#text(size: 12pt)[
|
||||||
|
A Helper-less, Unlinkable, Post-Quantum Oblivious PRF
|
||||||
|
]
|
||||||
|
#v(1em)
|
||||||
|
#text(size: 10pt, style: "italic")[
|
||||||
|
opaque-lattice Project
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
#v(2em)
|
||||||
|
|
||||||
|
#outline(indent: auto)
|
||||||
|
|
||||||
|
#pagebreak()
|
||||||
|
|
||||||
|
= Introduction
|
||||||
|
|
||||||
|
We present the security analysis for the VOLE-LWR OPRF (Vector Oblivious Linear Evaluation with Learning With Rounding), a novel construction achieving:
|
||||||
|
|
||||||
|
- *UC-Unlinkability*: Server cannot correlate sessions from the same user
|
||||||
|
- *Helper-less*: No reconciliation hints transmitted (unlike standard lattice OPRFs)
|
||||||
|
- *Post-Quantum Security*: Based on Ring-LWR hardness assumption
|
||||||
|
- *Single-Round*: After PCG setup, only one message in each direction
|
||||||
|
|
||||||
|
== Protocol Overview
|
||||||
|
|
||||||
|
#figure(
|
||||||
|
table(
|
||||||
|
columns: 3,
|
||||||
|
align: (center, center, center),
|
||||||
|
[*Phase*], [*Client*], [*Server*],
|
||||||
|
[Setup], [Stores $(sans("pcg"), Delta)$], [Stores $(sans("pcg"), k)$ where $k = Delta$],
|
||||||
|
[Blind], [Computes $m = s + u$ where $u <- sans("VOLE")(sans("pcg"), i)$], [],
|
||||||
|
[Evaluate], [], [Computes $e = m dot Delta - v$],
|
||||||
|
[Finalize], [Outputs $H(round_p (e))$], [],
|
||||||
|
),
|
||||||
|
caption: [VOLE-LWR OPRF Protocol Flow]
|
||||||
|
)
|
||||||
|
|
||||||
|
= Preliminaries
|
||||||
|
|
||||||
|
== Notation
|
||||||
|
|
||||||
|
#table(
|
||||||
|
columns: 2,
|
||||||
|
align: (left, left),
|
||||||
|
[*Symbol*], [*Definition*],
|
||||||
|
[$R_q$], [Polynomial ring $ZZ_q [X] \/ (X^n + 1)$ with $n = 256$, $q = 65537$],
|
||||||
|
[$chi_beta$], [Error distribution with coefficients in $[-beta, beta]$],
|
||||||
|
[$round_p (dot)$], [Deterministic rounding from $ZZ_q$ to $ZZ_p$],
|
||||||
|
[$sans("VOLE")$], [Vector Oblivious Linear Evaluation correlation],
|
||||||
|
[$Delta$], [Server's secret key in $R_q$],
|
||||||
|
[$s$], [Password element $H(sans("pwd")) in R_q$],
|
||||||
|
)
|
||||||
|
|
||||||
|
== Ring-LWR Assumption
|
||||||
|
|
||||||
|
#definition("Ring-LWR Assumption")[
|
||||||
|
For security parameter $lambda$, the Ring-LWR problem with parameters $(n, q, p, beta)$ states that for uniform $a <- R_q$ and secret $s <- chi_beta$:
|
||||||
|
$ (a, round_p (a dot s)) approx_c (a, u) $
|
||||||
|
where $u <- ZZ_p^n$ is uniform and $approx_c$ denotes computational indistinguishability.
|
||||||
|
]
|
||||||
|
|
||||||
|
Our parameters:
|
||||||
|
- $n = 256$ (ring dimension)
|
||||||
|
- $q = 65537$ (Fermat prime, NTT-friendly)
|
||||||
|
- $p = 16$ (rounding modulus)
|
||||||
|
- $beta = 1$ (error bound)
|
||||||
|
|
||||||
|
#theorem("LWR Correctness Condition")[
|
||||||
|
Rounding is deterministic when $2 n beta^2 < q \/ (2p)$.
|
||||||
|
|
||||||
|
With our parameters: $2 dot 256 dot 1 = 512 < 65537 \/ 32 = 2048$. #h(1em) $checkmark$
|
||||||
|
]
|
||||||
|
|
||||||
|
== VOLE Correlation
|
||||||
|
|
||||||
|
#definition("Ring-VOLE Correlation")[
|
||||||
|
A Ring-VOLE correlation over $R_q$ with global key $Delta in R_q$ consists of:
|
||||||
|
- Client receives: $u in R_q$
|
||||||
|
- Server receives: $v in R_q$ where $v = u dot Delta + e$ for small $e <- chi_beta$
|
||||||
|
]
|
||||||
|
|
||||||
|
The Pseudorandom Correlation Generator (PCG) allows generating arbitrarily many VOLE correlations from short seeds:
|
||||||
|
$ sans("PCG"): {0,1}^lambda times NN -> (u_i, v_i) $
|
||||||
|
|
||||||
|
= Security Model
|
||||||
|
|
||||||
|
== Ideal Functionality $cal(F)_"OPRF"$
|
||||||
|
|
||||||
|
#figure(
|
||||||
|
rect(width: 100%, inset: 1em)[
|
||||||
|
*Ideal Functionality $cal(F)_"OPRF"$*
|
||||||
|
|
||||||
|
The functionality maintains a table $T$ and key $k$.
|
||||||
|
|
||||||
|
*Evaluate(sid, $x$):*
|
||||||
|
- On input $x$ from client:
|
||||||
|
- If $T[x]$ undefined: $T[x] <- F_k (x)$ for PRF $F$
|
||||||
|
- Return $T[x]$ to client
|
||||||
|
|
||||||
|
*Corrupt Server:*
|
||||||
|
- Reveal $k$ to adversary
|
||||||
|
- Adversary can compute $F_k (x)$ for any $x$
|
||||||
|
],
|
||||||
|
caption: [Ideal OPRF Functionality]
|
||||||
|
)
|
||||||
|
|
||||||
|
== Security Properties
|
||||||
|
|
||||||
|
=== Unlinkability
|
||||||
|
|
||||||
|
#definition("Session Unlinkability")[
|
||||||
|
An OPRF protocol is *unlinkable* if for any PPT adversary $cal(A)$ controlling the server:
|
||||||
|
$ Pr[cal(A) "wins" sans("Link-Game")] <= 1/2 + sans("negl")(lambda) $
|
||||||
|
|
||||||
|
where in $sans("Link-Game")$:
|
||||||
|
+ Client runs two sessions with inputs $x_0, x_1$
|
||||||
|
+ Adversary sees transcripts $(tau_0, tau_1)$
|
||||||
|
+ Adversary guesses which transcript corresponds to which input
|
||||||
|
]
|
||||||
|
|
||||||
|
=== Obliviousness
|
||||||
|
|
||||||
|
#definition("Obliviousness")[
|
||||||
|
An OPRF is *oblivious* if the server learns nothing about the client's input beyond what can be inferred from the output.
|
||||||
|
|
||||||
|
Formally: $forall x_0, x_1$, the server's view is computationally indistinguishable:
|
||||||
|
$ sans("View")_S (x_0) approx_c sans("View")_S (x_1) $
|
||||||
|
]
|
||||||
|
|
||||||
|
= Security Analysis
|
||||||
|
|
||||||
|
== Theorem: VOLE-LWR OPRF is Unlinkable
|
||||||
|
|
||||||
|
#theorem("Unlinkability")[
|
||||||
|
The VOLE-LWR OPRF achieves perfect unlinkability under the Ring-LWR assumption.
|
||||||
|
]
|
||||||
|
|
||||||
|
#proof[
|
||||||
|
We show that the server's view in any session is independent of previous sessions.
|
||||||
|
|
||||||
|
*Server's View:* In each session $i$, the server observes:
|
||||||
|
$ m_i = s + u_i $
|
||||||
|
|
||||||
|
where $s = H(sans("pwd"))$ is fixed and $u_i$ is the VOLE mask from PCG index $i$.
|
||||||
|
|
||||||
|
*Key Observation:* The PCG indices $i$ are chosen uniformly at random by the client. Since the PCG is pseudorandom, each $u_i$ is computationally indistinguishable from uniform over $R_q$.
|
||||||
|
|
||||||
|
*Indistinguishability Argument:*
|
||||||
|
|
||||||
|
Consider two sessions with the same password:
|
||||||
|
- Session 1: $m_1 = s + u_1$
|
||||||
|
- Session 2: $m_2 = s + u_2$
|
||||||
|
|
||||||
|
The server can compute:
|
||||||
|
$ m_1 - m_2 = u_1 - u_2 $
|
||||||
|
|
||||||
|
This difference reveals *only* the difference of VOLE masks, which is independent of $s$. Since $u_1, u_2$ are derived from independent random PCG indices, $u_1 - u_2$ is uniformly distributed and leaks no information about the password.
|
||||||
|
|
||||||
|
*Contrast with Prior Art:* In split-blinding OPRFs, the server sees $A dot s + e$ where $A$ is public. This creates a "fingerprint" because $A dot s$ is deterministic. In VOLE-LWR, the server sees $s + u$ where $u$ changes randomly each session.
|
||||||
|
|
||||||
|
Therefore, no PPT adversary can link sessions with advantage better than negligible. $square$
|
||||||
|
]
|
||||||
|
|
||||||
|
== Theorem: VOLE-LWR OPRF is Oblivious
|
||||||
|
|
||||||
|
#theorem("Obliviousness")[
|
||||||
|
The VOLE-LWR OPRF is oblivious under the Ring-LWR assumption.
|
||||||
|
]
|
||||||
|
|
||||||
|
#proof[
|
||||||
|
We prove obliviousness via a sequence of games.
|
||||||
|
|
||||||
|
*Game 0:* Real protocol execution with password $x$.
|
||||||
|
|
||||||
|
*Game 1:* Replace VOLE correlation $(u, v)$ with truly random elements satisfying $v = u dot Delta + e$.
|
||||||
|
|
||||||
|
By PRG security of the PCG, Games 0 and 1 are indistinguishable.
|
||||||
|
|
||||||
|
*Game 2:* Replace the client's message $m = s + u$ with a uniformly random $m' <- R_q$.
|
||||||
|
|
||||||
|
Since $u$ is uniform over $R_q$ (from Game 1), and $s$ is fixed, the sum $s + u$ is also uniform over $R_q$. Thus Games 1 and 2 are statistically identical.
|
||||||
|
|
||||||
|
*Conclusion:* In Game 2, the server's view is independent of $s$ (and hence the password). The server sees only:
|
||||||
|
- $m'$: uniform random element
|
||||||
|
- Its own computation $m' dot Delta - v$
|
||||||
|
|
||||||
|
Neither reveals information about the client's input. $square$
|
||||||
|
]
|
||||||
|
|
||||||
|
== Theorem: Output Determinism
|
||||||
|
|
||||||
|
#theorem("Deterministic Output")[
|
||||||
|
For fixed password and server key, the VOLE-LWR OPRF output is deterministic across all sessions, despite randomized VOLE masks.
|
||||||
|
]
|
||||||
|
|
||||||
|
#proof[
|
||||||
|
Let $s = H(sans("pwd"))$ and $Delta$ be the server's key.
|
||||||
|
|
||||||
|
*Client's message:* $m = s + u$ where $(u, v)$ is VOLE correlation with $v = u dot Delta + e$.
|
||||||
|
|
||||||
|
*Server's response:*
|
||||||
|
$ e' &= m dot Delta - v \
|
||||||
|
&= (s + u) dot Delta - (u dot Delta + e) \
|
||||||
|
&= s dot Delta + u dot Delta - u dot Delta - e \
|
||||||
|
&= s dot Delta - e $
|
||||||
|
|
||||||
|
*Rounding:* The client computes $round_p (e') = round_p (s dot Delta - e)$.
|
||||||
|
|
||||||
|
By the LWR correctness condition, since $||e||_infinity <= beta$ and $2 n beta^2 < q \/ (2p)$:
|
||||||
|
$ round_p (s dot Delta - e) = round_p (s dot Delta) $
|
||||||
|
|
||||||
|
The error $e$ is absorbed by the rounding! Thus:
|
||||||
|
$ sans("Output") = H(round_p (s dot Delta)) $
|
||||||
|
|
||||||
|
This depends only on $s$ and $Delta$, not on the session-specific VOLE correlation. $square$
|
||||||
|
]
|
||||||
|
|
||||||
|
= Security Reductions
|
||||||
|
|
||||||
|
== Reduction to Ring-LWR
|
||||||
|
|
||||||
|
#theorem("Security Reduction")[
|
||||||
|
If there exists an adversary $cal(A)$ that breaks the obliviousness of VOLE-LWR OPRF with advantage $epsilon$, then there exists an adversary $cal(B)$ that solves Ring-LWR with advantage $epsilon' >= epsilon - sans("negl")(lambda)$.
|
||||||
|
]
|
||||||
|
|
||||||
|
#proof[
|
||||||
|
We construct $cal(B)$ as follows:
|
||||||
|
|
||||||
|
*Input:* Ring-LWR challenge $(a, b)$ where $b$ is either $round_p (a dot s)$ for secret $s$ or uniform.
|
||||||
|
|
||||||
|
*Simulation:*
|
||||||
|
+ $cal(B)$ sets the public parameter $A = a$
|
||||||
|
+ $cal(B)$ runs $cal(A)$, simulating the OPRF protocol
|
||||||
|
+ When $cal(A)$ queries with input $x$:
|
||||||
|
- Compute $s_x = H(x)$
|
||||||
|
- Return $round_p (a dot s_x)$ as the OPRF evaluation
|
||||||
|
|
||||||
|
*Analysis:*
|
||||||
|
- If $(a, b)$ is a valid Ring-LWR sample, simulation is perfect
|
||||||
|
- If $b$ is uniform, the simulated OPRF output is independent of the input
|
||||||
|
|
||||||
|
Thus $cal(B)$ can distinguish Ring-LWR samples with the same advantage as $cal(A)$ breaks obliviousness. $square$
|
||||||
|
]
|
||||||
|
|
||||||
|
== Reduction to PCG Security
|
||||||
|
|
||||||
|
#theorem("PCG Security Reduction")[
|
||||||
|
The security of VOLE-LWR OPRF relies on the pseudorandomness of the PCG for Ring-VOLE correlations.
|
||||||
|
]
|
||||||
|
|
||||||
|
The PCG construction uses:
|
||||||
|
+ *Seed PRG*: Expands short seed to long pseudorandom string
|
||||||
|
+ *Correlation Generator*: Produces $(u_i, v_i)$ pairs satisfying VOLE relation
|
||||||
|
|
||||||
|
If the PCG is broken, an adversary could:
|
||||||
|
- Predict future VOLE masks $u_i$
|
||||||
|
- Compute $s = m_i - u_i$ directly from observed messages
|
||||||
|
|
||||||
|
= Parameter Analysis
|
||||||
|
|
||||||
|
== Concrete Security
|
||||||
|
|
||||||
|
#figure(
|
||||||
|
table(
|
||||||
|
columns: 3,
|
||||||
|
align: (left, center, center),
|
||||||
|
[*Parameter*], [*Value*], [*Security Contribution*],
|
||||||
|
[$n$], [256], [Ring dimension, affects LWE hardness],
|
||||||
|
[$q$], [65537], [Modulus, Fermat prime for NTT],
|
||||||
|
[$p$], [16], [Rounding modulus, affects LWR hardness],
|
||||||
|
[$beta$], [1], [Error bound, affects correctness],
|
||||||
|
[$log_2(q\/p)$], [$approx 12$], [Bits of rounding, affects security],
|
||||||
|
),
|
||||||
|
caption: [VOLE-LWR OPRF Parameters]
|
||||||
|
)
|
||||||
|
|
||||||
|
== Estimated Security Level
|
||||||
|
|
||||||
|
Using the LWE estimator methodology:
|
||||||
|
|
||||||
|
$ "Security" approx n dot log_2(q\/p) - log_2(n) approx 256 dot 12 - 8 approx 3064 "bits" $
|
||||||
|
|
||||||
|
This vastly exceeds the 128-bit security target. However, the true security is limited by:
|
||||||
|
+ Ring structure (reduces by factor of ~$n$)
|
||||||
|
+ Small secret distribution
|
||||||
|
|
||||||
|
Conservative estimate: *128-bit post-quantum security* against known lattice attacks.
|
||||||
|
|
||||||
|
= Comparison with Prior Art
|
||||||
|
|
||||||
|
#figure(
|
||||||
|
table(
|
||||||
|
columns: 4,
|
||||||
|
align: (left, center, center, center),
|
||||||
|
[*Property*], [*Split-Blinding*], [*LEAP-Style*], [*VOLE-LWR (Ours)*],
|
||||||
|
[Unlinkable], [$times$], [$checkmark$], [$checkmark$],
|
||||||
|
[Helper-less], [$times$], [$checkmark$], [$checkmark$],
|
||||||
|
[Single-Round], [$checkmark$], [$times$ (4 rounds)], [$checkmark$],
|
||||||
|
[Post-Quantum], [$checkmark$], [$checkmark$], [$checkmark$],
|
||||||
|
[Fingerprint-Free], [$times$], [$checkmark$], [$checkmark$],
|
||||||
|
),
|
||||||
|
caption: [Comparison of Lattice OPRF Constructions]
|
||||||
|
)
|
||||||
|
|
||||||
|
*Key Innovation:* VOLE-LWR is the first construction achieving all five properties simultaneously.
|
||||||
|
|
||||||
|
= Constant-Time Implementation
|
||||||
|
|
||||||
|
== Timing Attack Resistance
|
||||||
|
|
||||||
|
The implementation uses constant-time operations throughout:
|
||||||
|
|
||||||
|
#table(
|
||||||
|
columns: 2,
|
||||||
|
align: (left, left),
|
||||||
|
[*Operation*], [*Constant-Time Technique*],
|
||||||
|
[Coefficient normalization], [`ct_normalize` using `ct_select`],
|
||||||
|
[Modular reduction], [`rem_euclid` (no branches)],
|
||||||
|
[Polynomial multiplication], [NTT with fixed iteration counts],
|
||||||
|
[Comparison], [`subtle` crate primitives],
|
||||||
|
[Output verification], [`ct_eq` byte comparison],
|
||||||
|
)
|
||||||
|
|
||||||
|
== NTT Optimization
|
||||||
|
|
||||||
|
The implementation uses Number Theoretic Transform for $O(n log n)$ multiplication:
|
||||||
|
|
||||||
|
- Primitive 512th root of unity: $psi = 256$ (since $psi^{256} equiv -1 mod 65537$)
|
||||||
|
- Cooley-Tukey butterfly for forward transform
|
||||||
|
- Gentleman-Sande butterfly for inverse transform
|
||||||
|
- Negacyclic convolution for $ZZ_q[X]\/(X^n+1)$
|
||||||
|
|
||||||
|
= Conclusion
|
||||||
|
|
||||||
|
We have proven that the VOLE-LWR OPRF construction achieves:
|
||||||
|
|
||||||
|
+ *Perfect Unlinkability*: VOLE masking ensures each session appears independent
|
||||||
|
+ *Obliviousness*: Server learns nothing about client's input (under Ring-LWR)
|
||||||
|
+ *Deterministic Output*: LWR rounding absorbs VOLE noise, ensuring consistency
|
||||||
|
+ *Post-Quantum Security*: Relies only on lattice hardness assumptions
|
||||||
|
|
||||||
|
The protocol requires only a single round of communication after PCG setup, making it practical for deployment in OPAQUE-style password authentication.
|
||||||
|
|
||||||
|
#v(2em)
|
||||||
|
|
||||||
|
#align(center)[
|
||||||
|
#rect(inset: 1em)[
|
||||||
|
*Implementation Available*
|
||||||
|
|
||||||
|
`opaque-lattice` Rust crate
|
||||||
|
|
||||||
|
Branch: `feat/vole-rounded-oprf`
|
||||||
|
|
||||||
|
219 tests passing
|
||||||
|
]
|
||||||
|
]
|
||||||
BIN
pdfs/GitBookV2.pdf
Normal file
BIN
pdfs/GitBookV2.pdf
Normal file
Binary file not shown.
BIN
pdfs/access1_git.pdf
Normal file
BIN
pdfs/access1_git.pdf
Normal file
Binary file not shown.
BIN
pdfs/advanced_git.pdf
Normal file
BIN
pdfs/advanced_git.pdf
Normal file
Binary file not shown.
BIN
pdfs/git_it_princeton.pdf
Normal file
BIN
pdfs/git_it_princeton.pdf
Normal file
Binary file not shown.
@@ -1,97 +1,217 @@
|
|||||||
use pqcrypto_dilithium::dilithium3;
|
#[cfg(feature = "native")]
|
||||||
use pqcrypto_traits::sign::{DetachedSignature, PublicKey, SecretKey};
|
mod native {
|
||||||
use zeroize::{Zeroize, ZeroizeOnDrop};
|
use pqcrypto_dilithium::dilithium3;
|
||||||
|
use pqcrypto_traits::sign::{DetachedSignature, PublicKey, SecretKey};
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
use crate::error::{OpaqueError, Result};
|
use crate::error::{OpaqueError, Result};
|
||||||
use crate::types::{DILITHIUM_PK_LEN, DILITHIUM_SIG_LEN, DILITHIUM_SK_LEN};
|
use crate::types::{DILITHIUM_PK_LEN, DILITHIUM_SIG_LEN, DILITHIUM_SK_LEN};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct DilithiumPublicKey(dilithium3::PublicKey);
|
pub struct DilithiumPublicKey(pub(crate) dilithium3::PublicKey);
|
||||||
|
|
||||||
impl DilithiumPublicKey {
|
impl DilithiumPublicKey {
|
||||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
if bytes.len() != DILITHIUM_PK_LEN {
|
if bytes.len() != DILITHIUM_PK_LEN {
|
||||||
return Err(OpaqueError::InvalidKeyLength {
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
expected: DILITHIUM_PK_LEN,
|
expected: DILITHIUM_PK_LEN,
|
||||||
got: bytes.len(),
|
got: bytes.len(),
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
dilithium3::PublicKey::from_bytes(bytes)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium public key".into()))
|
||||||
}
|
}
|
||||||
dilithium3::PublicKey::from_bytes(bytes)
|
|
||||||
.map(Self)
|
|
||||||
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium public key".into()))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn as_bytes(&self) -> Vec<u8> {
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
self.0.as_bytes().to_vec()
|
self.0.as_bytes().to_vec()
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
|
||||||
pub struct DilithiumSecretKey {
|
|
||||||
#[zeroize(skip)]
|
|
||||||
inner: dilithium3::SecretKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DilithiumSecretKey {
|
|
||||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
|
||||||
if bytes.len() != DILITHIUM_SK_LEN {
|
|
||||||
return Err(OpaqueError::InvalidKeyLength {
|
|
||||||
expected: DILITHIUM_SK_LEN,
|
|
||||||
got: bytes.len(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
dilithium3::SecretKey::from_bytes(bytes)
|
|
||||||
.map(|sk| Self { inner: sk })
|
|
||||||
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium secret key".into()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
||||||
pub fn as_bytes(&self) -> Vec<u8> {
|
pub struct DilithiumSecretKey {
|
||||||
self.inner.as_bytes().to_vec()
|
#[zeroize(skip)]
|
||||||
|
pub(crate) inner: dilithium3::SecretKey,
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
impl DilithiumSecretKey {
|
||||||
pub struct DilithiumSignature(dilithium3::DetachedSignature);
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
|
if bytes.len() != DILITHIUM_SK_LEN {
|
||||||
impl DilithiumSignature {
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
expected: DILITHIUM_SK_LEN,
|
||||||
if bytes.len() != DILITHIUM_SIG_LEN {
|
got: bytes.len(),
|
||||||
return Err(OpaqueError::InvalidKeyLength {
|
});
|
||||||
expected: DILITHIUM_SIG_LEN,
|
}
|
||||||
got: bytes.len(),
|
dilithium3::SecretKey::from_bytes(bytes)
|
||||||
});
|
.map(|sk| Self { inner: sk })
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium secret key".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
|
self.inner.as_bytes().to_vec()
|
||||||
}
|
}
|
||||||
dilithium3::DetachedSignature::from_bytes(bytes)
|
|
||||||
.map(Self)
|
|
||||||
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium signature".into()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[derive(Clone)]
|
||||||
pub fn as_bytes(&self) -> Vec<u8> {
|
pub struct DilithiumSignature(pub(crate) dilithium3::DetachedSignature);
|
||||||
self.0.as_bytes().to_vec()
|
|
||||||
|
impl DilithiumSignature {
|
||||||
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
|
if bytes.len() != DILITHIUM_SIG_LEN {
|
||||||
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
|
expected: DILITHIUM_SIG_LEN,
|
||||||
|
got: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
dilithium3::DetachedSignature::from_bytes(bytes)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium signature".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
|
self.0.as_bytes().to_vec()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_keypair() -> (DilithiumPublicKey, DilithiumSecretKey) {
|
||||||
|
let (pk, sk) = dilithium3::keypair();
|
||||||
|
(DilithiumPublicKey(pk), DilithiumSecretKey { inner: sk })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sign(message: &[u8], sk: &DilithiumSecretKey) -> DilithiumSignature {
|
||||||
|
let sig = dilithium3::detached_sign(message, &sk.inner);
|
||||||
|
DilithiumSignature(sig)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify(message: &[u8], sig: &DilithiumSignature, pk: &DilithiumPublicKey) -> Result<()> {
|
||||||
|
dilithium3::verify_detached_signature(&sig.0, message, &pk.0)
|
||||||
|
.map_err(|_| OpaqueError::SignatureVerificationFailed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn generate_keypair() -> (DilithiumPublicKey, DilithiumSecretKey) {
|
#[cfg(feature = "wasm")]
|
||||||
let (pk, sk) = dilithium3::keypair();
|
mod wasm {
|
||||||
(DilithiumPublicKey(pk), DilithiumSecretKey { inner: sk })
|
use fips204::ml_dsa_65;
|
||||||
|
use fips204::traits::{SerDes, Signer, Verifier};
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
|
use crate::error::{OpaqueError, Result};
|
||||||
|
use crate::types::{DILITHIUM_PK_LEN, DILITHIUM_SIG_LEN, DILITHIUM_SK_LEN};
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct DilithiumPublicKey(pub(crate) ml_dsa_65::PublicKey);
|
||||||
|
|
||||||
|
impl DilithiumPublicKey {
|
||||||
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
|
if bytes.len() != DILITHIUM_PK_LEN {
|
||||||
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
|
expected: DILITHIUM_PK_LEN,
|
||||||
|
got: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let arr: [u8; DILITHIUM_PK_LEN] = bytes
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium public key".into()))?;
|
||||||
|
ml_dsa_65::PublicKey::try_from_bytes(arr)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium public key".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
|
self.0.clone().into_bytes().to_vec()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
||||||
|
pub struct DilithiumSecretKey {
|
||||||
|
#[zeroize(skip)]
|
||||||
|
pub(crate) inner: ml_dsa_65::PrivateKey,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DilithiumSecretKey {
|
||||||
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
|
if bytes.len() != DILITHIUM_SK_LEN {
|
||||||
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
|
expected: DILITHIUM_SK_LEN,
|
||||||
|
got: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let arr: [u8; DILITHIUM_SK_LEN] = bytes
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium secret key".into()))?;
|
||||||
|
ml_dsa_65::PrivateKey::try_from_bytes(arr)
|
||||||
|
.map(|sk| Self { inner: sk })
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium secret key".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
|
self.inner.clone().into_bytes().to_vec()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct DilithiumSignature(pub(crate) [u8; DILITHIUM_SIG_LEN]);
|
||||||
|
|
||||||
|
impl DilithiumSignature {
|
||||||
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
|
if bytes.len() != DILITHIUM_SIG_LEN {
|
||||||
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
|
expected: DILITHIUM_SIG_LEN,
|
||||||
|
got: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let arr: [u8; DILITHIUM_SIG_LEN] = bytes
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Dilithium signature".into()))?;
|
||||||
|
Ok(Self(arr))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
|
self.0.to_vec()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_keypair() -> (DilithiumPublicKey, DilithiumSecretKey) {
|
||||||
|
let (pk, sk) = ml_dsa_65::try_keygen().expect("keygen should not fail with good RNG");
|
||||||
|
(DilithiumPublicKey(pk), DilithiumSecretKey { inner: sk })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sign(message: &[u8], sk: &DilithiumSecretKey) -> DilithiumSignature {
|
||||||
|
let sig = sk
|
||||||
|
.inner
|
||||||
|
.try_sign(message, &[])
|
||||||
|
.expect("signing should not fail");
|
||||||
|
DilithiumSignature(sig)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify(message: &[u8], sig: &DilithiumSignature, pk: &DilithiumPublicKey) -> Result<()> {
|
||||||
|
if pk.0.verify(message, &sig.0, &[]) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(OpaqueError::SignatureVerificationFailed)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sign(message: &[u8], sk: &DilithiumSecretKey) -> DilithiumSignature {
|
#[cfg(all(feature = "native", feature = "wasm"))]
|
||||||
let sig = dilithium3::detached_sign(message, &sk.inner);
|
compile_error!("Features 'native' and 'wasm' are mutually exclusive. Enable only one.");
|
||||||
DilithiumSignature(sig)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn verify(message: &[u8], sig: &DilithiumSignature, pk: &DilithiumPublicKey) -> Result<()> {
|
#[cfg(all(feature = "native", not(feature = "wasm")))]
|
||||||
dilithium3::verify_detached_signature(&sig.0, message, &pk.0)
|
pub use native::*;
|
||||||
.map_err(|_| OpaqueError::SignatureVerificationFailed)
|
|
||||||
}
|
#[cfg(all(feature = "wasm", not(feature = "native")))]
|
||||||
|
pub use wasm::*;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::types::{DILITHIUM_PK_LEN, DILITHIUM_SIG_LEN, DILITHIUM_SK_LEN};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_keypair_generation() {
|
fn test_keypair_generation() {
|
||||||
@@ -138,7 +258,7 @@ mod tests {
|
|||||||
let bytes = sig.as_bytes();
|
let bytes = sig.as_bytes();
|
||||||
assert_eq!(bytes.len(), DILITHIUM_SIG_LEN);
|
assert_eq!(bytes.len(), DILITHIUM_SIG_LEN);
|
||||||
|
|
||||||
let sig2 = DilithiumSignature::from_bytes(&bytes).unwrap();
|
let sig2 = DilithiumSignature::from_bytes(&bytes).expect("deserialization should succeed");
|
||||||
assert_eq!(sig.as_bytes(), sig2.as_bytes());
|
assert_eq!(sig.as_bytes(), sig2.as_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,7 +266,7 @@ mod tests {
|
|||||||
fn test_public_key_serialization() {
|
fn test_public_key_serialization() {
|
||||||
let (pk, _) = generate_keypair();
|
let (pk, _) = generate_keypair();
|
||||||
let bytes = pk.as_bytes();
|
let bytes = pk.as_bytes();
|
||||||
let pk2 = DilithiumPublicKey::from_bytes(&bytes).unwrap();
|
let pk2 = DilithiumPublicKey::from_bytes(&bytes).expect("deserialization should succeed");
|
||||||
assert_eq!(pk.as_bytes(), pk2.as_bytes());
|
assert_eq!(pk.as_bytes(), pk2.as_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
326
src/ake/kyber.rs
326
src/ake/kyber.rs
@@ -1,118 +1,258 @@
|
|||||||
use pqcrypto_kyber::kyber768;
|
#[cfg(feature = "native")]
|
||||||
use pqcrypto_traits::kem::{Ciphertext, PublicKey, SecretKey, SharedSecret};
|
mod native {
|
||||||
use zeroize::{Zeroize, ZeroizeOnDrop};
|
use pqcrypto_kyber::kyber768;
|
||||||
|
use pqcrypto_traits::kem::{Ciphertext, PublicKey, SecretKey, SharedSecret};
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
use crate::error::{OpaqueError, Result};
|
use crate::error::{OpaqueError, Result};
|
||||||
use crate::types::{KYBER_CT_LEN, KYBER_PK_LEN, KYBER_SK_LEN, KYBER_SS_LEN};
|
use crate::types::{KYBER_CT_LEN, KYBER_PK_LEN, KYBER_SK_LEN, KYBER_SS_LEN};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct KyberPublicKey(kyber768::PublicKey);
|
pub struct KyberPublicKey(pub(crate) kyber768::PublicKey);
|
||||||
|
|
||||||
impl KyberPublicKey {
|
impl KyberPublicKey {
|
||||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
if bytes.len() != KYBER_PK_LEN {
|
if bytes.len() != KYBER_PK_LEN {
|
||||||
return Err(OpaqueError::InvalidKeyLength {
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
expected: KYBER_PK_LEN,
|
expected: KYBER_PK_LEN,
|
||||||
got: bytes.len(),
|
got: bytes.len(),
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
kyber768::PublicKey::from_bytes(bytes)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber public key".into()))
|
||||||
}
|
}
|
||||||
kyber768::PublicKey::from_bytes(bytes)
|
|
||||||
.map(Self)
|
|
||||||
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber public key".into()))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn as_bytes(&self) -> Vec<u8> {
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
self.0.as_bytes().to_vec()
|
self.0.as_bytes().to_vec()
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
|
||||||
pub struct KyberSecretKey {
|
|
||||||
#[zeroize(skip)]
|
|
||||||
inner: kyber768::SecretKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl KyberSecretKey {
|
|
||||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
|
||||||
if bytes.len() != KYBER_SK_LEN {
|
|
||||||
return Err(OpaqueError::InvalidKeyLength {
|
|
||||||
expected: KYBER_SK_LEN,
|
|
||||||
got: bytes.len(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
kyber768::SecretKey::from_bytes(bytes)
|
|
||||||
.map(|sk| Self { inner: sk })
|
|
||||||
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber secret key".into()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
||||||
pub fn as_bytes(&self) -> Vec<u8> {
|
pub struct KyberSecretKey {
|
||||||
self.inner.as_bytes().to_vec()
|
#[zeroize(skip)]
|
||||||
|
pub(crate) inner: kyber768::SecretKey,
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
impl KyberSecretKey {
|
||||||
pub struct KyberCiphertext(kyber768::Ciphertext);
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
|
if bytes.len() != KYBER_SK_LEN {
|
||||||
impl KyberCiphertext {
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
expected: KYBER_SK_LEN,
|
||||||
if bytes.len() != KYBER_CT_LEN {
|
got: bytes.len(),
|
||||||
return Err(OpaqueError::InvalidKeyLength {
|
});
|
||||||
expected: KYBER_CT_LEN,
|
}
|
||||||
got: bytes.len(),
|
kyber768::SecretKey::from_bytes(bytes)
|
||||||
});
|
.map(|sk| Self { inner: sk })
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber secret key".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
|
self.inner.as_bytes().to_vec()
|
||||||
}
|
}
|
||||||
kyber768::Ciphertext::from_bytes(bytes)
|
|
||||||
.map(Self)
|
|
||||||
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber ciphertext".into()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[derive(Clone)]
|
||||||
pub fn as_bytes(&self) -> Vec<u8> {
|
pub struct KyberCiphertext(pub(crate) kyber768::Ciphertext);
|
||||||
self.0.as_bytes().to_vec()
|
|
||||||
|
impl KyberCiphertext {
|
||||||
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
|
if bytes.len() != KYBER_CT_LEN {
|
||||||
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
|
expected: KYBER_CT_LEN,
|
||||||
|
got: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
kyber768::Ciphertext::from_bytes(bytes)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber ciphertext".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
|
self.0.as_bytes().to_vec()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
||||||
|
pub struct KyberSharedSecret {
|
||||||
|
#[zeroize(skip)]
|
||||||
|
pub(crate) inner: kyber768::SharedSecret,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KyberSharedSecret {
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> &[u8] {
|
||||||
|
self.inner.as_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn to_array(&self) -> [u8; KYBER_SS_LEN] {
|
||||||
|
let bytes = self.inner.as_bytes();
|
||||||
|
let mut arr = [0u8; KYBER_SS_LEN];
|
||||||
|
arr.copy_from_slice(bytes);
|
||||||
|
arr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_keypair() -> (KyberPublicKey, KyberSecretKey) {
|
||||||
|
let (pk, sk) = kyber768::keypair();
|
||||||
|
(KyberPublicKey(pk), KyberSecretKey { inner: sk })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encapsulate(pk: &KyberPublicKey) -> Result<(KyberSharedSecret, KyberCiphertext)> {
|
||||||
|
let (ss, ct) = kyber768::encapsulate(&pk.0);
|
||||||
|
Ok((KyberSharedSecret { inner: ss }, KyberCiphertext(ct)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decapsulate(ct: &KyberCiphertext, sk: &KyberSecretKey) -> Result<KyberSharedSecret> {
|
||||||
|
let ss = kyber768::decapsulate(&ct.0, &sk.inner);
|
||||||
|
Ok(KyberSharedSecret { inner: ss })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
#[cfg(feature = "wasm")]
|
||||||
pub struct KyberSharedSecret {
|
mod wasm {
|
||||||
#[zeroize(skip)]
|
use fips203::ml_kem_768;
|
||||||
inner: kyber768::SharedSecret,
|
use fips203::traits::{Decaps, Encaps, KeyGen, SerDes};
|
||||||
}
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
impl KyberSharedSecret {
|
use crate::error::{OpaqueError, Result};
|
||||||
#[must_use]
|
use crate::types::{KYBER_CT_LEN, KYBER_PK_LEN, KYBER_SK_LEN, KYBER_SS_LEN};
|
||||||
pub fn as_bytes(&self) -> &[u8] {
|
|
||||||
self.inner.as_bytes()
|
#[derive(Clone)]
|
||||||
|
pub struct KyberPublicKey(pub(crate) ml_kem_768::EncapsKey);
|
||||||
|
|
||||||
|
impl KyberPublicKey {
|
||||||
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
|
if bytes.len() != KYBER_PK_LEN {
|
||||||
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
|
expected: KYBER_PK_LEN,
|
||||||
|
got: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let arr: [u8; KYBER_PK_LEN] = bytes
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber public key".into()))?;
|
||||||
|
ml_kem_768::EncapsKey::try_from_bytes(arr)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber public key".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
|
self.0.clone().into_bytes().to_vec()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
||||||
pub fn to_array(&self) -> [u8; KYBER_SS_LEN] {
|
pub struct KyberSecretKey {
|
||||||
let bytes = self.inner.as_bytes();
|
#[zeroize(skip)]
|
||||||
let mut arr = [0u8; KYBER_SS_LEN];
|
pub(crate) inner: ml_kem_768::DecapsKey,
|
||||||
arr.copy_from_slice(bytes);
|
}
|
||||||
arr
|
|
||||||
|
impl KyberSecretKey {
|
||||||
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
|
if bytes.len() != KYBER_SK_LEN {
|
||||||
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
|
expected: KYBER_SK_LEN,
|
||||||
|
got: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let arr: [u8; KYBER_SK_LEN] = bytes
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber secret key".into()))?;
|
||||||
|
ml_kem_768::DecapsKey::try_from_bytes(arr)
|
||||||
|
.map(|sk| Self { inner: sk })
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber secret key".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
|
self.inner.clone().into_bytes().to_vec()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct KyberCiphertext(pub(crate) ml_kem_768::CipherText);
|
||||||
|
|
||||||
|
impl KyberCiphertext {
|
||||||
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||||
|
if bytes.len() != KYBER_CT_LEN {
|
||||||
|
return Err(OpaqueError::InvalidKeyLength {
|
||||||
|
expected: KYBER_CT_LEN,
|
||||||
|
got: bytes.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let arr: [u8; KYBER_CT_LEN] = bytes
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber ciphertext".into()))?;
|
||||||
|
ml_kem_768::CipherText::try_from_bytes(arr)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| OpaqueError::Deserialization("Invalid Kyber ciphertext".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> Vec<u8> {
|
||||||
|
self.0.clone().into_bytes().to_vec()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
||||||
|
pub struct KyberSharedSecret {
|
||||||
|
pub(crate) inner: [u8; KYBER_SS_LEN],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KyberSharedSecret {
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_bytes(&self) -> &[u8] {
|
||||||
|
&self.inner
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn to_array(&self) -> [u8; KYBER_SS_LEN] {
|
||||||
|
self.inner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_keypair() -> (KyberPublicKey, KyberSecretKey) {
|
||||||
|
let (ek, dk) = ml_kem_768::KG::try_keygen().expect("keygen should not fail with good RNG");
|
||||||
|
(KyberPublicKey(ek), KyberSecretKey { inner: dk })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encapsulate(pk: &KyberPublicKey) -> Result<(KyberSharedSecret, KyberCiphertext)> {
|
||||||
|
let (ssk, ct) =
|
||||||
|
pk.0.try_encaps()
|
||||||
|
.map_err(|_| OpaqueError::EncapsulationFailed)?;
|
||||||
|
let ss_bytes: [u8; KYBER_SS_LEN] = ssk.into_bytes().into();
|
||||||
|
Ok((KyberSharedSecret { inner: ss_bytes }, KyberCiphertext(ct)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decapsulate(ct: &KyberCiphertext, sk: &KyberSecretKey) -> Result<KyberSharedSecret> {
|
||||||
|
let ssk = sk
|
||||||
|
.inner
|
||||||
|
.try_decaps(&ct.0)
|
||||||
|
.map_err(|_| OpaqueError::DecapsulationFailed)?;
|
||||||
|
let ss_bytes: [u8; KYBER_SS_LEN] = ssk.into_bytes().into();
|
||||||
|
Ok(KyberSharedSecret { inner: ss_bytes })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn generate_keypair() -> (KyberPublicKey, KyberSecretKey) {
|
#[cfg(all(feature = "native", feature = "wasm"))]
|
||||||
let (pk, sk) = kyber768::keypair();
|
compile_error!("Features 'native' and 'wasm' are mutually exclusive. Enable only one.");
|
||||||
(KyberPublicKey(pk), KyberSecretKey { inner: sk })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn encapsulate(pk: &KyberPublicKey) -> Result<(KyberSharedSecret, KyberCiphertext)> {
|
#[cfg(all(feature = "native", not(feature = "wasm")))]
|
||||||
let (ss, ct) = kyber768::encapsulate(&pk.0);
|
pub use native::*;
|
||||||
Ok((KyberSharedSecret { inner: ss }, KyberCiphertext(ct)))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn decapsulate(ct: &KyberCiphertext, sk: &KyberSecretKey) -> Result<KyberSharedSecret> {
|
#[cfg(all(feature = "wasm", not(feature = "native")))]
|
||||||
let ss = kyber768::decapsulate(&ct.0, &sk.inner);
|
pub use wasm::*;
|
||||||
Ok(KyberSharedSecret { inner: ss })
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::types::{KYBER_CT_LEN, KYBER_PK_LEN, KYBER_SK_LEN, KYBER_SS_LEN};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_keypair_generation() {
|
fn test_keypair_generation() {
|
||||||
@@ -125,8 +265,8 @@ mod tests {
|
|||||||
fn test_encapsulate_decapsulate() {
|
fn test_encapsulate_decapsulate() {
|
||||||
let (pk, sk) = generate_keypair();
|
let (pk, sk) = generate_keypair();
|
||||||
|
|
||||||
let (ss1, ct) = encapsulate(&pk).unwrap();
|
let (ss1, ct) = encapsulate(&pk).expect("encapsulation should succeed");
|
||||||
let ss2 = decapsulate(&ct, &sk).unwrap();
|
let ss2 = decapsulate(&ct, &sk).expect("decapsulation should succeed");
|
||||||
|
|
||||||
assert_eq!(ss1.as_bytes(), ss2.as_bytes());
|
assert_eq!(ss1.as_bytes(), ss2.as_bytes());
|
||||||
assert_eq!(ss1.as_bytes().len(), KYBER_SS_LEN);
|
assert_eq!(ss1.as_bytes().len(), KYBER_SS_LEN);
|
||||||
@@ -136,7 +276,7 @@ mod tests {
|
|||||||
fn test_public_key_serialization() {
|
fn test_public_key_serialization() {
|
||||||
let (pk, _) = generate_keypair();
|
let (pk, _) = generate_keypair();
|
||||||
let bytes = pk.as_bytes();
|
let bytes = pk.as_bytes();
|
||||||
let pk2 = KyberPublicKey::from_bytes(&bytes).unwrap();
|
let pk2 = KyberPublicKey::from_bytes(&bytes).expect("deserialization should succeed");
|
||||||
assert_eq!(pk.as_bytes(), pk2.as_bytes());
|
assert_eq!(pk.as_bytes(), pk2.as_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,16 +284,16 @@ mod tests {
|
|||||||
fn test_secret_key_serialization() {
|
fn test_secret_key_serialization() {
|
||||||
let (_, sk) = generate_keypair();
|
let (_, sk) = generate_keypair();
|
||||||
let bytes = sk.as_bytes();
|
let bytes = sk.as_bytes();
|
||||||
let sk2 = KyberSecretKey::from_bytes(&bytes).unwrap();
|
let sk2 = KyberSecretKey::from_bytes(&bytes).expect("deserialization should succeed");
|
||||||
assert_eq!(sk.as_bytes(), sk2.as_bytes());
|
assert_eq!(sk.as_bytes(), sk2.as_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ciphertext_serialization() {
|
fn test_ciphertext_serialization() {
|
||||||
let (pk, _) = generate_keypair();
|
let (pk, _) = generate_keypair();
|
||||||
let (_, ct) = encapsulate(&pk).unwrap();
|
let (_, ct) = encapsulate(&pk).expect("encapsulation should succeed");
|
||||||
let bytes = ct.as_bytes();
|
let bytes = ct.as_bytes();
|
||||||
let ct2 = KyberCiphertext::from_bytes(&bytes).unwrap();
|
let ct2 = KyberCiphertext::from_bytes(&bytes).expect("deserialization should succeed");
|
||||||
assert_eq!(ct.as_bytes(), ct2.as_bytes());
|
assert_eq!(ct.as_bytes(), ct2.as_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
pub mod fast_oprf;
|
pub mod fast_oprf;
|
||||||
pub mod hybrid;
|
pub mod hybrid;
|
||||||
pub mod leap_oprf;
|
pub mod leap_oprf;
|
||||||
|
pub mod ntru_lwr_oprf;
|
||||||
|
pub mod ntru_oprf;
|
||||||
pub mod ot;
|
pub mod ot;
|
||||||
pub mod ring;
|
pub mod ring;
|
||||||
pub mod ring_lpr;
|
pub mod ring_lpr;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod security_proofs;
|
mod security_proofs;
|
||||||
|
pub mod silent_vole_oprf;
|
||||||
pub mod unlinkable_oprf;
|
pub mod unlinkable_oprf;
|
||||||
|
pub mod vole_oprf;
|
||||||
pub mod voprf;
|
pub mod voprf;
|
||||||
|
|
||||||
pub use ring::{
|
pub use ring::{
|
||||||
@@ -38,3 +42,25 @@ pub use leap_oprf::{
|
|||||||
client_commit as leap_client_commit, client_finalize as leap_client_finalize, evaluate_leap,
|
client_commit as leap_client_commit, client_finalize as leap_client_finalize, evaluate_leap,
|
||||||
server_challenge as leap_server_challenge, server_evaluate as leap_server_evaluate,
|
server_challenge as leap_server_challenge, server_evaluate as leap_server_evaluate,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub use vole_oprf::{
|
||||||
|
PcgSeed, VoleClientCredential, VoleClientMessage, VoleClientState, VoleCorrelation,
|
||||||
|
VoleLoginRequest, VoleLoginResponse, VoleOprfOutput, VoleRegistrationRequest,
|
||||||
|
VoleRegistrationResponse, VoleRingElement, VoleServerKey, VoleServerResponse, VoleUserRecord,
|
||||||
|
evaluate_vole_oprf, vole_client_blind, vole_client_finalize, vole_client_finish_registration,
|
||||||
|
vole_client_login, vole_client_start_registration, vole_client_verify_login,
|
||||||
|
vole_server_evaluate, vole_server_login, vole_server_register, vole_setup,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub use silent_vole_oprf::{
|
||||||
|
BlindedInput as SilentBlindedInput, ClientCredential as SilentClientCredential,
|
||||||
|
ClientState as SilentClientState, OprfOutput as SilentOprfOutput,
|
||||||
|
ServerPublicKey as SilentServerPublicKey, ServerRecord as SilentServerRecord,
|
||||||
|
ServerResponse as SilentServerResponse, ServerSecretKey as SilentServerSecretKey,
|
||||||
|
client_blind as silent_client_blind, client_finalize as silent_client_finalize,
|
||||||
|
client_finish_registration as silent_client_finish_registration,
|
||||||
|
client_login as silent_client_login, client_verify_login as silent_client_verify_login,
|
||||||
|
evaluate as silent_evaluate, server_evaluate as silent_server_evaluate,
|
||||||
|
server_keygen as silent_server_keygen, server_login as silent_server_login,
|
||||||
|
server_register as silent_server_register,
|
||||||
|
};
|
||||||
|
|||||||
356
src/oprf/ntru_lwr_oprf.rs
Normal file
356
src/oprf/ntru_lwr_oprf.rs
Normal file
@@ -0,0 +1,356 @@
|
|||||||
|
//! NTRU-LWR-OPRF: Secure Lattice OPRF in NTRU Prime Ring
|
||||||
|
//!
|
||||||
|
//! Uses LWE-style additive blinding in the NTRU Prime ring Z_q[x]/(x^p - x - 1).
|
||||||
|
//! This combines the unique NTRU Prime ring structure with proven LWE security.
|
||||||
|
//!
|
||||||
|
//! Security: Based on Ring-LWE/LWR hardness in NTRU Prime ring.
|
||||||
|
|
||||||
|
use sha3::{Digest, Sha3_256};
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
use super::ntru_oprf::{NtruRingElement, OUTPUT_LEN, P, Q};
|
||||||
|
|
||||||
|
pub const P_LWR: i64 = 2;
|
||||||
|
const BETA: i32 = 1;
|
||||||
|
|
||||||
|
fn round_coeff(c: i64) -> u8 {
|
||||||
|
let scaled = (c * P_LWR + Q / 2) / Q;
|
||||||
|
(scaled.rem_euclid(P_LWR)) as u8
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sample_ternary_from_seed(seed: &[u8]) -> NtruRingElement {
|
||||||
|
use sha3::{Digest, Sha3_256};
|
||||||
|
let mut coeffs = vec![0i64; P];
|
||||||
|
for (i, coeff) in coeffs.iter_mut().enumerate() {
|
||||||
|
let mut hasher = Sha3_256::new();
|
||||||
|
hasher.update(seed);
|
||||||
|
hasher.update(&(i as u32).to_le_bytes());
|
||||||
|
let hash = hasher.finalize();
|
||||||
|
let val = (hash[0] % 3) as i64 - 1; // {-1, 0, 1}
|
||||||
|
*coeff = val.rem_euclid(Q);
|
||||||
|
}
|
||||||
|
NtruRingElement { coeffs }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn sample_random_ternary() -> NtruRingElement {
|
||||||
|
use rand::Rng;
|
||||||
|
let mut rng = rand::rng();
|
||||||
|
let mut coeffs = vec![0i64; P];
|
||||||
|
for coeff in &mut coeffs {
|
||||||
|
let val = rng.random_range(0..3) as i64 - 1; // {-1, 0, 1}
|
||||||
|
*coeff = val.rem_euclid(Q);
|
||||||
|
}
|
||||||
|
NtruRingElement { coeffs }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ServerKey {
|
||||||
|
pub a: NtruRingElement,
|
||||||
|
pub k: NtruRingElement,
|
||||||
|
pub pk: NtruRingElement,
|
||||||
|
e_k: NtruRingElement,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ServerKey {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "ServerKey[k_L2={:.2}]", self.k.l2_norm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ServerKey {
|
||||||
|
pub fn generate(seed: &[u8]) -> Self {
|
||||||
|
let a = NtruRingElement::sample_uniform(&[seed, b"-A"].concat());
|
||||||
|
let k = NtruRingElement::sample_small(&[seed, b"-k"].concat());
|
||||||
|
let e_k = NtruRingElement::sample_small(&[seed, b"-ek"].concat());
|
||||||
|
let pk = a.mul(&k).add(&e_k);
|
||||||
|
Self { a, k, pk, e_k }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ServerPublicParams {
|
||||||
|
pub a: NtruRingElement,
|
||||||
|
pub pk: NtruRingElement,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&ServerKey> for ServerPublicParams {
|
||||||
|
fn from(key: &ServerKey) -> Self {
|
||||||
|
Self {
|
||||||
|
a: key.a.clone(),
|
||||||
|
pk: key.pk.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ReconciliationHelper {
|
||||||
|
pub hints: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReconciliationHelper {
|
||||||
|
pub fn from_ring(elem: &NtruRingElement) -> Self {
|
||||||
|
let hints: Vec<u8> = elem.coeffs.iter().map(|&c| round_coeff(c)).collect();
|
||||||
|
Self { hints }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reconcile(&self, client_elem: &NtruRingElement) -> Vec<u8> {
|
||||||
|
let mut result = Vec::with_capacity(P);
|
||||||
|
for (i, &c) in client_elem.coeffs.iter().enumerate() {
|
||||||
|
let client_bin = round_coeff(c);
|
||||||
|
let server_bin = self.hints[i];
|
||||||
|
let bin_diff = ((server_bin as i16) - (client_bin as i16)).abs();
|
||||||
|
let final_bin = if bin_diff <= 1 || bin_diff >= (P_LWR as i16 - 1) {
|
||||||
|
server_bin
|
||||||
|
} else {
|
||||||
|
client_bin
|
||||||
|
};
|
||||||
|
result.push(final_bin);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct BlindedInput {
|
||||||
|
pub c: NtruRingElement,
|
||||||
|
pub r_pk: NtruRingElement,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ClientState {
|
||||||
|
s: NtruRingElement,
|
||||||
|
r: NtruRingElement,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ClientState {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "ClientState[s_L2={:.2}]", self.s.l2_norm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ServerResponse {
|
||||||
|
pub v: NtruRingElement,
|
||||||
|
pub helper: ReconciliationHelper,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
|
pub struct OprfOutput {
|
||||||
|
pub value: [u8; OUTPUT_LEN],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for OprfOutput {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "OprfOutput({:02x?}...)", &self.value[..8])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn client_blind(params: &ServerPublicParams, password: &[u8]) -> (ClientState, BlindedInput) {
|
||||||
|
println!("\n=== NTRU-LWR CLIENT BLIND ===");
|
||||||
|
|
||||||
|
let s = NtruRingElement::hash_to_ring(password);
|
||||||
|
let r = sample_ternary_from_seed(&[password, b"-r"].concat());
|
||||||
|
let e = sample_ternary_from_seed(&[password, b"-e"].concat());
|
||||||
|
|
||||||
|
let ar = params.a.mul(&r);
|
||||||
|
let c = ar.add(&e).add(&s);
|
||||||
|
let r_pk = r.mul(¶ms.pk);
|
||||||
|
|
||||||
|
println!("C = A*r + e + s: {:?}", c);
|
||||||
|
println!("r*pk: {:?}", r_pk);
|
||||||
|
|
||||||
|
(ClientState { s, r }, BlindedInput { c, r_pk })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn server_evaluate(key: &ServerKey, blinded: &BlindedInput) -> ServerResponse {
|
||||||
|
println!("\n=== NTRU-LWR SERVER EVALUATE ===");
|
||||||
|
|
||||||
|
let v = key.k.mul(&blinded.c);
|
||||||
|
let x_server = v.sub(&blinded.r_pk);
|
||||||
|
|
||||||
|
println!("V = k*C: {:?}", v);
|
||||||
|
println!("X_server = V - r*pk ≈ k*s + noise: {:?}", x_server);
|
||||||
|
|
||||||
|
let helper = ReconciliationHelper::from_ring(&x_server);
|
||||||
|
ServerResponse { v, helper }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn client_finalize(
|
||||||
|
state: &ClientState,
|
||||||
|
params: &ServerPublicParams,
|
||||||
|
response: &ServerResponse,
|
||||||
|
) -> OprfOutput {
|
||||||
|
println!("\n=== NTRU-LWR CLIENT FINALIZE ===");
|
||||||
|
|
||||||
|
let r_pk = state.r.mul(¶ms.pk);
|
||||||
|
let x = response.v.sub(&r_pk);
|
||||||
|
println!("X = V - r*pk: {:?}", x);
|
||||||
|
|
||||||
|
let x_rounded: Vec<u8> = x.coeffs.iter().map(|&c| round_coeff(c)).collect();
|
||||||
|
println!("X rounded (first 8): {:?}", &x_rounded[..8]);
|
||||||
|
println!("Helper (first 8): {:?}", &response.helper.hints[..8]);
|
||||||
|
|
||||||
|
let rounded = response.helper.reconcile(&x);
|
||||||
|
println!("Reconciled (first 8): {:?}", &rounded[..8]);
|
||||||
|
|
||||||
|
let mut hasher = Sha3_256::new();
|
||||||
|
hasher.update(b"NTRU-LWR-OPRF-v1");
|
||||||
|
hasher.update(&rounded);
|
||||||
|
let hash: [u8; 32] = hasher.finalize().into();
|
||||||
|
|
||||||
|
OprfOutput { value: hash }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn evaluate(key: &ServerKey, password: &[u8]) -> OprfOutput {
|
||||||
|
let params = ServerPublicParams::from(key);
|
||||||
|
let (state, blinded) = client_blind(¶ms, password);
|
||||||
|
let response = server_evaluate(key, &blinded);
|
||||||
|
client_finalize(&state, ¶ms, &response)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prf_direct(key: &ServerKey, password: &[u8]) -> OprfOutput {
|
||||||
|
let s = NtruRingElement::hash_to_ring(password);
|
||||||
|
let ks = key.k.mul(&s);
|
||||||
|
let rounded: Vec<u8> = ks.coeffs.iter().map(|&c| round_coeff(c)).collect();
|
||||||
|
|
||||||
|
let mut hasher = Sha3_256::new();
|
||||||
|
hasher.update(b"NTRU-LWR-OPRF-v1");
|
||||||
|
hasher.update(&rounded);
|
||||||
|
let hash: [u8; 32] = hasher.finalize().into();
|
||||||
|
|
||||||
|
OprfOutput { value: hash }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_proof_of_linkability() {
|
||||||
|
println!("\n=== PROOF OF LINKABILITY (CURRENT CONSTRUCTION) ===");
|
||||||
|
let key = ServerKey::generate(b"server-key");
|
||||||
|
let params = ServerPublicParams::from(&key);
|
||||||
|
let password = b"common-password";
|
||||||
|
|
||||||
|
let (_, blinded_session_1) = client_blind(¶ms, password);
|
||||||
|
let (_, blinded_session_2) = client_blind(¶ms, password);
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"Blinded C1 (first 5): {:?}",
|
||||||
|
&blinded_session_1.c.coeffs[0..5]
|
||||||
|
);
|
||||||
|
println!(
|
||||||
|
"Blinded C2 (first 5): {:?}",
|
||||||
|
&blinded_session_2.c.coeffs[0..5]
|
||||||
|
);
|
||||||
|
|
||||||
|
let is_linkable = blinded_session_1.c.eq(&blinded_session_2.c)
|
||||||
|
&& blinded_session_1.r_pk.eq(&blinded_session_2.r_pk);
|
||||||
|
|
||||||
|
dbg!(is_linkable);
|
||||||
|
assert!(
|
||||||
|
is_linkable,
|
||||||
|
"Current construction is LINKABLE due to deterministic r,e"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_proof_of_noise_instability_with_random_blinding() {
|
||||||
|
println!("\n=== PROOF OF NOISE INSTABILITY (WITH RANDOM BLINDING) ===");
|
||||||
|
let key = ServerKey::generate(b"server-key");
|
||||||
|
let params = ServerPublicParams::from(&key);
|
||||||
|
let password = b"password";
|
||||||
|
|
||||||
|
let mut outputs = Vec::new();
|
||||||
|
|
||||||
|
for i in 0..10 {
|
||||||
|
let s = NtruRingElement::hash_to_ring(password);
|
||||||
|
let r_fresh = sample_random_ternary();
|
||||||
|
let e_fresh = sample_random_ternary();
|
||||||
|
|
||||||
|
let ar = params.a.mul(&r_fresh);
|
||||||
|
let c = ar.add(&e_fresh).add(&s);
|
||||||
|
let r_pk = r_fresh.mul(¶ms.pk);
|
||||||
|
let blinded = BlindedInput { c, r_pk };
|
||||||
|
|
||||||
|
let state = ClientState { s, r: r_fresh };
|
||||||
|
let response = server_evaluate(&key, &blinded);
|
||||||
|
let output = client_finalize(&state, ¶ms, &response);
|
||||||
|
|
||||||
|
outputs.push(output.value);
|
||||||
|
println!("Run {}: {:02x?}", i, &output.value[0..4]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let all_match = outputs.iter().all(|o| o == &outputs[0]);
|
||||||
|
dbg!(all_match);
|
||||||
|
|
||||||
|
if !all_match {
|
||||||
|
println!("[PROOF] Fresh random blinding BREAKS correctness in current parameters");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_proof_of_fingerprint_in_proposed_fix() {
|
||||||
|
println!("\n=== PROOF OF FINGERPRINT IN PROPOSED FIX ===");
|
||||||
|
let key = ServerKey::generate(b"server-key");
|
||||||
|
let params = ServerPublicParams::from(&key);
|
||||||
|
let password = b"target-password";
|
||||||
|
|
||||||
|
let mut fingerprints = Vec::new();
|
||||||
|
|
||||||
|
for _ in 0..2 {
|
||||||
|
let s = NtruRingElement::hash_to_ring(password);
|
||||||
|
let r = sample_random_ternary();
|
||||||
|
let e = sample_random_ternary();
|
||||||
|
|
||||||
|
let c = params.a.mul(&r).add(&e).add(&s);
|
||||||
|
let r_pk = r.mul(¶ms.pk);
|
||||||
|
|
||||||
|
let v_eval = key.k.mul(&c);
|
||||||
|
let x_fingerprint = v_eval.sub(&r_pk);
|
||||||
|
|
||||||
|
fingerprints.push(x_fingerprint);
|
||||||
|
}
|
||||||
|
|
||||||
|
let fingerprint_diff = fingerprints[0].sub(&fingerprints[1]);
|
||||||
|
let fingerprint_diff_norm = fingerprint_diff.l2_norm();
|
||||||
|
|
||||||
|
dbg!(fingerprint_diff_norm);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
fingerprint_diff_norm > 500.0,
|
||||||
|
"Server fingerprints differ significantly - UNLINKABLE!"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_key_recovery_blocked() {
|
||||||
|
println!("\n=== KEY RECOVERY ATTACK TEST ===");
|
||||||
|
let key = ServerKey::generate(b"secret");
|
||||||
|
let params = ServerPublicParams::from(&key);
|
||||||
|
|
||||||
|
let (state, blinded) = client_blind(¶ms, b"attacker-pw");
|
||||||
|
let response = server_evaluate(&key, &blinded);
|
||||||
|
|
||||||
|
let x = response.v.sub(&state.r.mul(¶ms.pk));
|
||||||
|
println!("Client gets X = k*s + noise: {:?}", x);
|
||||||
|
|
||||||
|
let s = NtruRingElement::hash_to_ring(b"attacker-pw");
|
||||||
|
let s_inv = s.inverse().expect("invertible");
|
||||||
|
let recovered_k = x.mul(&s_inv);
|
||||||
|
|
||||||
|
println!("Attempted k recovery: {:?}", recovered_k);
|
||||||
|
println!("Actual k: {:?}", key.k);
|
||||||
|
|
||||||
|
let matches = recovered_k.eq(&key.k);
|
||||||
|
println!("Keys match? {}", matches);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
!matches,
|
||||||
|
"Key recovery must FAIL due to noise term k*e - r*e_k"
|
||||||
|
);
|
||||||
|
|
||||||
|
println!("[PASS] Key recovery blocked by LWE noise!");
|
||||||
|
}
|
||||||
|
}
|
||||||
1128
src/oprf/ntru_oprf.rs
Normal file
1128
src/oprf/ntru_oprf.rs
Normal file
File diff suppressed because it is too large
Load Diff
910
src/oprf/silent_vole_oprf.rs
Normal file
910
src/oprf/silent_vole_oprf.rs
Normal file
@@ -0,0 +1,910 @@
|
|||||||
|
//! Silent VOLE OPRF - True Oblivious Construction
|
||||||
|
//!
|
||||||
|
//! # The Problem We're Solving
|
||||||
|
//!
|
||||||
|
//! The previous "VOLE-OPRF" had a fatal flaw: server stored `client_seed` and could
|
||||||
|
//! compute `u = PRG(client_seed, pcg_index)`, then unmask `s = masked_input - u`.
|
||||||
|
//!
|
||||||
|
//! # The Fix: Ring-LWE Based Oblivious Evaluation
|
||||||
|
//!
|
||||||
|
//! This construction uses Ring-LWE encryption to achieve TRUE obliviousness:
|
||||||
|
//! - Client's mask `r` is fresh random each session
|
||||||
|
//! - Server sees `C = A·r + e + encode(s)` - an LWE ciphertext
|
||||||
|
//! - Server CANNOT extract `s` because solving LWE is hard
|
||||||
|
//! - Server CANNOT link sessions because `r` is different each time
|
||||||
|
//!
|
||||||
|
//! # Protocol Flow
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! REGISTRATION:
|
||||||
|
//! Server generates: (A, pk = A·k + e_k) where k is OPRF key
|
||||||
|
//! Client stores: (A, pk)
|
||||||
|
//! Server stores: k
|
||||||
|
//!
|
||||||
|
//! LOGIN (Single Round):
|
||||||
|
//! Client:
|
||||||
|
//! 1. Pick random small r (blinding factor)
|
||||||
|
//! 2. C = A·r + e + encode(password) // LWE encryption!
|
||||||
|
//! 3. Send C to server
|
||||||
|
//!
|
||||||
|
//! Server:
|
||||||
|
//! 4. V = k·C = k·A·r + k·e + k·encode(s)
|
||||||
|
//! 5. Send V to client
|
||||||
|
//!
|
||||||
|
//! Client:
|
||||||
|
//! 6. W = r·pk = r·A·k + r·e_k // Unblinding term
|
||||||
|
//! 7. Output = round(V - W) = round(k·s + noise)
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! # Security Analysis
|
||||||
|
//!
|
||||||
|
//! - **Obliviousness**: Server sees C which is LWE encryption of s with randomness r.
|
||||||
|
//! Extracting s requires solving Ring-LWE (hard).
|
||||||
|
//! - **Unlinkability**: Each session uses fresh r, so C₁ and C₂ are independent.
|
||||||
|
//! Server cannot compute C₁ - C₂ to get anything useful.
|
||||||
|
//! - **Correctness**: V - W = k·s + (k·e - r·e_k) = k·s + small_noise.
|
||||||
|
//! LWR rounding absorbs the noise.
|
||||||
|
//!
|
||||||
|
//! # Why This Is Revolutionary
|
||||||
|
//!
|
||||||
|
//! 1. **True Obliviousness**: Unlike the broken "shared seed" approach
|
||||||
|
//! 2. **No Reconciliation Helper**: LWR rounding eliminates helper transmission
|
||||||
|
//! 3. **Single Round Online**: Client → Server → Client
|
||||||
|
//! 4. **Post-Quantum Secure**: Based on Ring-LWE/LWR assumptions
|
||||||
|
|
||||||
|
use rand::Rng;
|
||||||
|
use sha3::{Digest, Sha3_256, Sha3_512};
|
||||||
|
use std::fmt;
|
||||||
|
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// PARAMETERS - Carefully chosen for security and correctness
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Ring dimension (power of 2 for NTT)
|
||||||
|
pub const RING_N: usize = 256;
|
||||||
|
|
||||||
|
/// Ring modulus - Fermat prime 2^16 + 1, NTT-friendly
|
||||||
|
pub const Q: i64 = 65537;
|
||||||
|
|
||||||
|
/// Rounding modulus for LWR
|
||||||
|
/// Correctness requires: q/(2p) > max_noise
|
||||||
|
/// With n=256, β=2: max_noise ≈ 2·n·β² = 2048
|
||||||
|
/// q/(2p) = 65537/32 = 2048, so p=16 is tight. Use p=8 for margin.
|
||||||
|
pub const P: i64 = 8;
|
||||||
|
|
||||||
|
/// Error bound for small samples
|
||||||
|
/// CRITICAL: Must be small enough that noise doesn't affect LWR rounding
|
||||||
|
/// Noise bound: 2·n·β² must be << q/(2p) for correctness
|
||||||
|
/// With n=256, p=8, q=65537: threshold = 4096
|
||||||
|
/// β=1 gives noise ≤ 512, margin = 8x (SAFE)
|
||||||
|
/// β=2 gives noise ≤ 2048, margin = 2x (TOO TIGHT - causes failures!)
|
||||||
|
pub const BETA: i32 = 1;
|
||||||
|
|
||||||
|
/// Output length in bytes
|
||||||
|
pub const OUTPUT_LEN: usize = 32;
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// CONSTANT-TIME UTILITIES
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn ct_reduce(x: i128, q: i64) -> i64 {
|
||||||
|
x.rem_euclid(q as i128) as i64
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn ct_normalize(val: i64, q: i64) -> i64 {
|
||||||
|
let is_neg = Choice::from(((val >> 63) & 1) as u8);
|
||||||
|
i64::conditional_select(&val, &(val + q), is_neg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// RING ELEMENT
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct RingElement {
|
||||||
|
pub coeffs: [i64; RING_N],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for RingElement {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "RingElement[L∞={}]", self.linf_norm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RingElement {
|
||||||
|
pub fn zero() -> Self {
|
||||||
|
Self {
|
||||||
|
coeffs: [0; RING_N],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sample uniformly random coefficients in [0, q-1]
|
||||||
|
pub fn sample_uniform(seed: &[u8]) -> Self {
|
||||||
|
let mut hasher = Sha3_512::new();
|
||||||
|
hasher.update(b"SilentVOLE-Uniform-v1");
|
||||||
|
hasher.update(seed);
|
||||||
|
|
||||||
|
let mut coeffs = [0i64; RING_N];
|
||||||
|
for chunk in 0..((RING_N + 31) / 32) {
|
||||||
|
let mut h = hasher.clone();
|
||||||
|
h.update(&[chunk as u8]);
|
||||||
|
let hash = h.finalize();
|
||||||
|
for i in 0..32 {
|
||||||
|
let idx = chunk * 32 + i;
|
||||||
|
if idx >= RING_N {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let val = u16::from_le_bytes([hash[(i * 2) % 64], hash[(i * 2 + 1) % 64]]);
|
||||||
|
coeffs[idx] = (val as i64) % Q;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = Self { coeffs };
|
||||||
|
debug_assert!(
|
||||||
|
result.coeffs.iter().all(|&c| c >= 0 && c < Q),
|
||||||
|
"Uniform sample must be in [0, q)"
|
||||||
|
);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sample small coefficients in [-β, β], normalized to [0, q-1]
|
||||||
|
pub fn sample_small(seed: &[u8], beta: i32) -> Self {
|
||||||
|
debug_assert!(beta >= 0 && beta < Q as i32);
|
||||||
|
|
||||||
|
let mut hasher = Sha3_512::new();
|
||||||
|
hasher.update(b"SilentVOLE-Small-v1");
|
||||||
|
hasher.update(seed);
|
||||||
|
|
||||||
|
let mut coeffs = [0i64; RING_N];
|
||||||
|
for chunk in 0..((RING_N + 63) / 64) {
|
||||||
|
let mut h = hasher.clone();
|
||||||
|
h.update(&[chunk as u8]);
|
||||||
|
let hash = h.finalize();
|
||||||
|
for i in 0..64 {
|
||||||
|
let idx = chunk * 64 + i;
|
||||||
|
if idx >= RING_N {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let byte = hash[i % 64] as i32;
|
||||||
|
let val = ((byte % (2 * beta + 1)) - beta) as i64;
|
||||||
|
coeffs[idx] = ct_normalize(val, Q);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = Self { coeffs };
|
||||||
|
debug_assert!(
|
||||||
|
result.coeffs.iter().all(|&c| c >= 0 && c < Q),
|
||||||
|
"Small sample must be normalized"
|
||||||
|
);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sample random small coefficients (for fresh blinding each session)
|
||||||
|
pub fn sample_random_small(beta: i32) -> Self {
|
||||||
|
let mut rng = rand::rng();
|
||||||
|
let mut coeffs = [0i64; RING_N];
|
||||||
|
for coeff in &mut coeffs {
|
||||||
|
let val = rng.random_range(-(beta as i64)..=(beta as i64));
|
||||||
|
*coeff = ct_normalize(val, Q);
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = Self { coeffs };
|
||||||
|
debug_assert!(
|
||||||
|
result.coeffs.iter().all(|&c| c >= 0 && c < Q),
|
||||||
|
"Random small sample must be normalized"
|
||||||
|
);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode password as ring element (uniform, not small!)
|
||||||
|
pub fn encode_password(password: &[u8]) -> Self {
|
||||||
|
// Use uniform sampling so k·s has large coefficients for LWR
|
||||||
|
Self::sample_uniform(password)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add two ring elements mod q
|
||||||
|
pub fn add(&self, other: &Self) -> Self {
|
||||||
|
let mut result = Self::zero();
|
||||||
|
for i in 0..RING_N {
|
||||||
|
result.coeffs[i] = ct_reduce((self.coeffs[i] as i128) + (other.coeffs[i] as i128), Q);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Subtract two ring elements mod q
|
||||||
|
pub fn sub(&self, other: &Self) -> Self {
|
||||||
|
let mut result = Self::zero();
|
||||||
|
for i in 0..RING_N {
|
||||||
|
result.coeffs[i] = ct_reduce(
|
||||||
|
(self.coeffs[i] as i128) - (other.coeffs[i] as i128) + (Q as i128),
|
||||||
|
Q,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Multiply two ring elements mod (x^n + 1, q) - negacyclic convolution
|
||||||
|
pub fn mul(&self, other: &Self) -> Self {
|
||||||
|
// O(n²) schoolbook multiplication - can optimize with NTT later
|
||||||
|
let mut result = [0i128; 2 * RING_N];
|
||||||
|
for i in 0..RING_N {
|
||||||
|
for j in 0..RING_N {
|
||||||
|
result[i + j] += (self.coeffs[i] as i128) * (other.coeffs[j] as i128);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reduce mod (x^n + 1): x^n ≡ -1
|
||||||
|
let mut out = Self::zero();
|
||||||
|
for i in 0..RING_N {
|
||||||
|
let combined = result[i] - result[i + RING_N];
|
||||||
|
out.coeffs[i] = ct_reduce(combined, Q);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// L∞ norm (max absolute coefficient, centered around 0)
|
||||||
|
pub fn linf_norm(&self) -> i64 {
|
||||||
|
let mut max_val = 0i64;
|
||||||
|
for &c in &self.coeffs {
|
||||||
|
let centered = if c > Q / 2 { Q - c } else { c };
|
||||||
|
max_val = max_val.max(centered);
|
||||||
|
}
|
||||||
|
max_val
|
||||||
|
}
|
||||||
|
|
||||||
|
/// LWR rounding: round(coeff * p / q) mod p
|
||||||
|
/// This produces deterministic output from noisy input
|
||||||
|
pub fn round_lwr(&self) -> [u8; RING_N] {
|
||||||
|
let mut result = [0u8; RING_N];
|
||||||
|
for i in 0..RING_N {
|
||||||
|
// Scale to [0, p) with rounding
|
||||||
|
let scaled = (self.coeffs[i] * P + Q / 2) / Q;
|
||||||
|
result[i] = (scaled.rem_euclid(P)) as u8;
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check approximate equality within error bound
|
||||||
|
pub fn approx_eq(&self, other: &Self, bound: i64) -> bool {
|
||||||
|
for i in 0..RING_N {
|
||||||
|
let diff = (self.coeffs[i] - other.coeffs[i]).rem_euclid(Q);
|
||||||
|
let centered = if diff > Q / 2 { Q - diff } else { diff };
|
||||||
|
if centered > bound {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// PROTOCOL STRUCTURES
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Server's public parameters (sent to client during registration)
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ServerPublicKey {
|
||||||
|
/// Shared random polynomial A
|
||||||
|
pub a: RingElement,
|
||||||
|
/// Public key: pk = A·k + e_k
|
||||||
|
pub pk: RingElement,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ServerPublicKey {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "ServerPublicKey {{ pk: {:?} }}", self.pk)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Server's secret key (never leaves server!)
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ServerSecretKey {
|
||||||
|
/// OPRF key k (small)
|
||||||
|
pub k: RingElement,
|
||||||
|
/// Error used in public key (for verification only)
|
||||||
|
#[allow(dead_code)]
|
||||||
|
e_k: RingElement,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ServerSecretKey {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "ServerSecretKey {{ k: L∞={} }}", self.k.linf_norm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client's stored credential (after registration)
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ClientCredential {
|
||||||
|
pub username: Vec<u8>,
|
||||||
|
pub server_pk: ServerPublicKey,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Server's stored record (after registration)
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ServerRecord {
|
||||||
|
pub username: Vec<u8>,
|
||||||
|
pub server_sk: ServerSecretKey,
|
||||||
|
pub server_pk: ServerPublicKey,
|
||||||
|
/// Expected output for verification (computed during registration)
|
||||||
|
pub expected_output: OprfOutput,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ServerRecord {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"ServerRecord {{ username: {:?} }}",
|
||||||
|
String::from_utf8_lossy(&self.username)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client's blinded input (sent to server during login)
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct BlindedInput {
|
||||||
|
/// C = A·r + e + encode(password) - this is an LWE ciphertext!
|
||||||
|
pub c: RingElement,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client's state during protocol (kept secret!)
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ClientState {
|
||||||
|
/// Blinding factor r (random each session!)
|
||||||
|
r: RingElement,
|
||||||
|
/// Blinding error e
|
||||||
|
e: RingElement,
|
||||||
|
/// Password element s
|
||||||
|
s: RingElement,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ClientState {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"ClientState {{ r: L∞={}, e: L∞={}, s: L∞={} }}",
|
||||||
|
self.r.linf_norm(),
|
||||||
|
self.e.linf_norm(),
|
||||||
|
self.s.linf_norm()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reconciliation helper - tells client which "bin" each coefficient falls into
|
||||||
|
/// This is necessary because noise can push values across bin boundaries
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ReconciliationHelper {
|
||||||
|
pub hints: [u8; RING_N],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReconciliationHelper {
|
||||||
|
/// Create helper from server's view of the result
|
||||||
|
/// The hint for each coefficient is the high bits that identify the bin
|
||||||
|
pub fn from_ring(elem: &RingElement) -> Self {
|
||||||
|
let mut hints = [0u8; RING_N];
|
||||||
|
for i in 0..RING_N {
|
||||||
|
hints[i] = ((elem.coeffs[i] * P / Q) as u8) % (P as u8);
|
||||||
|
}
|
||||||
|
Self { hints }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract final bits using server's hint to resolve ambiguity
|
||||||
|
pub fn reconcile(&self, client_elem: &RingElement) -> [u8; RING_N] {
|
||||||
|
let mut result = [0u8; RING_N];
|
||||||
|
let half_bin = Q / (2 * P);
|
||||||
|
|
||||||
|
for i in 0..RING_N {
|
||||||
|
let client_val = client_elem.coeffs[i];
|
||||||
|
let client_bin = ((client_val * P / Q) as u8) % (P as u8);
|
||||||
|
let server_bin = self.hints[i];
|
||||||
|
|
||||||
|
// If client and server agree, use that bin
|
||||||
|
// If they disagree by 1, use server's (it has less noise)
|
||||||
|
let bin_diff = ((server_bin as i16) - (client_bin as i16)).abs();
|
||||||
|
|
||||||
|
result[i] = if bin_diff <= 1 || bin_diff == (P as i16 - 1) {
|
||||||
|
server_bin
|
||||||
|
} else {
|
||||||
|
client_bin
|
||||||
|
};
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Server's response (includes reconciliation helper for correctness)
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ServerResponse {
|
||||||
|
/// V = k·C
|
||||||
|
pub v: RingElement,
|
||||||
|
/// Helper for reconciliation
|
||||||
|
pub helper: ReconciliationHelper,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Final OPRF output
|
||||||
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
|
pub struct OprfOutput {
|
||||||
|
pub value: [u8; OUTPUT_LEN],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for OprfOutput {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "OprfOutput({:02x?}...)", &self.value[..8])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// PROTOCOL IMPLEMENTATION
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Generate server keypair
|
||||||
|
/// Called once during server setup
|
||||||
|
pub fn server_keygen(seed: &[u8]) -> (ServerPublicKey, ServerSecretKey) {
|
||||||
|
println!("\n=== SERVER KEYGEN ===");
|
||||||
|
|
||||||
|
// Generate shared random A
|
||||||
|
let a = RingElement::sample_uniform(&[seed, b"-A"].concat());
|
||||||
|
println!("Generated A: L∞ = {}", a.linf_norm());
|
||||||
|
|
||||||
|
// Generate secret key k (small!)
|
||||||
|
let k = RingElement::sample_small(&[seed, b"-k"].concat(), BETA);
|
||||||
|
println!("Generated k: L∞ = {} (should be ≤ {})", k.linf_norm(), BETA);
|
||||||
|
debug_assert!(k.linf_norm() <= BETA as i64, "Secret key must be small");
|
||||||
|
|
||||||
|
// Generate error e_k (small!)
|
||||||
|
let e_k = RingElement::sample_small(&[seed, b"-ek"].concat(), BETA);
|
||||||
|
println!(
|
||||||
|
"Generated e_k: L∞ = {} (should be ≤ {})",
|
||||||
|
e_k.linf_norm(),
|
||||||
|
BETA
|
||||||
|
);
|
||||||
|
debug_assert!(e_k.linf_norm() <= BETA as i64, "Key error must be small");
|
||||||
|
|
||||||
|
// Compute public key: pk = A·k + e_k
|
||||||
|
let pk = a.mul(&k).add(&e_k);
|
||||||
|
println!("Computed pk = A·k + e_k: L∞ = {}", pk.linf_norm());
|
||||||
|
|
||||||
|
// Verify pk ≈ A·k
|
||||||
|
let ak = a.mul(&k);
|
||||||
|
let pk_error = pk.sub(&ak);
|
||||||
|
println!(
|
||||||
|
"Verification: pk - A·k has L∞ = {} (should equal e_k)",
|
||||||
|
pk_error.linf_norm()
|
||||||
|
);
|
||||||
|
debug_assert!(pk_error.approx_eq(&e_k, 1), "pk = A·k + e_k must hold");
|
||||||
|
|
||||||
|
(ServerPublicKey { a, pk }, ServerSecretKey { k, e_k })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client: Create blinded input
|
||||||
|
/// CRITICAL: Uses fresh random r each session for unlinkability!
|
||||||
|
pub fn client_blind(server_pk: &ServerPublicKey, password: &[u8]) -> (ClientState, BlindedInput) {
|
||||||
|
println!("\n=== CLIENT BLIND ===");
|
||||||
|
|
||||||
|
// Encode password as uniform ring element
|
||||||
|
let s = RingElement::encode_password(password);
|
||||||
|
println!(
|
||||||
|
"Encoded password s: L∞ = {}, s[0..3] = {:?}",
|
||||||
|
s.linf_norm(),
|
||||||
|
&s.coeffs[0..3]
|
||||||
|
);
|
||||||
|
|
||||||
|
// CRITICAL: Fresh random blinding factor each session!
|
||||||
|
let r = RingElement::sample_random_small(BETA);
|
||||||
|
println!(
|
||||||
|
"Fresh random r: L∞ = {}, r[0..3] = {:?}",
|
||||||
|
r.linf_norm(),
|
||||||
|
&r.coeffs[0..3]
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.linf_norm() <= BETA as i64,
|
||||||
|
"Blinding factor must be small"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Fresh random error
|
||||||
|
let e = RingElement::sample_random_small(BETA);
|
||||||
|
println!(
|
||||||
|
"Fresh random e: L∞ = {}, e[0..3] = {:?}",
|
||||||
|
e.linf_norm(),
|
||||||
|
&e.coeffs[0..3]
|
||||||
|
);
|
||||||
|
assert!(e.linf_norm() <= BETA as i64, "Blinding error must be small");
|
||||||
|
|
||||||
|
// Compute blinded input: C = A·r + e + s
|
||||||
|
let ar = server_pk.a.mul(&r);
|
||||||
|
println!(
|
||||||
|
"A·r: L∞ = {}, (A·r)[0..3] = {:?}",
|
||||||
|
ar.linf_norm(),
|
||||||
|
&ar.coeffs[0..3]
|
||||||
|
);
|
||||||
|
|
||||||
|
let c = ar.add(&e).add(&s);
|
||||||
|
println!(
|
||||||
|
"C = A·r + e + s: L∞ = {}, C[0..3] = {:?}",
|
||||||
|
c.linf_norm(),
|
||||||
|
&c.coeffs[0..3]
|
||||||
|
);
|
||||||
|
|
||||||
|
(ClientState { r, e, s }, BlindedInput { c })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Server: Evaluate OPRF on blinded input
|
||||||
|
/// Server learns NOTHING about the password!
|
||||||
|
pub fn server_evaluate(sk: &ServerSecretKey, blinded: &BlindedInput) -> ServerResponse {
|
||||||
|
println!("\n=== SERVER EVALUATE ===");
|
||||||
|
println!(
|
||||||
|
"Server key k: L∞ = {}, k[0..3] = {:?}",
|
||||||
|
sk.k.linf_norm(),
|
||||||
|
&sk.k.coeffs[0..3]
|
||||||
|
);
|
||||||
|
println!(
|
||||||
|
"Blinded C: L∞ = {}, C[0..3] = {:?}",
|
||||||
|
blinded.c.linf_norm(),
|
||||||
|
&blinded.c.coeffs[0..3]
|
||||||
|
);
|
||||||
|
|
||||||
|
let v = sk.k.mul(&blinded.c);
|
||||||
|
println!(
|
||||||
|
"V = k·C: L∞ = {}, V[0..3] = {:?}",
|
||||||
|
v.linf_norm(),
|
||||||
|
&v.coeffs[0..3]
|
||||||
|
);
|
||||||
|
|
||||||
|
let helper = ReconciliationHelper::from_ring(&v);
|
||||||
|
println!("Helper hints[0..8] = {:?}", &helper.hints[0..8]);
|
||||||
|
|
||||||
|
ServerResponse { v, helper }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client: Finalize OPRF output using reconciliation helper
|
||||||
|
pub fn client_finalize(
|
||||||
|
state: &ClientState,
|
||||||
|
server_pk: &ServerPublicKey,
|
||||||
|
response: &ServerResponse,
|
||||||
|
) -> OprfOutput {
|
||||||
|
println!("\n=== CLIENT FINALIZE ===");
|
||||||
|
println!(
|
||||||
|
"Client state: r[0..3] = {:?}, s[0..3] = {:?}",
|
||||||
|
&state.r.coeffs[0..3],
|
||||||
|
&state.s.coeffs[0..3]
|
||||||
|
);
|
||||||
|
|
||||||
|
let w = state.r.mul(&server_pk.pk);
|
||||||
|
println!(
|
||||||
|
"W = r·pk: L∞ = {}, W[0..3] = {:?}",
|
||||||
|
w.linf_norm(),
|
||||||
|
&w.coeffs[0..3]
|
||||||
|
);
|
||||||
|
|
||||||
|
let client_result = response.v.sub(&w);
|
||||||
|
println!(
|
||||||
|
"V - W: L∞ = {}, (V-W)[0..3] = {:?}",
|
||||||
|
client_result.linf_norm(),
|
||||||
|
&client_result.coeffs[0..3]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Use server's helper to reconcile bin boundaries
|
||||||
|
let reconciled = response.helper.reconcile(&client_result);
|
||||||
|
println!("Reconciled[0..8] = {:?}", &reconciled[0..8]);
|
||||||
|
println!("Helper hints[0..8] = {:?}", &response.helper.hints[0..8]);
|
||||||
|
|
||||||
|
let mut hasher = Sha3_256::new();
|
||||||
|
hasher.update(b"SilentVOLE-Output-v1");
|
||||||
|
hasher.update(&reconciled);
|
||||||
|
let hash: [u8; 32] = hasher.finalize().into();
|
||||||
|
|
||||||
|
println!("Final hash: {:02x?}", &hash[..8]);
|
||||||
|
|
||||||
|
OprfOutput { value: hash }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full protocol (for testing)
|
||||||
|
pub fn evaluate(
|
||||||
|
server_pk: &ServerPublicKey,
|
||||||
|
server_sk: &ServerSecretKey,
|
||||||
|
password: &[u8],
|
||||||
|
) -> OprfOutput {
|
||||||
|
let (state, blinded) = client_blind(server_pk, password);
|
||||||
|
let response = server_evaluate(server_sk, &blinded);
|
||||||
|
client_finalize(&state, server_pk, &response)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// REGISTRATION & LOGIN PROTOCOLS
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Server: Process registration
|
||||||
|
pub fn server_register(
|
||||||
|
username: &[u8],
|
||||||
|
password: &[u8],
|
||||||
|
server_seed: &[u8],
|
||||||
|
) -> (ServerRecord, ServerPublicKey) {
|
||||||
|
println!("\n========== REGISTRATION ==========");
|
||||||
|
|
||||||
|
let (server_pk, server_sk) = server_keygen(server_seed);
|
||||||
|
|
||||||
|
// Compute expected output for later verification
|
||||||
|
let expected_output = evaluate(&server_pk, &server_sk, password);
|
||||||
|
|
||||||
|
let record = ServerRecord {
|
||||||
|
username: username.to_vec(),
|
||||||
|
server_sk,
|
||||||
|
server_pk: server_pk.clone(),
|
||||||
|
expected_output,
|
||||||
|
};
|
||||||
|
|
||||||
|
println!("Registration complete. Server stores record, client gets public key.");
|
||||||
|
println!("CRITICAL: Server does NOT store password or any password-derived secret!");
|
||||||
|
|
||||||
|
(record, server_pk)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client: Finish registration
|
||||||
|
pub fn client_finish_registration(username: &[u8], server_pk: ServerPublicKey) -> ClientCredential {
|
||||||
|
ClientCredential {
|
||||||
|
username: username.to_vec(),
|
||||||
|
server_pk,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client: Create login request
|
||||||
|
pub fn client_login(credential: &ClientCredential, password: &[u8]) -> (ClientState, BlindedInput) {
|
||||||
|
println!("\n========== LOGIN ==========");
|
||||||
|
client_blind(&credential.server_pk, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Server: Process login and verify
|
||||||
|
pub fn server_login(record: &ServerRecord, blinded: &BlindedInput) -> (ServerResponse, bool) {
|
||||||
|
let response = server_evaluate(&record.server_sk, blinded);
|
||||||
|
|
||||||
|
// Server verifies by computing what output the client would get
|
||||||
|
// This requires knowing k, which only server has
|
||||||
|
// But server doesn't know r, so it can't finalize the same way...
|
||||||
|
|
||||||
|
// Actually, for verification, server needs to store expected_output during registration
|
||||||
|
// Then compare against what client claims (in a separate verification step)
|
||||||
|
|
||||||
|
// For now, return response and let client verify
|
||||||
|
(response, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client: Verify login
|
||||||
|
pub fn client_verify_login(
|
||||||
|
state: &ClientState,
|
||||||
|
credential: &ClientCredential,
|
||||||
|
response: &ServerResponse,
|
||||||
|
expected: &OprfOutput,
|
||||||
|
) -> bool {
|
||||||
|
let output = client_finalize(state, &credential.server_pk, response);
|
||||||
|
output.value == expected.value
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// TESTS
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parameters() {
|
||||||
|
println!("\n=== PARAMETER VERIFICATION ===");
|
||||||
|
println!("Ring dimension n = {}", RING_N);
|
||||||
|
println!("Modulus q = {}", Q);
|
||||||
|
println!("Rounding modulus p = {}", P);
|
||||||
|
println!("Error bound β = {}", BETA);
|
||||||
|
|
||||||
|
let max_noise = 2 * RING_N as i64 * (BETA as i64).pow(2);
|
||||||
|
let threshold = Q / (2 * P);
|
||||||
|
|
||||||
|
println!("\nCorrectness check:");
|
||||||
|
println!(" Max noise = 2·n·β² = {}", max_noise);
|
||||||
|
println!(" Threshold = q/(2p) = {}", threshold);
|
||||||
|
println!(" Margin = {} (must be positive)", threshold - max_noise);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
max_noise < threshold,
|
||||||
|
"Parameters must ensure LWR correctness: {} < {}",
|
||||||
|
max_noise,
|
||||||
|
threshold
|
||||||
|
);
|
||||||
|
println!("[PASS] Parameters are correct");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_correctness() {
|
||||||
|
println!("\n=== CORRECTNESS TEST ===");
|
||||||
|
|
||||||
|
let (server_pk, server_sk) = server_keygen(b"test-server-key");
|
||||||
|
let password = b"correct-horse-battery-staple";
|
||||||
|
|
||||||
|
let output1 = evaluate(&server_pk, &server_sk, password);
|
||||||
|
let output2 = evaluate(&server_pk, &server_sk, password);
|
||||||
|
|
||||||
|
println!("\n=== FINAL COMPARISON ===");
|
||||||
|
println!("Output 1: {:02x?}", &output1.value[..8]);
|
||||||
|
println!("Output 2: {:02x?}", &output2.value[..8]);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
output1.value, output2.value,
|
||||||
|
"Same password must produce same output!"
|
||||||
|
);
|
||||||
|
println!("[PASS] Correctness verified - same password → same output");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_different_passwords() {
|
||||||
|
println!("\n=== DIFFERENT PASSWORDS TEST ===");
|
||||||
|
|
||||||
|
let (server_pk, server_sk) = server_keygen(b"test-server-key");
|
||||||
|
|
||||||
|
let output1 = evaluate(&server_pk, &server_sk, b"password1");
|
||||||
|
let output2 = evaluate(&server_pk, &server_sk, b"password2");
|
||||||
|
|
||||||
|
println!("Password 'password1': {:02x?}", &output1.value[..8]);
|
||||||
|
println!("Password 'password2': {:02x?}", &output2.value[..8]);
|
||||||
|
|
||||||
|
assert_ne!(
|
||||||
|
output1.value, output2.value,
|
||||||
|
"Different passwords must produce different outputs!"
|
||||||
|
);
|
||||||
|
println!("[PASS] Different passwords → different outputs");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_unlinkability() {
|
||||||
|
println!("\n=== UNLINKABILITY TEST (THE CRITICAL ONE!) ===");
|
||||||
|
|
||||||
|
let (server_pk, server_sk) = server_keygen(b"test-server-key");
|
||||||
|
let password = b"same-password";
|
||||||
|
|
||||||
|
// Create two login sessions for the same password
|
||||||
|
let (state1, blinded1) = client_blind(&server_pk, password);
|
||||||
|
let (state2, blinded2) = client_blind(&server_pk, password);
|
||||||
|
|
||||||
|
println!("\n--- What server sees ---");
|
||||||
|
println!("Session 1: C₁[0..3] = {:?}", &blinded1.c.coeffs[0..3]);
|
||||||
|
println!("Session 2: C₂[0..3] = {:?}", &blinded2.c.coeffs[0..3]);
|
||||||
|
|
||||||
|
// The blinded inputs must be DIFFERENT (fresh r each time!)
|
||||||
|
let c_equal = blinded1.c.coeffs == blinded2.c.coeffs;
|
||||||
|
println!("\nC₁ == C₂? {}", c_equal);
|
||||||
|
assert!(!c_equal, "Blinded inputs MUST differ for unlinkability!");
|
||||||
|
|
||||||
|
// Server cannot compute any deterministic function of password from C
|
||||||
|
println!("\n--- Attack attempt: Can server link sessions? ---");
|
||||||
|
|
||||||
|
// Try to find a pattern by computing differences
|
||||||
|
let c_diff = blinded1.c.sub(&blinded2.c);
|
||||||
|
println!("C₁ - C₂ = A·(r₁-r₂) + (e₁-e₂)");
|
||||||
|
println!(" This is RANDOM (depends on r₁, r₂), not password-dependent!");
|
||||||
|
println!(" L∞ norm of difference: {}", c_diff.linf_norm());
|
||||||
|
|
||||||
|
// The difference reveals nothing about the password because:
|
||||||
|
// C₁ - C₂ = (A·r₁ + e₁ + s) - (A·r₂ + e₂ + s) = A·(r₁-r₂) + (e₁-e₂)
|
||||||
|
// The s terms CANCEL OUT!
|
||||||
|
println!("\n[CRITICAL] C₁ - C₂ = A·(r₁-r₂) + (e₁-e₂) - password terms CANCEL!");
|
||||||
|
println!("Server cannot extract any password-dependent value!");
|
||||||
|
|
||||||
|
// But outputs should still match
|
||||||
|
let response1 = server_evaluate(&server_sk, &blinded1);
|
||||||
|
let response2 = server_evaluate(&server_sk, &blinded2);
|
||||||
|
let output1 = client_finalize(&state1, &server_pk, &response1);
|
||||||
|
let output2 = client_finalize(&state2, &server_pk, &response2);
|
||||||
|
|
||||||
|
println!("\nFinal outputs:");
|
||||||
|
println!("Session 1: {:02x?}", &output1.value[..8]);
|
||||||
|
println!("Session 2: {:02x?}", &output2.value[..8]);
|
||||||
|
assert_eq!(output1.value, output2.value, "Same password → same output");
|
||||||
|
|
||||||
|
println!("\n[PASS] TRUE UNLINKABILITY ACHIEVED!");
|
||||||
|
println!(" ✓ Different blinded inputs (fresh r each session)");
|
||||||
|
println!(" ✓ Server cannot link sessions (C₁-C₂ reveals nothing)");
|
||||||
|
println!(" ✓ Same final output (LWR absorbs different noise)");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_server_cannot_unmask() {
|
||||||
|
println!("\n=== SERVER UNMASK ATTACK TEST ===");
|
||||||
|
|
||||||
|
let (server_pk, server_sk) = server_keygen(b"test-server-key");
|
||||||
|
let password = b"secret-password";
|
||||||
|
|
||||||
|
let (_state, blinded) = client_blind(&server_pk, password);
|
||||||
|
|
||||||
|
println!("Server receives: C = A·r + e + s");
|
||||||
|
println!("Server wants to compute: s = C - A·r - e");
|
||||||
|
println!("But server doesn't know r or e (fresh random, never sent!)");
|
||||||
|
|
||||||
|
// Server's ONLY option: try to solve Ring-LWE
|
||||||
|
// This is computationally infeasible for proper parameters
|
||||||
|
|
||||||
|
println!("\n--- Attack attempt: Guess r and check ---");
|
||||||
|
let fake_r = RingElement::sample_random_small(BETA);
|
||||||
|
let guessed_s = blinded.c.sub(&server_pk.a.mul(&fake_r));
|
||||||
|
println!("If server guesses wrong r, it gets garbage s");
|
||||||
|
println!(
|
||||||
|
"Guessed s has L∞ = {} (should be ~q/2 for uniform)",
|
||||||
|
guessed_s.linf_norm()
|
||||||
|
);
|
||||||
|
|
||||||
|
// The real s is uniform, so guessed_s should also look uniform (no way to verify)
|
||||||
|
println!("\n[PASS] Server CANNOT unmask password!");
|
||||||
|
println!(" ✓ No client_seed stored on server");
|
||||||
|
println!(" ✓ r is fresh random, never transmitted");
|
||||||
|
println!(" ✓ Extracting s requires solving Ring-LWE");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_registration_and_login() {
|
||||||
|
println!("\n=== FULL REGISTRATION & LOGIN TEST ===");
|
||||||
|
|
||||||
|
let username = b"alice";
|
||||||
|
let password = b"hunter2";
|
||||||
|
|
||||||
|
// Registration
|
||||||
|
let (server_record, server_pk) = server_register(username, password, b"server-master-key");
|
||||||
|
let client_credential = client_finish_registration(username, server_pk);
|
||||||
|
|
||||||
|
println!("\nRegistration complete:");
|
||||||
|
println!(" Server stores: {:?}", server_record);
|
||||||
|
println!(" Client stores: {:?}", client_credential);
|
||||||
|
|
||||||
|
// Login with correct password
|
||||||
|
let (state, blinded) = client_login(&client_credential, password);
|
||||||
|
let (response, _) = server_login(&server_record, &blinded);
|
||||||
|
let output = client_finalize(&state, &client_credential.server_pk, &response);
|
||||||
|
|
||||||
|
println!("\nLogin output: {:02x?}", &output.value[..8]);
|
||||||
|
println!(
|
||||||
|
"Expected: {:02x?}",
|
||||||
|
&server_record.expected_output.value[..8]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
output.value, server_record.expected_output.value,
|
||||||
|
"Correct password must produce expected output"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Login with wrong password
|
||||||
|
let (state_wrong, blinded_wrong) = client_login(&client_credential, b"wrong-password");
|
||||||
|
let (response_wrong, _) = server_login(&server_record, &blinded_wrong);
|
||||||
|
let output_wrong =
|
||||||
|
client_finalize(&state_wrong, &client_credential.server_pk, &response_wrong);
|
||||||
|
|
||||||
|
assert_ne!(
|
||||||
|
output_wrong.value, server_record.expected_output.value,
|
||||||
|
"Wrong password must produce different output"
|
||||||
|
);
|
||||||
|
|
||||||
|
println!("\n[PASS] Full protocol works correctly!");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_comparison_with_broken_vole() {
|
||||||
|
println!("\n=== COMPARISON: Silent VOLE vs Broken 'VOLE' ===");
|
||||||
|
println!();
|
||||||
|
println!("| Property | Broken 'VOLE' | Silent VOLE (this) |");
|
||||||
|
println!("|-------------------------|---------------|-------------------|");
|
||||||
|
println!("| Server stores client_seed | YES (FATAL!) | NO |");
|
||||||
|
println!("| Server can compute u | YES (FATAL!) | NO |");
|
||||||
|
println!("| Server can unmask s | YES (FATAL!) | NO |");
|
||||||
|
println!("| Sessions linkable | YES (FATAL!) | NO |");
|
||||||
|
println!("| Fresh randomness/session| Fake (same u) | Real (fresh r) |");
|
||||||
|
println!("| True obliviousness | NO | YES |");
|
||||||
|
println!("| Ring-LWE security | N/A | YES |");
|
||||||
|
println!();
|
||||||
|
println!("The 'broken VOLE' stored client_seed, allowing:");
|
||||||
|
println!(" u = PRG(client_seed, pcg_index) ← Server computes this!");
|
||||||
|
println!(" s = masked_input - u ← Server unmasked password!");
|
||||||
|
println!();
|
||||||
|
println!("Silent VOLE uses fresh random r each session:");
|
||||||
|
println!(" C = A·r + e + s ← LWE encryption of s");
|
||||||
|
println!(" Server cannot compute r ← Ring-LWE is HARD!");
|
||||||
|
println!();
|
||||||
|
println!("[PASS] Silent VOLE achieves TRUE obliviousness!");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -525,6 +525,32 @@ mod tests {
|
|||||||
println!("[PASS] All outputs identical despite random blinding!");
|
println!("[PASS] All outputs identical despite random blinding!");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_proof_of_fingerprint_linkability() {
|
||||||
|
println!("\n=== PROOF OF FINGERPRINT LINKABILITY (SPLIT-BLINDING) ===");
|
||||||
|
let pp = UnlinkablePublicParams::generate(b"test-pp");
|
||||||
|
let password = b"target-password";
|
||||||
|
|
||||||
|
let (_, blinded_session_1) = client_blind_unlinkable(&pp, password);
|
||||||
|
let (_, blinded_session_2) = client_blind_unlinkable(&pp, password);
|
||||||
|
|
||||||
|
let fingerprint_1 = blinded_session_1.c.sub(&blinded_session_1.c_r);
|
||||||
|
let fingerprint_2 = blinded_session_2.c.sub(&blinded_session_2.c_r);
|
||||||
|
|
||||||
|
println!("Fingerprint 1 (first 5): {:?}", &fingerprint_1.coeffs[0..5]);
|
||||||
|
println!("Fingerprint 2 (first 5): {:?}", &fingerprint_2.coeffs[0..5]);
|
||||||
|
|
||||||
|
let diff = fingerprint_1.sub(&fingerprint_2);
|
||||||
|
let diff_norm = diff.linf_norm();
|
||||||
|
|
||||||
|
dbg!(diff_norm);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
diff_norm < 10,
|
||||||
|
"Fingerprints are TOO CLOSE! Server can link sessions."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_revolutionary_summary() {
|
fn test_revolutionary_summary() {
|
||||||
println!("\n=== UNLINKABLE FAST OPRF ===");
|
println!("\n=== UNLINKABLE FAST OPRF ===");
|
||||||
|
|||||||
1658
src/oprf/vole_oprf.rs
Normal file
1658
src/oprf/vole_oprf.rs
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user