Skip to main content

confium_tc_elgamal_p256/
keys.rs

1//! Keypair generation for threshold ElGamal-P256.
2
3use p256::elliptic_curve::PrimeField;
4use p256::elliptic_curve::rand_core;
5use p256::elliptic_curve::rand_core::Rng;
6use p256::elliptic_curve::subtle::CtOption;
7use p256::{AffinePoint, FieldBytes, ProjectivePoint, Scalar};
8
9/// A P-256 keypair.
10#[derive(Debug, Clone)]
11pub struct Keypair {
12    /// Secret scalar.
13    pub secret_scalar: Scalar,
14    /// Public key (affine point).
15    pub public_key: AffinePoint,
16}
17
18/// Generate a fresh random keypair.
19pub fn generate_keypair() -> Keypair {
20    let secret = loop {
21        let mut buf = [0u8; 32];
22        rand_core::UnwrapErr(getrandom::SysRng).fill_bytes(&mut buf);
23        if let Some(s) = CtOption::into(Scalar::from_repr(FieldBytes::from(buf))) {
24            if s != Scalar::ZERO {
25                break s;
26            }
27        }
28    };
29    let public = public_key_for(&secret);
30    Keypair {
31        secret_scalar: secret,
32        public_key: public,
33    }
34}
35
36/// Compute the public key for a given secret scalar.
37pub fn public_key_for(secret: &Scalar) -> AffinePoint {
38    let g = ProjectivePoint::GENERATOR;
39    (g * secret).to_affine()
40}