Skip to main content

dcrypt_algorithms/ec/p521/
mod.rs

1//! NIST P-521 Elliptic Curve Primitives
2//!
3//! This module implements NIST P-521 elliptic-curve arithmetic.
4//! The curve equation is y² = x³ - 3x + b over the prime field F_p where:
5//! - p = 2^521 - 1 (NIST P-521 prime, a Mersenne prime)
6//! - The curve order n = 0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409
7//!
8//! Selected paths use fixed-iteration or conditional-selection techniques, but
9//! no blanket constant-time claim is made for the module, compiler, or target.
10//! The implementation uses:
11//! - Mersenne reduction for field arithmetic (2^521 ≡ 1 mod p)
12//! - Jacobian projective coordinates for efficient point operations
13//! - Binary scalar multiplication with constant-time point selection
14
15mod constants;
16mod field;
17mod point;
18mod scalar;
19
20pub use constants::{
21    P521_FIELD_ELEMENT_SIZE, P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE, P521_POINT_COMPRESSED_SIZE,
22    P521_POINT_UNCOMPRESSED_SIZE, P521_SCALAR_SIZE,
23};
24pub use field::FieldElement;
25pub use point::{Point, PointFormat};
26pub use scalar::Scalar;
27
28use crate::error::{Error, Result};
29use crate::hash::sha2::Sha512;
30use crate::kdf::hkdf::Hkdf;
31use crate::kdf::KeyDerivationFunction as KdfTrait;
32use dcrypt_internal::random::{try_fill_bytes_zeroing_on_error, CryptoRng, RngCore};
33use dcrypt_internal::zeroing::Zeroizing;
34use dcrypt_params::traditional::ecdsa::NIST_P521;
35
36/// Get the standard base point G of the P-521 curve
37///
38/// Returns the generator point specified in the NIST P-521 standard.
39/// This point generates the cyclic subgroup used for ECDH and ECDSA.
40pub fn base_point_g() -> Point {
41    Point::new_uncompressed(&NIST_P521.g_x, &NIST_P521.g_y)
42        .expect("Standard base point must be valid")
43}
44
45/// Scalar multiplication with the base point: scalar * G
46///
47/// Efficiently computes scalar multiplication with the standard generator.
48/// This is the core operation for generating public keys from private keys.
49pub fn scalar_mult_base_g(scalar: &Scalar) -> Result<Point> {
50    let g = base_point_g();
51    g.mul(scalar)
52}
53
54/// Generate a cryptographically secure ECDH keypair
55///
56/// Uses rejection sampling to ensure the private key scalar is uniformly
57/// distributed in the range [1, n-1]. The public key is computed as
58/// private_key * G where G is the standard base point.
59///
60/// Returns (private_key, public_key) pair suitable for ECDH key agreement.
61pub fn generate_keypair<R: CryptoRng + RngCore>(rng: &mut R) -> Result<(Scalar, Point)> {
62    let mut scalar_bytes = Zeroizing::new([0u8; P521_SCALAR_SIZE]);
63
64    // Use rejection sampling for uniform distribution
65    loop {
66        try_fill_bytes_zeroing_on_error(rng, &mut scalar_bytes[..])?;
67        // P-521 scalars use 521 bits in a 66-byte container. Mask the seven
68        // unused high bits, then reject zero or values at/above the order.
69        // This samples uniformly without reducing a 528-bit value modulo n.
70        scalar_bytes[0] &= 0x01;
71
72        // Attempt to create a valid scalar (non-zero, < n)
73        match Scalar::new(*scalar_bytes) {
74            Ok(private_key) => {
75                // Compute corresponding public key
76                let public_key = scalar_mult_base_g(&private_key)?;
77                return Ok((private_key, public_key));
78            }
79            Err(_) => {
80                // Invalid scalar generated, retry with new random bytes
81                continue;
82            }
83        }
84    }
85}
86
87/// General scalar multiplication: compute scalar * point
88///
89/// Performs scalar multiplication with an arbitrary point on the curve.
90/// Used in ECDH key agreement and signature verification.
91pub fn scalar_mult(scalar: &Scalar, point: &Point) -> Result<Point> {
92    if point.is_identity() {
93        // scalar * O = O (identity element)
94        return Ok(Point::identity());
95    }
96
97    point.mul(scalar)
98}
99
100/// Key derivation function for ECDH shared secret using HKDF-SHA512
101///
102/// Derives a cryptographically strong shared secret from the ECDH raw output.
103/// Uses HKDF (HMAC-based Key Derivation Function) with SHA-512 as specified
104/// in RFC 5869 for secure key derivation.
105///
106/// SHA-512 is more appropriate for P-521 due to the larger curve size.
107///
108/// Parameters:
109/// - ikm: Input key material (raw ECDH output, e.g., x-coordinate)
110/// - info: Optional context information for domain separation
111///
112/// Returns a fixed-length derived key suitable for symmetric encryption.
113pub fn kdf_hkdf_sha512_for_ecdh_kem(
114    ikm: &[u8],
115    info: Option<&[u8]>,
116) -> Result<Zeroizing<[u8; P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE]>> {
117    let hkdf_instance = <Hkdf<Sha512, 16> as KdfTrait>::new();
118
119    // Perform HKDF key derivation
120    let derived_key_vec = hkdf_instance.derive_key(
121        ikm,
122        None, // No salt for ECDH applications (uses zero-length salt)
123        info, // Context info for domain separation
124        P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE,
125    )?;
126
127    // Convert to fixed-size array
128    let mut output_array = Zeroizing::new([0u8; P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE]);
129    if derived_key_vec.len() == P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE {
130        output_array.copy_from_slice(&derived_key_vec);
131        Ok(output_array)
132    } else {
133        Err(Error::Length {
134            context: "KDF output for ECDH",
135            expected: P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE,
136            actual: derived_key_vec.len(),
137        })
138    }
139}
140
141#[cfg(test)]
142mod tests;