libcrux/
ecdh.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! # ECDH
//!
//! Depending on the platform and available features the most efficient implementation
//! is chosen.
//!
//! ## x25519
//! For x25519 the portable HACL implementation is used unless running on an x64
//! CPU with BMI2 and ADX support. In this case the libjade implementation is
//! used.
//!
//! ## P256
//! For P256 the portable HACL implementation is used.

use crate::hacl;

#[derive(Debug, PartialEq, Eq)]
pub enum LowLevelError {
    Jasmin(String),
    Hacl(hacl::Error),
}

#[derive(Debug, PartialEq, Eq)]
pub enum Error {
    InvalidPoint,
    InvalidScalar,
    UnknownAlgorithm,
    KeyGenError,
    Custom(String),
    Wrap(LowLevelError),
}

impl From<hacl::p256::Error> for Error {
    fn from(value: hacl::p256::Error) -> Self {
        Error::Wrap(LowLevelError::Hacl(hacl::Error::P256(value)))
    }
}

/// ECDH algorithm.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Algorithm {
    X25519,
    X448,
    P256,
    P384,
    P521,
}

pub(crate) mod x25519 {
    use rand::{CryptoRng, Rng};

    use super::Error;

    pub struct PrivateKey(pub [u8; 32]);
    pub struct PublicKey(pub [u8; 32]);

    impl From<&[u8; 32]> for PublicKey {
        fn from(value: &[u8; 32]) -> Self {
            Self(value.clone())
        }
    }

    impl TryFrom<&[u8]> for PublicKey {
        type Error = Error;

        fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
            Ok(Self(value.try_into().map_err(|_| Error::InvalidPoint)?))
        }
    }

    impl TryFrom<crate::kem::PublicKey> for PublicKey {
        type Error = Error;

        fn try_from(value: crate::kem::PublicKey) -> Result<Self, Self::Error> {
            if let crate::kem::PublicKey::X25519(k) = value {
                Ok(k)
            } else {
                Err(Error::InvalidPoint)
            }
        }
    }

    impl From<&[u8; 32]> for PrivateKey {
        fn from(value: &[u8; 32]) -> Self {
            Self(value.clone())
        }
    }

    impl TryFrom<&[u8]> for PrivateKey {
        type Error = Error;

        fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
            Ok(Self(value.try_into().map_err(|_| Error::InvalidScalar)?))
        }
    }

    impl TryFrom<crate::kem::PrivateKey> for PrivateKey {
        type Error = Error;

        fn try_from(value: crate::kem::PrivateKey) -> Result<Self, Self::Error> {
            if let crate::kem::PrivateKey::X25519(k) = value {
                Ok(k)
            } else {
                Err(Error::InvalidScalar)
            }
        }
    }

    impl AsRef<[u8]> for PrivateKey {
        fn as_ref(&self) -> &[u8] {
            &self.0
        }
    }

    impl AsRef<[u8]> for PublicKey {
        fn as_ref(&self) -> &[u8] {
            &self.0
        }
    }

    impl AsRef<[u8; 32]> for PrivateKey {
        fn as_ref(&self) -> &[u8; 32] {
            &self.0
        }
    }

    impl AsRef<[u8; 32]> for PublicKey {
        fn as_ref(&self) -> &[u8; 32] {
            &self.0
        }
    }

    #[cfg(all(bmi2, adx, target_arch = "x86_64"))]
    pub(crate) fn derive(p: &PublicKey, s: &PrivateKey) -> Result<PublicKey, Error> {
        use crate::hacl::curve25519;
        use libcrux_platform::x25519_support;
        // On x64 we use vale if available or hacl as fallback.
        // Jasmin exists but is not verified yet.

        if x25519_support() {
            curve25519::vale::ecdh(s, p)
                .map_err(|e| Error::Custom(format!("HACL Error {:?}", e)))
                .map(|p| PublicKey(p))
            // XXX: not verified yet
            // crate::jasmin::x25519::mulx::derive(s, p)
            //     .map_err(|e| Error::Custom(format!("Libjade Error {:?}", e)))
        } else {
            curve25519::ecdh(s, p)
                .map_err(|e| Error::Custom(format!("HACL Error {:?}", e)))
                .map(|p| PublicKey(p))
            // XXX: not verified yet
            // crate::jasmin::x25519::derive(s, p)
            //     .map_err(|e| Error::Custom(format!("Libjade Error {:?}", e)))
        }
    }

    #[cfg(any(
        all(target_arch = "x86_64", any(not(bmi2), not(adx))),
        target_arch = "x86"
    ))]
    pub(crate) fn derive(p: &PublicKey, s: &PrivateKey) -> Result<PublicKey, Error> {
        use crate::hacl::curve25519;
        // On x64 we use vale if available or hacl as fallback.
        // Jasmin exists but is not verified yet.

        curve25519::ecdh(s, p)
            .map_err(|e| Error::Custom(format!("HACL Error {:?}", e)))
            .map(|p| PublicKey(p))
        // XXX: not verified yet
        // crate::jasmin::x25519::derive(s, p)
        //     .map_err(|e| Error::Custom(format!("Libjade Error {:?}", e)))
    }

    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
    pub(crate) fn derive(p: &PublicKey, s: &PrivateKey) -> Result<PublicKey, Error> {
        // On any other platform we use the portable HACL implementation.
        use crate::hacl::curve25519;

        curve25519::ecdh(s, p)
            .map_err(|e| Error::Custom(format!("HACL Error {:?}", e)))
            .map(|p| PublicKey(p))
    }

    // XXX: libjade's secret to public is broken on Windows (overflows the stack).
    // #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    // pub(super) fn secret_to_public(p: &PrivateKey) -> Result<[u8; 32], Error> {
    //     crate::jasmin::x25519::secret_to_public(s).map_err(|e| Error::Custom(format!("Libjade Error {:?}", e)))
    // }

    // #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
    pub(crate) fn secret_to_public(s: &PrivateKey) -> Result<PublicKey, Error> {
        // On any other platform we use the portable HACL implementation.
        use crate::hacl::curve25519;

        Ok(PublicKey(curve25519::secret_to_public(s)))
    }

    /// Generate a new x25519 secret.
    pub fn generate_secret(rng: &mut (impl CryptoRng + Rng)) -> Result<PrivateKey, Error> {
        const LIMIT: usize = 100;
        for _ in 0..LIMIT {
            let mut out = [0u8; 32];
            rng.try_fill_bytes(&mut out)
                .map_err(|_| Error::KeyGenError)?;

            // We don't want a 0 key.
            if out.iter().all(|&b| b == 0) {
                continue;
            }

            // We clamp the key already to make sure it can't be misused.
            out[0] = out[0] & 248u8;
            out[31] = out[31] & 127u8;
            out[31] = out[31] | 64u8;

            return Ok(PrivateKey(out));
        }

        Err(Error::KeyGenError)
    }

    /// Generate a new P256 key pair
    pub fn key_gen(rng: &mut (impl CryptoRng + Rng)) -> Result<(PrivateKey, PublicKey), Error> {
        let sk = generate_secret(rng)?;
        let pk = secret_to_public(&sk)?;
        Ok((sk, pk))
    }
}

