1#![forbid(unsafe_code)]
22#![allow(missing_docs)] pub 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
44pub const ALGORITHM: &str = "ECIES-P256-threshold";
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54pub enum AeadAlgorithm {
55 #[default]
57 Aes256Gcm,
58 Aes256GcmSiv,
60}
61
62impl AeadAlgorithm {
63 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#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct PublicKey {
78 pub bytes: Vec<u8>,
80}
81
82impl PublicKey {
83 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#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct DecryptionShare {
94 pub party_index: u32,
96 pub bytes: Vec<u8>,
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct EncryptedBlob {
103 pub ephemeral_public: Vec<u8>,
105 pub ciphertext: Vec<u8>,
107 pub nonce: Vec<u8>,
109 pub tag: Vec<u8>,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct PartialDecryption {
116 pub party_index: u32,
118 pub bytes: Vec<u8>,
120}
121
122#[derive(Debug, thiserror::Error)]
124pub enum EciesError {
125 #[error("threshold not met: have {have}, need {need}")]
127 ThresholdNotMet {
128 have: usize,
130 need: u32,
132 },
133 #[error("SEC1 decode failed: {0}")]
135 Sec1Decode(String),
136 #[error("duplicate party index: {0}")]
138 DuplicateParty(u32),
139 #[error("invalid scalar: {0}")]
141 InvalidScalar(String),
142 #[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 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
205pub fn encrypt(recipient: &PublicKey, plaintext: &[u8]) -> Result<EncryptedBlob, EciesError> {
207 encrypt_with(recipient, plaintext, AeadAlgorithm::default())
208}
209
210pub 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 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 let r_point = ProjectivePoint::GENERATOR * r;
231 let ephemeral_public = encode_point(&r_point);
232
233 let shared_point = recipient_pt * r;
235 let shared = x_coordinate(&shared_point);
236
237 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 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
275pub 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
289pub 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
301pub 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 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 let shared = x_coordinate(&combined);
349 let key = derive_aead_key(&shared, algorithm);
350
351 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 let ct: CtOption<Scalar> = s.invert();
385 Option::<Scalar>::from(ct).unwrap_or(Scalar::ZERO)
386}
387
388fn 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 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 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 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 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 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 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 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}