Skip to main content

dcrypt_kem/ecdh/k256/
mod.rs

1// File: crates/kem/src/ecdh/k256/mod.rs
2//! ECDH-KEM with secp256k1 (K-256)
3//!
4//! This module provides a Key Encapsulation Mechanism (KEM) based on the
5//! Elliptic Curve Diffie-Hellman (ECDH) protocol using the secp256k1 curve.
6//! This is a dcrypt-specific ECDH-plus-HKDF construction, not RFC 9180 HPKE.
7//! Invalid inputs return errors. No blanket constant-time or IND-CCA claim is
8//! made; arithmetic behavior depends on the backend, compiler, and target.
9//!
10//! This implementation uses compressed point format for optimal bandwidth efficiency.
11//!
12//! Public points are validated and the shared point is processed with
13//! HKDF-SHA256. Protocols needing HPKE or implicit rejection must use a vetted
14//! implementation of that construction instead.
15
16use super::concat_kdf_ikm;
17use crate::error::Error as KemError;
18use alloc::vec::Vec;
19use dcrypt_algorithms::ec::k256 as ec_k256;
20use dcrypt_api::{
21    error::Error as ApiError,
22    traits::serialize::{Serialize, SerializeSecret},
23    Kem, Key as ApiKey, Result as ApiResult, ZeroizingBytes,
24};
25use dcrypt_common::security::SecretBuffer;
26use dcrypt_internal::random::{CryptoRng, RngCore};
27use dcrypt_internal::zeroing::Zeroizing;
28
29const KDF_INFO: &[u8] = b"dcrypt-v3/ECDH-K256-KEM/shared-secret";
30
31/// ECDH KEM with secp256k1 curve
32pub struct EcdhK256;
33
34/// Public key for ECDH-K256 KEM (compressed EC point)
35#[derive(Clone)]
36pub struct EcdhK256PublicKey([u8; ec_k256::K256_POINT_COMPRESSED_SIZE]);
37
38impl_zeroize_tuple!(EcdhK256PublicKey);
39
40impl AsRef<[u8]> for EcdhK256PublicKey {
41    fn as_ref(&self) -> &[u8] {
42        &self.0
43    }
44}
45
46impl AsMut<[u8]> for EcdhK256PublicKey {
47    fn as_mut(&mut self) -> &mut [u8] {
48        &mut self.0
49    }
50}
51
52/// Secret key for ECDH-K256 KEM (scalar value)
53#[derive(Clone)]
54pub struct EcdhK256SecretKey(SecretBuffer<{ ec_k256::K256_SCALAR_SIZE }>);
55
56impl_zeroize_on_drop_tuple!(EcdhK256SecretKey);
57
58impl AsRef<[u8]> for EcdhK256SecretKey {
59    fn as_ref(&self) -> &[u8] {
60        self.0.as_ref()
61    }
62}
63
64/// Shared secret from ECDH-K256 KEM
65#[derive(Clone)]
66pub struct EcdhK256SharedSecret(ApiKey);
67
68impl_zeroize_on_drop_tuple!(EcdhK256SharedSecret);
69
70impl AsRef<[u8]> for EcdhK256SharedSecret {
71    fn as_ref(&self) -> &[u8] {
72        self.0.as_ref()
73    }
74}
75
76/// Ciphertext for ECDH-K256 KEM (compressed ephemeral public key)
77#[derive(Clone)]
78pub struct EcdhK256Ciphertext([u8; ec_k256::K256_POINT_COMPRESSED_SIZE]);
79
80impl AsRef<[u8]> for EcdhK256Ciphertext {
81    fn as_ref(&self) -> &[u8] {
82        &self.0
83    }
84}
85
86impl AsMut<[u8]> for EcdhK256Ciphertext {
87    fn as_mut(&mut self) -> &mut [u8] {
88        &mut self.0
89    }
90}
91
92// --- Public key methods ---
93impl EcdhK256PublicKey {
94    pub fn from_bytes(bytes: &[u8]) -> ApiResult<Self> {
95        if bytes.len() != ec_k256::K256_POINT_COMPRESSED_SIZE {
96            return Err(ApiError::InvalidLength {
97                context: "EcdhK256PublicKey::from_bytes",
98                expected: ec_k256::K256_POINT_COMPRESSED_SIZE,
99                actual: bytes.len(),
100            });
101        }
102        let point = ec_k256::Point::deserialize_compressed(bytes)
103            .map_err(|e| ApiError::from(KemError::from(e)))?;
104        if point.is_identity() {
105            return Err(ApiError::InvalidKey {
106                context: "EcdhK256PublicKey::from_bytes",
107                #[cfg(feature = "std")]
108                message: "Public key cannot be the identity point".to_string(),
109            });
110        }
111        let mut key_bytes = [0u8; ec_k256::K256_POINT_COMPRESSED_SIZE];
112        key_bytes.copy_from_slice(bytes);
113        Ok(Self(key_bytes))
114    }
115    pub fn to_bytes(&self) -> Vec<u8> {
116        self.0.to_vec()
117    }
118}
119
120impl Serialize for EcdhK256PublicKey {
121    fn from_bytes(bytes: &[u8]) -> ApiResult<Self> {
122        Self::from_bytes(bytes)
123    }
124    fn to_bytes(&self) -> Vec<u8> {
125        self.to_bytes()
126    }
127}
128
129// --- Secret key methods ---
130impl EcdhK256SecretKey {
131    pub fn from_bytes(bytes: &[u8]) -> ApiResult<Self> {
132        if bytes.len() != ec_k256::K256_SCALAR_SIZE {
133            return Err(ApiError::InvalidLength {
134                context: "EcdhK256SecretKey::from_bytes",
135                expected: ec_k256::K256_SCALAR_SIZE,
136                actual: bytes.len(),
137            });
138        }
139        let mut buffer = SecretBuffer::zeroed();
140        buffer.as_mut().copy_from_slice(bytes);
141        let scalar = ec_k256::Scalar::from_secret_buffer(buffer.clone())
142            .map_err(|e| ApiError::from(KemError::from(e)))?;
143        drop(scalar);
144        Ok(Self(buffer))
145    }
146    pub fn to_bytes(&self) -> ZeroizingBytes {
147        self.0.to_bytes_zeroizing_boxed()
148    }
149}
150
151impl SerializeSecret for EcdhK256SecretKey {
152    fn from_bytes(bytes: &[u8]) -> ApiResult<Self> {
153        Self::from_bytes(bytes)
154    }
155    fn to_bytes_zeroizing(&self) -> ZeroizingBytes {
156        self.to_bytes()
157    }
158}
159
160// --- Shared secret methods ---
161impl EcdhK256SharedSecret {
162    pub fn to_bytes(&self) -> ZeroizingBytes {
163        self.0.to_bytes_zeroizing_boxed()
164    }
165    pub fn to_bytes_zeroizing(&self) -> ZeroizingBytes {
166        self.to_bytes()
167    }
168}
169
170impl SerializeSecret for EcdhK256SharedSecret {
171    fn from_bytes(bytes: &[u8]) -> ApiResult<Self> {
172        if bytes.len() != ec_k256::K256_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE {
173            return Err(ApiError::InvalidLength {
174                context: "EcdhK256SharedSecret::from_bytes",
175                expected: ec_k256::K256_KEM_SHARED_SECRET_KDF_OUTPUT_SIZE,
176                actual: bytes.len(),
177            });
178        }
179        Ok(Self(ApiKey::new(bytes)))
180    }
181    fn to_bytes_zeroizing(&self) -> ZeroizingBytes {
182        self.to_bytes_zeroizing()
183    }
184}
185
186// --- Ciphertext methods ---
187impl EcdhK256Ciphertext {
188    pub fn from_bytes(bytes: &[u8]) -> ApiResult<Self> {
189        if bytes.len() != ec_k256::K256_POINT_COMPRESSED_SIZE {
190            return Err(ApiError::InvalidLength {
191                context: "EcdhK256Ciphertext::from_bytes",
192                expected: ec_k256::K256_POINT_COMPRESSED_SIZE,
193                actual: bytes.len(),
194            });
195        }
196        let point = ec_k256::Point::deserialize_compressed(bytes)
197            .map_err(|e| ApiError::from(KemError::from(e)))?;
198        if point.is_identity() {
199            return Err(ApiError::InvalidCiphertext {
200                context: "EcdhK256Ciphertext::from_bytes",
201                #[cfg(feature = "std")]
202                message: "Ephemeral public key cannot be the identity point".to_string(),
203            });
204        }
205        let mut ct_bytes = [0u8; ec_k256::K256_POINT_COMPRESSED_SIZE];
206        ct_bytes.copy_from_slice(bytes);
207        Ok(Self(ct_bytes))
208    }
209    pub fn to_bytes(&self) -> Vec<u8> {
210        self.0.to_vec()
211    }
212}
213
214impl Serialize for EcdhK256Ciphertext {
215    fn from_bytes(bytes: &[u8]) -> ApiResult<Self> {
216        Self::from_bytes(bytes)
217    }
218    fn to_bytes(&self) -> Vec<u8> {
219        self.to_bytes()
220    }
221}
222
223impl Kem for EcdhK256 {
224    type PublicKey = EcdhK256PublicKey;
225    type SecretKey = EcdhK256SecretKey;
226    type SharedSecret = EcdhK256SharedSecret;
227    type Ciphertext = EcdhK256Ciphertext;
228    type KeyPair = (Self::PublicKey, Self::SecretKey);
229
230    fn name() -> &'static str {
231        "ECDH-K256"
232    }
233
234    fn keypair<R: CryptoRng + RngCore>(rng: &mut R) -> ApiResult<Self::KeyPair> {
235        let (sk_scalar, pk_point) =
236            ec_k256::generate_keypair(rng).map_err(|e| ApiError::from(KemError::from(e)))?;
237        let public_key = EcdhK256PublicKey(pk_point.serialize_compressed());
238        let secret_key = EcdhK256SecretKey(sk_scalar.as_secret_buffer().clone());
239        Ok((public_key, secret_key))
240    }
241
242    fn public_key(keypair: &Self::KeyPair) -> Self::PublicKey {
243        keypair.0.clone()
244    }
245
246    fn secret_key(keypair: &Self::KeyPair) -> Self::SecretKey {
247        keypair.1.clone()
248    }
249
250    fn encapsulate<R: CryptoRng + RngCore>(
251        rng: &mut R,
252        public_key_recipient: &Self::PublicKey,
253    ) -> ApiResult<(Self::Ciphertext, Self::SharedSecret)> {
254        let pk_r_point = ec_k256::Point::deserialize_compressed(&public_key_recipient.0)
255            .map_err(|e| ApiError::from(KemError::from(e)))?;
256        if pk_r_point.is_identity() {
257            return Err(ApiError::InvalidKey {
258                context: "ECDH-K256 encapsulate",
259                #[cfg(feature = "std")]
260                message: "Recipient public key cannot be the identity point".to_string(),
261            });
262        }
263        let (ephemeral_scalar, ephemeral_point) =
264            ec_k256::generate_keypair(rng).map_err(|e| ApiError::from(KemError::from(e)))?;
265        let ciphertext = EcdhK256Ciphertext(ephemeral_point.serialize_compressed());
266        let shared_point = ec_k256::scalar_mult(&ephemeral_scalar, &pk_r_point)
267            .map_err(|e| ApiError::from(KemError::from(e)))?;
268        if shared_point.is_identity() {
269            return Err(ApiError::DecryptionFailed {
270                context: "ECDH-K256 encapsulate",
271                #[cfg(feature = "std")]
272                message: "Shared point is the identity".to_string(),
273            });
274        }
275        let x_coord_bytes = Zeroizing::new(shared_point.x_coordinate_bytes());
276        let kdf_ikm = concat_kdf_ikm(
277            x_coord_bytes.as_ref(),
278            &ephemeral_point.serialize_compressed(),
279            &public_key_recipient.0,
280        );
281        let ss_bytes = ec_k256::kdf_hkdf_sha256_for_ecdh_kem(&kdf_ikm, Some(KDF_INFO))
282            .map_err(|e| ApiError::from(KemError::from(e)))?;
283        let shared_secret = EcdhK256SharedSecret(ApiKey::new(&ss_bytes[..]));
284        drop(ephemeral_scalar);
285        Ok((ciphertext, shared_secret))
286    }
287
288    fn decapsulate(
289        secret_key_recipient: &Self::SecretKey,
290        ciphertext_ephemeral_pk: &Self::Ciphertext,
291    ) -> ApiResult<Self::SharedSecret> {
292        let sk_r_scalar = ec_k256::Scalar::from_secret_buffer(secret_key_recipient.0.clone())
293            .map_err(|e| ApiError::from(KemError::from(e)))?;
294        let q_e_point = ec_k256::Point::deserialize_compressed(&ciphertext_ephemeral_pk.0)
295            .map_err(|e| ApiError::from(KemError::from(e)))?;
296        if q_e_point.is_identity() {
297            return Err(ApiError::InvalidCiphertext {
298                context: "ECDH-K256 decapsulate",
299                #[cfg(feature = "std")]
300                message: "Ephemeral public key cannot be the identity point".to_string(),
301            });
302        }
303        let shared_point = ec_k256::scalar_mult(&sk_r_scalar, &q_e_point)
304            .map_err(|e| ApiError::from(KemError::from(e)))?;
305        if shared_point.is_identity() {
306            return Err(ApiError::DecryptionFailed {
307                context: "ECDH-K256 decapsulate",
308                #[cfg(feature = "std")]
309                message: "Shared point is the identity".to_string(),
310            });
311        }
312        let x_coord_bytes = Zeroizing::new(shared_point.x_coordinate_bytes());
313        let q_r_point = ec_k256::scalar_mult_base_g(&sk_r_scalar)
314            .map_err(|e| ApiError::from(KemError::from(e)))?;
315        let kdf_ikm = concat_kdf_ikm(
316            x_coord_bytes.as_ref(),
317            &ciphertext_ephemeral_pk.0,
318            &q_r_point.serialize_compressed(),
319        );
320        let ss_bytes = ec_k256::kdf_hkdf_sha256_for_ecdh_kem(&kdf_ikm, Some(KDF_INFO))
321            .map_err(|e| ApiError::from(KemError::from(e)))?;
322        let shared_secret = EcdhK256SharedSecret(ApiKey::new(&ss_bytes[..]));
323        Ok(shared_secret)
324    }
325}
326
327#[cfg(test)]
328mod tests;