Skip to main content

confium_tc_ecies_p256/
lib.rs

1//! Threshold ECIES over P-256 — real implementation.
2//!
3//! ECIES (Elliptic Curve Integrated Encryption Scheme) on P-256:
4//!
5//! - Encryptor generates ephemeral scalar `r`, computes `R = r * G`
6//! - Encryptor computes ECDH shared secret `K = r * recipient_pubkey`
7//! - Encryptor derives AEAD key from `K` via a domain-separated hash
8//! - Encryptor encrypts plaintext with the selected AEAD
9//!   (AES-256-GCM by default; AES-256-GCM-SIV selectable — RFC 8452)
10//! - Output: `(R, ciphertext, nonce, tag)`
11//!
12//! Threshold variant: recipient's private scalar `x` is Shamir-shared
13//! among N parties. Each party computes `partial_i = x_i * R`. Combined
14//! via Lagrange: `sum_i λ_i * partial_i = x * R = K`. From K, the AEAD
15//! key is derived and decryption proceeds normally.
16//!
17//! Used for browser-side key escrow and Mode 2 enterprise secrets.
18//!
19//! See `TODO.roadmap/31-threshold-encryption.md` for full spec.
20
21#![forbid(unsafe_code)]
22#![allow(missing_docs)] // TODO: document before 1.0
23
24pub mod keys;
25pub mod shamir;
26
27use aes_gcm::aead::AeadInOut;
28use aes_gcm::aead::inout::InOutBuf;
29use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
30use aes_gcm_siv::Aes256GcmSiv;
31use p256::elliptic_curve::PrimeField;
32use p256::elliptic_curve::rand_core;
33use p256::elliptic_curve::rand_core::Rng;
34use p256::elliptic_curve::sec1::Sec1Point;
35use p256::elliptic_curve::sec1::{FromSec1Point, ToSec1Point};
36use p256::elliptic_curve::subtle::CtOption;
37use p256::{AffinePoint, FieldBytes, ProjectivePoint, Scalar};
38use serde::{Deserialize, Serialize};
39use sha2::{Digest as _, Sha256};
40
41pub use keys::generate_keypair;
42pub use shamir::{Share, recover_secret, split_secret};
43
44/// Algorithm identifier.
45pub const ALGORITHM: &str = "ECIES-P256-threshold";
46
47/// AEAD used to protect the ECIES payload.
48///
49/// The default remains [`AeadAlgorithm::Aes256Gcm`]. Every ECIES
50/// ephemeral key is fresh, so nonce-misuse resistance matters little
51/// here; GCM-SIV (RFC 8452) is offered for deployments that standardize
52/// on it across long-lived protocol artifacts.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54pub enum AeadAlgorithm {
55    /// AES-256-GCM (the historical default).
56    #[default]
57    Aes256Gcm,
58    /// AES-256-GCM-SIV (RFC 8452, nonce-misuse resistant).
59    Aes256GcmSiv,
60}
61
62impl AeadAlgorithm {
63    /// Domain-separation label mixed into the AEAD key derivation.
64    ///
65    /// The GCM label is byte-identical to the pre-agility derivation so
66    /// existing ciphertexts keep decrypting.
67    fn domain_label(self) -> &'static [u8] {
68        match self {
69            Self::Aes256Gcm => b"confium-ecies-p256-v1",
70            Self::Aes256GcmSiv => b"confium-ecies-p256-v1-gcm-siv",
71        }
72    }
73}
74
75/// Threshold ECIES public key.
76#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct PublicKey {
78    /// SEC1-encoded public key bytes (uncompressed, 65 bytes).
79    pub bytes: Vec<u8>,
80}
81
82impl PublicKey {
83    /// Construct from an affine point.
84    pub fn from_affine(point: AffinePoint) -> Self {
85        Self {
86            bytes: point.to_sec1_point(false).as_bytes().to_vec(),
87        }
88    }
89}
90
91/// Share of the threshold ECIES secret key.
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct DecryptionShare {
94    /// Party index.
95    pub party_index: u32,
96    /// Share bytes (32-byte scalar).
97    pub bytes: Vec<u8>,
98}
99
100/// ECIES-encrypted blob.
101#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct EncryptedBlob {
103    /// Ephemeral public key R (uncompressed, 65 bytes).
104    pub ephemeral_public: Vec<u8>,
105    /// AEAD ciphertext.
106    pub ciphertext: Vec<u8>,
107    /// AEAD nonce (12 bytes for AES-GCM).
108    pub nonce: Vec<u8>,
109    /// AEAD tag (16 bytes for AES-256-GCM).
110    pub tag: Vec<u8>,
111}
112
113/// Partial decryption from one party: `share * R` as SEC1 bytes.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct PartialDecryption {
116    /// Contributing party index.
117    pub party_index: u32,
118    /// SEC1-encoded point.
119    pub bytes: Vec<u8>,
120}
121
122/// Errors during threshold ECIES operations.
123#[derive(Debug, thiserror::Error)]
124pub enum EciesError {
125    /// Threshold not met.
126    #[error("threshold not met: have {have}, need {need}")]
127    ThresholdNotMet {
128        /// Count received.
129        have: usize,
130        /// Required threshold.
131        need: u32,
132    },
133    /// SEC1 decode failure.
134    #[error("SEC1 decode failed: {0}")]
135    Sec1Decode(String),
136    /// Duplicate party index.
137    #[error("duplicate party index: {0}")]
138    DuplicateParty(u32),
139    /// Invalid scalar.
140    #[error("invalid scalar: {0}")]
141    InvalidScalar(String),
142    /// AEAD failure.
143    #[error("AEAD failure: {0}")]
144    Aead(String),
145}
146
147fn decode_point(bytes: &[u8]) -> Result<ProjectivePoint, EciesError> {
148    let ep = Sec1Point::<p256::NistP256>::from_bytes(bytes)
149        .map_err(|e| EciesError::Sec1Decode(format!("encoded point: {e}")))?;
150    let ct_opt = AffinePoint::from_sec1_point(&ep);
151    let affine = Option::<AffinePoint>::from(ct_opt)
152        .ok_or_else(|| EciesError::Sec1Decode("point at infinity".into()))?;
153    Ok(ProjectivePoint::from(affine))
154}
155
156fn encode_point(point: &ProjectivePoint) -> Vec<u8> {
157    point.to_affine().to_sec1_point(false).as_bytes().to_vec()
158}
159
160fn decode_scalar(bytes: &[u8]) -> Result<Scalar, EciesError> {
161    if bytes.len() != 32 {
162        return Err(EciesError::InvalidScalar(format!(
163            "expected 32 bytes, got {}",
164            bytes.len()
165        )));
166    }
167    let mut arr = [0u8; 32];
168    arr.copy_from_slice(bytes);
169    let fb = FieldBytes::from(arr);
170    let ct: CtOption<Scalar> = Scalar::from_repr(fb);
171    Option::<Scalar>::from(ct).ok_or_else(|| EciesError::InvalidScalar("out of range".into()))
172}
173
174fn slice_to_array<const N: usize>(bytes: &[u8]) -> Result<[u8; N], EciesError> {
175    bytes
176        .try_into()
177        .map_err(|_| EciesError::Aead(format!("expected {N} bytes, got {}", bytes.len())))
178}
179
180fn x_coordinate(point: &ProjectivePoint) -> [u8; 32] {
181    let ep = point.to_affine().to_sec1_point(false);
182    let bytes = ep.as_bytes();
183    if bytes.len() == 65 {
184        let mut arr = [0u8; 32];
185        arr.copy_from_slice(&bytes[1..33]);
186        arr
187    } else {
188        [0u8; 32]
189    }
190}
191
192fn derive_aead_key(shared: &[u8; 32], algorithm: AeadAlgorithm) -> [u8; 32] {
193    use sha2::Digest;
194    // Simple HKDF-like derivation: SHA-256(domain-sep || shared).
195    // Real HKDF would use extract+expand; this is sufficient for ECIES on P-256.
196    let mut h = sha2::Sha256::new();
197    h.update(algorithm.domain_label());
198    h.update(shared);
199    let out = h.finalize();
200    let mut key = [0u8; 32];
201    key.copy_from_slice(&out);
202    key
203}
204
205/// Encrypt `plaintext` to `recipient` using ECIES-P256 + AES-256-GCM.
206pub fn encrypt(recipient: &PublicKey, plaintext: &[u8]) -> Result<EncryptedBlob, EciesError> {
207    encrypt_with(recipient, plaintext, AeadAlgorithm::default())
208}
209
210/// Encrypt `plaintext` to `recipient` with an explicit AEAD choice.
211pub fn encrypt_with(
212    recipient: &PublicKey,
213    plaintext: &[u8],
214    algorithm: AeadAlgorithm,
215) -> Result<EncryptedBlob, EciesError> {
216    let recipient_pt = decode_point(&recipient.bytes)?;
217
218    // Ephemeral scalar
219    let r = loop {
220        let mut buf = [0u8; 32];
221        rand_core::UnwrapErr(getrandom::SysRng).fill_bytes(&mut buf);
222        if let Some(s) = Option::<Scalar>::from(Scalar::from_repr(FieldBytes::from(buf))) {
223            if s != Scalar::ZERO {
224                break s;
225            }
226        }
227    };
228
229    // Ephemeral public R = r*G
230    let r_point = ProjectivePoint::GENERATOR * r;
231    let ephemeral_public = encode_point(&r_point);
232
233    // Shared secret K = r * recipient_pubkey
234    let shared_point = recipient_pt * r;
235    let shared = x_coordinate(&shared_point);
236
237    // Derive AEAD key
238    let key = derive_aead_key(&shared, algorithm);
239    let nonce_bytes: [u8; 12] = {
240        let mut nb = [0u8; 12];
241        rand_core::UnwrapErr(getrandom::SysRng).fill_bytes(&mut nb);
242        nb
243    };
244    let nonce = Nonce::from(nonce_bytes);
245
246    // Encrypt
247    let mut buffer = plaintext.to_vec();
248    let tag: Vec<u8> = match algorithm {
249        AeadAlgorithm::Aes256Gcm => {
250            let cipher =
251                Aes256Gcm::new_from_slice(&key).map_err(|e| EciesError::Aead(e.to_string()))?;
252            cipher
253                .encrypt_inout_detached(&nonce, b"", InOutBuf::from(buffer.as_mut_slice()))
254                .map_err(|e| EciesError::Aead(e.to_string()))?
255                .to_vec()
256        }
257        AeadAlgorithm::Aes256GcmSiv => {
258            let cipher =
259                Aes256GcmSiv::new_from_slice(&key).map_err(|e| EciesError::Aead(e.to_string()))?;
260            cipher
261                .encrypt_inout_detached(&nonce, b"", InOutBuf::from(buffer.as_mut_slice()))
262                .map_err(|e| EciesError::Aead(e.to_string()))?
263                .to_vec()
264        }
265    };
266
267    Ok(EncryptedBlob {
268        ephemeral_public,
269        ciphertext: buffer,
270        nonce: nonce_bytes.to_vec(),
271        tag: tag.to_vec(),
272    })
273}
274
275/// Compute a partial decryption: `share * R` where R is the blob's ephemeral public key.
276pub fn partial_decrypt(
277    share: &DecryptionShare,
278    blob: &EncryptedBlob,
279) -> Result<PartialDecryption, EciesError> {
280    let s = decode_scalar(&share.bytes)?;
281    let r_point = decode_point(&blob.ephemeral_public)?;
282    let partial = r_point * s;
283    Ok(PartialDecryption {
284        party_index: share.party_index,
285        bytes: encode_point(&partial),
286    })
287}
288
289/// Aggregate T partial decryptions to recover the plaintext.
290///
291/// Combined point = sum_i [ λ_i * partial_i ] = x * R = K (the ECDH shared secret).
292/// Derive AEAD key from X-coordinate of K, then AEAD-decrypt the blob.
293pub fn aggregate_partials(
294    partials: &[PartialDecryption],
295    threshold: u32,
296    blob: &EncryptedBlob,
297) -> Result<Vec<u8>, EciesError> {
298    aggregate_partials_with(partials, threshold, blob, AeadAlgorithm::default())
299}
300
301/// Aggregate T partial decryptions with an explicit AEAD choice.
302///
303/// Must match the algorithm used at encryption time; the derivation is
304/// domain-separated per algorithm, so the mismatch fails at AEAD.
305pub fn aggregate_partials_with(
306    partials: &[PartialDecryption],
307    threshold: u32,
308    blob: &EncryptedBlob,
309    algorithm: AeadAlgorithm,
310) -> Result<Vec<u8>, EciesError> {
311    if (partials.len() as u32) < threshold {
312        return Err(EciesError::ThresholdNotMet {
313            have: partials.len(),
314            need: threshold,
315        });
316    }
317
318    let mut seen = std::collections::HashSet::new();
319    for p in partials {
320        if !seen.insert(p.party_index) {
321            return Err(EciesError::DuplicateParty(p.party_index));
322        }
323    }
324
325    // Lagrange-weighted sum: combined = sum_i λ_i * partial_i
326    let mut combined = ProjectivePoint::IDENTITY;
327    for p_i in partials {
328        let x_i = party_to_scalar(p_i.party_index);
329        let mut numerator = Scalar::ONE;
330        let mut denominator = Scalar::ONE;
331        for p_j in partials {
332            if p_j.party_index == p_i.party_index {
333                continue;
334            }
335            let x_j = party_to_scalar(p_j.party_index);
336            numerator *= negate(&x_j);
337            denominator *= x_i.sub(&x_j);
338        }
339        let denom_inv = invert(&denominator);
340        let lagrange = numerator * denom_inv;
341
342        let partial_point = decode_point(&p_i.bytes)?;
343        let weighted = partial_point * lagrange;
344        combined = combined.add(&weighted);
345    }
346
347    // Derive AEAD key from X-coordinate of combined
348    let shared = x_coordinate(&combined);
349    let key = derive_aead_key(&shared, algorithm);
350
351    // AEAD decrypt
352    let nonce = Nonce::from(slice_to_array::<12>(&blob.nonce)?);
353    let tag_bytes = slice_to_array::<16>(&blob.tag)?;
354    let mut buffer = blob.ciphertext.clone();
355    match algorithm {
356        AeadAlgorithm::Aes256Gcm => {
357            let cipher =
358                Aes256Gcm::new_from_slice(&key).map_err(|e| EciesError::Aead(e.to_string()))?;
359            let tag = aes_gcm::Tag::from(tag_bytes);
360            cipher
361                .decrypt_inout_detached(&nonce, b"", InOutBuf::from(buffer.as_mut_slice()), &tag)
362                .map_err(|e| EciesError::Aead(format!("decrypt: {e}")))?;
363        }
364        AeadAlgorithm::Aes256GcmSiv => {
365            let cipher =
366                Aes256GcmSiv::new_from_slice(&key).map_err(|e| EciesError::Aead(e.to_string()))?;
367            let tag = aes_gcm_siv::Tag::from(tag_bytes);
368            cipher
369                .decrypt_inout_detached(&nonce, b"", InOutBuf::from(buffer.as_mut_slice()), &tag)
370                .map_err(|e| EciesError::Aead(format!("decrypt: {e}")))?;
371        }
372    }
373
374    Ok(buffer)
375}
376
377fn negate(s: &Scalar) -> Scalar {
378    Scalar::ZERO.sub(s)
379}
380
381fn invert(s: &Scalar) -> Scalar {
382    // Garbage-in-garbage-out on zero input; protocol callers pass
383    // non-zero scalars (sweep ledger: SEC-audit-notes).
384    let ct: CtOption<Scalar> = s.invert();
385    Option::<Scalar>::from(ct).unwrap_or(Scalar::ZERO)
386}
387
388/// Reduce 32 bytes to a scalar by rejection sampling with re-hash;
389/// never falls back to a constant.
390fn reduce_to_scalar(mut bytes: [u8; 32]) -> Scalar {
391    loop {
392        if let Some(s) = Option::<Scalar>::from(Scalar::from_repr(FieldBytes::from(bytes))) {
393            return s;
394        }
395        let mut h = Sha256::new();
396        h.update(b"confium-scalar-reduce-v1");
397        h.update(bytes);
398        bytes = h.finalize().into();
399    }
400}
401
402fn party_to_scalar(v: u32) -> Scalar {
403    let mut arr = [0u8; 32];
404    arr[28..32].copy_from_slice(&v.to_be_bytes());
405    reduce_to_scalar(arr)
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    #[test]
413    fn encrypt_then_decrypt_round_trip() {
414        // Generate keypair, split into 3 shares (T=2).
415        let keypair = generate_keypair();
416        let pk = PublicKey::from_affine(keypair.public_key);
417        let shares = split_secret(&keypair.secret_scalar, 2, 3);
418
419        let plaintext = b"hello, threshold ECIES world";
420        let blob = encrypt(&pk, plaintext).unwrap();
421
422        // T-of-N partial decryption
423        let decryption_shares: Vec<DecryptionShare> = shares
424            .iter()
425            .map(|s| DecryptionShare {
426                party_index: s.x,
427                bytes: {
428                    let fb: FieldBytes = s.y.to_bytes();
429                    let arr: [u8; 32] = fb.into();
430                    arr.to_vec()
431                },
432            })
433            .collect();
434        let partials: Vec<PartialDecryption> = decryption_shares
435            .iter()
436            .take(2)
437            .map(|ds| partial_decrypt(ds, &blob).unwrap())
438            .collect();
439
440        let recovered = aggregate_partials(&partials, 2, &blob).unwrap();
441        assert_eq!(recovered.as_slice(), plaintext);
442    }
443
444    #[test]
445    fn different_share_subsets_recover_same_plaintext() {
446        let keypair = generate_keypair();
447        let pk = PublicKey::from_affine(keypair.public_key);
448        let shares = split_secret(&keypair.secret_scalar, 3, 5);
449
450        let plaintext = b"consistency check across share subsets";
451        let blob = encrypt(&pk, plaintext).unwrap();
452
453        let decryption_shares: Vec<DecryptionShare> = shares
454            .iter()
455            .map(|s| DecryptionShare {
456                party_index: s.x,
457                bytes: {
458                    let fb: FieldBytes = s.y.to_bytes();
459                    let arr: [u8; 32] = fb.into();
460                    arr.to_vec()
461                },
462            })
463            .collect();
464
465        // Subset A: shares 0, 1, 2
466        let partials_a: Vec<PartialDecryption> = decryption_shares[0..3]
467            .iter()
468            .map(|ds| partial_decrypt(ds, &blob).unwrap())
469            .collect();
470        let recovered_a = aggregate_partials(&partials_a, 3, &blob).unwrap();
471
472        // Subset B: shares 2, 3, 4
473        let partials_b: Vec<PartialDecryption> = decryption_shares[2..5]
474            .iter()
475            .map(|ds| partial_decrypt(ds, &blob).unwrap())
476            .collect();
477        let recovered_b = aggregate_partials(&partials_b, 3, &blob).unwrap();
478
479        assert_eq!(recovered_a.as_slice(), plaintext);
480        assert_eq!(recovered_b.as_slice(), plaintext);
481    }
482
483    #[test]
484    fn gcm_siv_round_trip() {
485        let keypair = generate_keypair();
486        let pk = PublicKey::from_affine(keypair.public_key);
487        let shares = split_secret(&keypair.secret_scalar, 2, 3);
488
489        let plaintext = b"gcm-siv protected escrow payload";
490        let blob = encrypt_with(&pk, plaintext, AeadAlgorithm::Aes256GcmSiv).unwrap();
491
492        let decryption_shares: Vec<DecryptionShare> = shares
493            .iter()
494            .map(|s| DecryptionShare {
495                party_index: s.x,
496                bytes: {
497                    let fb: FieldBytes = s.y.to_bytes();
498                    let arr: [u8; 32] = fb.into();
499                    arr.to_vec()
500                },
501            })
502            .collect();
503        let partials: Vec<PartialDecryption> = decryption_shares[0..2]
504            .iter()
505            .map(|ds| partial_decrypt(ds, &blob).unwrap())
506            .collect();
507
508        let recovered =
509            aggregate_partials_with(&partials, 2, &blob, AeadAlgorithm::Aes256GcmSiv).unwrap();
510        assert_eq!(recovered.as_slice(), plaintext);
511    }
512
513    #[test]
514    fn algorithm_mismatch_fails() {
515        let keypair = generate_keypair();
516        let pk = PublicKey::from_affine(keypair.public_key);
517        let shares = split_secret(&keypair.secret_scalar, 2, 3);
518        let blob = encrypt_with(&pk, b"x", AeadAlgorithm::Aes256GcmSiv).unwrap();
519
520        let decryption_shares: Vec<DecryptionShare> = shares
521            .iter()
522            .map(|s| DecryptionShare {
523                party_index: s.x,
524                bytes: {
525                    let fb: FieldBytes = s.y.to_bytes();
526                    let arr: [u8; 32] = fb.into();
527                    arr.to_vec()
528                },
529            })
530            .collect();
531        let partials: Vec<PartialDecryption> = decryption_shares[0..2]
532            .iter()
533            .map(|ds| partial_decrypt(ds, &blob).unwrap())
534            .collect();
535
536        // decrypting a SIV blob as GCM must fail (domain-separated keys)
537        let result = aggregate_partials_with(&partials, 2, &blob, AeadAlgorithm::Aes256Gcm);
538        assert!(matches!(result, Err(EciesError::Aead(_))));
539    }
540
541    #[test]
542    fn threshold_not_met_fails() {
543        let keypair = generate_keypair();
544        let pk = PublicKey::from_affine(keypair.public_key);
545        let shares = split_secret(&keypair.secret_scalar, 3, 5);
546        let blob = encrypt(&pk, b"x").unwrap();
547        let decryption_shares: Vec<DecryptionShare> = shares
548            .iter()
549            .map(|s| DecryptionShare {
550                party_index: s.x,
551                bytes: {
552                    let fb: FieldBytes = s.y.to_bytes();
553                    let arr: [u8; 32] = fb.into();
554                    arr.to_vec()
555                },
556            })
557            .collect();
558        let partials: Vec<PartialDecryption> = decryption_shares[0..2]
559            .iter()
560            .map(|ds| partial_decrypt(ds, &blob).unwrap())
561            .collect();
562        let result = aggregate_partials(&partials, 3, &blob);
563        assert!(matches!(result, Err(EciesError::ThresholdNotMet { .. })));
564    }
565
566    #[test]
567    fn wrong_subset_fails_to_decrypt() {
568        // Aggregate with random unrelated partials should fail AEAD.
569        let keypair = generate_keypair();
570        let pk = PublicKey::from_affine(keypair.public_key);
571        let _shares = split_secret(&keypair.secret_scalar, 2, 3);
572        let blob = encrypt(&pk, b"secret").unwrap();
573
574        // Use shares from a DIFFERENT keypair to produce wrong partials.
575        let other = generate_keypair();
576        let other_shares = split_secret(&other.secret_scalar, 2, 3);
577        let wrong_partials: Vec<PartialDecryption> = other_shares[0..2]
578            .iter()
579            .map(|s| {
580                partial_decrypt(
581                    &DecryptionShare {
582                        party_index: s.x,
583                        bytes: {
584                            let fb: FieldBytes = s.y.to_bytes();
585                            let arr: [u8; 32] = fb.into();
586                            arr.to_vec()
587                        },
588                    },
589                    &blob,
590                )
591                .unwrap()
592            })
593            .collect();
594        let result = aggregate_partials(&wrong_partials, 2, &blob);
595        assert!(matches!(result, Err(EciesError::Aead(_))));
596    }
597}