pub use x25519::generate_secret as x25519_generate_secret;
pub use x25519::key_gen as x25519_key_gen;

pub(crate) mod p256 {
    use rand::{CryptoRng, Rng};

    // P256 we only have in HACL
    use crate::hacl::p256;

    use super::Error;

    pub struct PrivateKey(pub [u8; 32]);
    pub struct PublicKey(pub [u8; 64]);

    impl From<&[u8; 64]> for PublicKey {
        fn from(value: &[u8; 64]) -> Self {
            Self(value.clone())
        }
    }

    impl TryFrom<&[u8]> for PublicKey {
        type Error = Error;

        fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
            Ok(Self(value.try_into().map_err(|_| Error::InvalidPoint)?))
        }
    }

    impl From<&[u8; 32]> for PrivateKey {
        fn from(value: &[u8; 32]) -> Self {
            Self(value.clone())
        }
    }

    impl TryFrom<&[u8]> for PrivateKey {
        type Error = Error;

        fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
            Ok(Self(value.try_into().map_err(|_| Error::InvalidScalar)?))
        }
    }

    impl AsRef<[u8]> for PrivateKey {
        fn as_ref(&self) -> &[u8] {
            &self.0
        }
    }

    impl AsRef<[u8]> for PublicKey {
        fn as_ref(&self) -> &[u8] {
            &self.0
        }
    }

    impl AsRef<[u8; 32]> for PrivateKey {
        fn as_ref(&self) -> &[u8; 32] {
            &self.0
        }
    }

    impl AsRef<[u8; 64]> for PublicKey {
        fn as_ref(&self) -> &[u8; 64] {
            &self.0
        }
    }

    pub(super) fn derive(p: &PublicKey, s: &PrivateKey) -> Result<PublicKey, Error> {
        // We assume that the private key has been validated.
        p256::ecdh(s, p)
            .map_err(|e| Error::Custom(format!("HACL Error {:?}", e)))
            .map(|p| PublicKey(p))
    }

    pub(super) fn secret_to_public(s: &PrivateKey) -> Result<PublicKey, Error> {
        p256::validate_scalar(s).map_err(|e| Error::Custom(format!("HACL Error {:?}", e)))?;
        p256::secret_to_public(s)
            .map_err(|e| Error::Custom(format!("HACL Error {:?}", e)))
            .map(|p| PublicKey(p))
    }

    pub fn validate_scalar(s: &PrivateKey) -> Result<(), Error> {
        p256::validate_scalar(s).map_err(|e| e.into())
    }

    #[allow(unused)]
    pub fn validate_point(p: &PublicKey) -> Result<(), Error> {
        p256::validate_point(p).map_err(|e| e.into())
    }

    pub(crate) fn prepare_public_key(public_key: &[u8]) -> Result<PublicKey, Error> {
        if public_key.is_empty() {
            return Err(Error::InvalidPoint);
        }

        // Parse the public key.
        let pk = if let Ok(pk) = p256::uncompressed_to_coordinates(public_key) {
            pk
        } else {
            // Might be uncompressed
            if public_key.len() == 33 {
                p256::compressed_to_coordinates(public_key).map_err(|_| Error::InvalidPoint)?
            } else {
                // Might be a simple concatenation
                public_key.try_into().map_err(|_| Error::InvalidPoint)?
            }
        };
        let pk = PublicKey(pk);

        p256::validate_point(&pk)
            .map(|()| pk)
            .map_err(|_| Error::InvalidPoint)
    }

    /// Generate a new p256 secret (scalar)
    pub fn generate_secret(rng: &mut (impl CryptoRng + Rng)) -> Result<PrivateKey, Error> {
        const LIMIT: usize = 100;
        for _ in 0..LIMIT {
            let mut out = [0u8; 32];
            rng.try_fill_bytes(&mut out)
                .map_err(|_| Error::KeyGenError)?;

            let out = PrivateKey(out);
            if validate_scalar(&out).is_ok() {
                return Ok(out);
            }
        }
        Err(Error::KeyGenError)
    }

    /// Generate a new P256 key pair
    pub fn key_gen(rng: &mut (impl CryptoRng + Rng)) -> Result<(PrivateKey, PublicKey), Error> {
        let sk = generate_secret(rng)?;
        let pk = secret_to_public(&sk)?;
        Ok((sk, pk))
    }
}

