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_params::traditional::ecdsa::NIST_P521;
33use rand::{CryptoRng, RngCore};
34
35/// Get the standard base point G of the P-521 curve
36///
37/// Returns the generator point specified in the NIST P-521 standard.
38/// This point generates the cyclic subgroup used for ECDH and ECDSA.
39pub fn base_point_g() -> Point {
40 Point::new_uncompressed(&NIST_P521.g_x, &NIST_P521.g_y)
41 .expect("Standard base point must be valid")
42}
43
44/// Scalar multiplication with the base point: scalar * G
45///
46/// Efficiently computes scalar multiplication with the standard generator.
47/// This is the core operation for generating public keys from private keys.
48pub fn scalar_mult_base_g(scalar: &Scalar) -> Result<Point> {
49 let g = base_point_g();
50 g.mul(scalar)
51}
52
53/// Generate a cryptographically secure ECDH keypair
54///
55/// Uses rejection sampling to ensure the private key scalar is uniformly
56/// distributed in the range [1, n-1]. The public key is computed as
57/// private_key * G where G is the standard base point.
58///
59/// Returns (private_key, public_key) pair suitable for ECDH key agreement.
60pub fn generate_keypair<R: CryptoRng + RngCore>(rng: &mut R) -> Result<(Scalar, Point)> {
61 let mut scalar_bytes = [0u8; P521_SCALAR_SIZE];
62
63 // Use rejection sampling for uniform distribution
64 loop {
65 rng.fill_bytes(&mut scalar_bytes);
66
67 // Attempt to create a valid scalar (non-zero, < n)
68 match Scalar::new(scalar_bytes) {
69 Ok(private_key) => {
70 // Compute corresponding public key
71 let public_key = scalar_mult_base_g(&private_key)?;
72 return Ok((private_key, public_key));
73 }
74 Err(_) => {
75 // Invalid scalar generated, retry with new random bytes
76 continue;
77 }
78 }
79 }
80}
81
82/// General scalar multiplication: compute scalar * point
83///
84/// Performs scalar multiplication with an arbitrary point on the curve.
85/// Used in ECDH key agreement and signature verification.
86pub fn scalar_mult(scalar: &Scalar, point: &Point) -> Result<Point> {
87 if point.is_identity() {
88 // scalar * O = O (identity element)
89 return Ok(Point::identity());
90 }
91
92 point.mul(scalar)
93}
94
95/// Key derivation function for ECDH shared secret using HKDF-SHA512
96///
97/// Derives a cryptographically strong shared secret from the ECDH raw output.
98/// Uses HKDF (HMAC-based Key Derivation Function) with SHA-512 as specified
99/// in RFC 5869 for secure key derivation.
100///
101/// SHA-512 is more appropriate for P-521 due to the larger curve size.
102///
103/// Parameters:
104/// - ikm: Input key material (raw ECDH output, e.g., x-coordinate)
105/// - info: Optional context information for domain separation
106///
107/// Returns a fixed-length derived key suitable for symmetric encryption.
108pub fn kdf_hkdf_sha512_for_ecdh_kem(
109 ikm: &[u8],
110 info: Option<&[u8]>,
111) -> Result<[u8; P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE]> {
112 let hkdf_instance = <Hkdf<Sha512, 16> as KdfTrait>::new();
113
114 // Perform HKDF key derivation
115 let derived_key_vec = hkdf_instance.derive_key(
116 ikm,
117 None, // No salt for ECDH applications (uses zero-length salt)
118 info, // Context info for domain separation
119 P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE,
120 )?;
121
122 // Convert to fixed-size array
123 let mut output_array = [0u8; P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE];
124 if derived_key_vec.len() == P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE {
125 output_array.copy_from_slice(&derived_key_vec);
126 Ok(output_array)
127 } else {
128 Err(Error::Length {
129 context: "KDF output for ECDH",
130 expected: P521_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE,
131 actual: derived_key_vec.len(),
132 })
133 }
134}
135
136#[cfg(test)]
137mod tests;