pub use p256::generate_secret as p256_generate_secret;
pub use p256::key_gen as p256_key_gen;
pub use p256::validate_scalar as p256_validate_scalar;

/// Derive the ECDH shared secret.
/// Returns `Ok(point * scalar)` on the provided curve [`Algorithm`] or an error.
pub fn derive(
    alg: Algorithm,
    point: impl AsRef<[u8]>,
    scalar: impl AsRef<[u8]>,
) -> Result<Vec<u8>, Error> {
    match alg {
        Algorithm::X25519 => {
            x25519::derive(&point.as_ref().try_into()?, &scalar.as_ref().try_into()?)
                .map(|r| r.0.into())
        }
        Algorithm::P256 => {
            let point = p256::prepare_public_key(point.as_ref())?;
            let scalar = hacl::p256::validate_scalar_slice(scalar.as_ref())
                .map_err(|_| Error::InvalidScalar)?;

            p256::derive(&point, &scalar).map(|r| r.0.into())
        }
        _ => Err(Error::UnknownAlgorithm),
    }
}

pub(crate) fn p256_derive(
    point: &p256::PublicKey,
    scalar: &p256::PrivateKey,
) -> Result<p256::PublicKey, Error> {
    p256::validate_point(point)?;
    p256::validate_scalar(scalar)?;

    p256::derive(&point, &scalar)
}

/// Derive the public key for the provided secret key `scalar`.
pub fn secret_to_public(alg: Algorithm, scalar: impl AsRef<[u8]>) -> Result<Vec<u8>, Error> {
    match alg {
        Algorithm::X25519 => {
            x25519::secret_to_public(&scalar.as_ref().try_into()?).map(|r| r.0.into())
        }
        Algorithm::P256 => p256::secret_to_public(&scalar.as_ref().try_into()?).map(|r| r.0.into()),
        _ => Err(Error::UnknownAlgorithm),
    }
}

/// Validate a secret key.
pub fn validate_scalar(alg: Algorithm, s: impl AsRef<[u8]>) -> Result<(), Error> {
    match alg {
        Algorithm::X25519 => {
            if s.as_ref().iter().all(|&b| b == 0) {
                Err(Error::InvalidScalar)
            } else {
                Ok(())
            }
        }
        Algorithm::P256 => p256::validate_scalar(&s.as_ref().try_into()?),
        _ => Err(Error::UnknownAlgorithm),
    }
}

use rand::{CryptoRng, Rng};

/// Generate a new private key scalar.
///
/// The function returns the new scalar or an [`Error::KeyGenError`] if it was unable to
/// generate a new key. If this happens, the provided `rng` is probably faulty.
pub fn generate_secret(alg: Algorithm, rng: &mut (impl CryptoRng + Rng)) -> Result<Vec<u8>, Error> {
    match alg {
        Algorithm::X25519 => x25519::generate_secret(rng).map(|k| k.0.to_vec()),
        Algorithm::P256 => p256::generate_secret(rng).map(|k| k.0.to_vec()),
        _ => Err(Error::UnknownAlgorithm),
    }
}

/// Generate a fresh key pair.
///
/// The function returns the (secret key, public key) tuple, or an [`Error`].
pub fn key_gen(
    alg: Algorithm,
    rng: &mut (impl CryptoRng + Rng),
) -> Result<(Vec<u8>, Vec<u8>), Error> {
    let sk = generate_secret(alg, rng)?;
    let pk = secret_to_public(alg, &sk)?;
    Ok((sk, pk))
}