ring/ec/curve25519/
x25519.rs

1// Copyright 2015-2016 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15//! X25519 Key agreement.
16
17use super::{ops, scalar::SCALAR_LEN};
18use crate::{agreement, constant_time, cpu, ec, error, rand};
19use core::convert::TryInto;
20
21static CURVE25519: ec::Curve = ec::Curve {
22    public_key_len: PUBLIC_KEY_LEN,
23    elem_scalar_seed_len: ELEM_AND_SCALAR_LEN,
24    id: ec::CurveID::Curve25519,
25    check_private_key_bytes: x25519_check_private_key_bytes,
26    generate_private_key: x25519_generate_private_key,
27    public_from_private: x25519_public_from_private,
28};
29
30/// X25519 (ECDH using Curve25519) as described in [RFC 7748].
31///
32/// Everything is as described in RFC 7748. Key agreement will fail if the
33/// result of the X25519 operation is zero; see the notes on the
34/// "all-zero value" in [RFC 7748 section 6.1].
35///
36/// [RFC 7748]: https://tools.ietf.org/html/rfc7748
37/// [RFC 7748 section 6.1]: https://tools.ietf.org/html/rfc7748#section-6.1
38pub static X25519: agreement::Algorithm = agreement::Algorithm {
39    curve: &CURVE25519,
40    ecdh: x25519_ecdh,
41};
42
43fn x25519_check_private_key_bytes(bytes: &[u8]) -> Result<(), error::Unspecified> {
44    debug_assert_eq!(bytes.len(), PRIVATE_KEY_LEN);
45    Ok(())
46}
47
48fn x25519_generate_private_key(
49    rng: &dyn rand::SecureRandom,
50    out: &mut [u8],
51) -> Result<(), error::Unspecified> {
52    rng.fill(out)
53}
54
55fn x25519_public_from_private(
56    public_out: &mut [u8],
57    private_key: &ec::Seed,
58) -> Result<(), error::Unspecified> {
59    let public_out = public_out.try_into()?;
60
61    #[cfg(target_arch = "arm")]
62    let cpu_features = private_key.cpu_features;
63
64    let private_key: &[u8; SCALAR_LEN] = private_key.bytes_less_safe().try_into()?;
65    let private_key = ops::MaskedScalar::from_bytes_masked(*private_key);
66
67    #[cfg(all(not(target_os = "ios"), target_arch = "arm"))]
68    {
69        if cpu::arm::NEON.available(cpu_features) {
70            static MONTGOMERY_BASE_POINT: [u8; 32] = [
71                9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72                0, 0, 0, 0,
73            ];
74            x25519_neon(public_out, &private_key, &MONTGOMERY_BASE_POINT);
75            return Ok(());
76        }
77    }
78
79    extern "C" {
80        fn GFp_x25519_public_from_private_generic_masked(
81            public_key_out: &mut PublicKey,
82            private_key: &PrivateKey,
83        );
84    }
85    unsafe {
86        GFp_x25519_public_from_private_generic_masked(public_out, &private_key);
87    }
88
89    Ok(())
90}
91
92fn x25519_ecdh(
93    out: &mut [u8],
94    my_private_key: &ec::Seed,
95    peer_public_key: untrusted::Input,
96) -> Result<(), error::Unspecified> {
97    let cpu_features = my_private_key.cpu_features;
98    let my_private_key: &[u8; SCALAR_LEN] = my_private_key.bytes_less_safe().try_into()?;
99    let my_private_key = ops::MaskedScalar::from_bytes_masked(*my_private_key);
100    let peer_public_key: &[u8; PUBLIC_KEY_LEN] = peer_public_key.as_slice_less_safe().try_into()?;
101
102    #[cfg_attr(
103        not(all(not(target_os = "ios"), target_arch = "arm")),
104        allow(unused_variables)
105    )]
106    fn scalar_mult(
107        out: &mut ops::EncodedPoint,
108        scalar: &ops::MaskedScalar,
109        point: &ops::EncodedPoint,
110        cpu_features: cpu::Features,
111    ) {
112        #[cfg(all(not(target_os = "ios"), target_arch = "arm"))]
113        {
114            if cpu::arm::NEON.available(cpu_features) {
115                return x25519_neon(out, scalar, point);
116            }
117        }
118
119        extern "C" {
120            fn GFp_x25519_scalar_mult_generic_masked(
121                out: &mut ops::EncodedPoint,
122                scalar: &ops::MaskedScalar,
123                point: &ops::EncodedPoint,
124            );
125        }
126        unsafe {
127            GFp_x25519_scalar_mult_generic_masked(out, scalar, point);
128        }
129    }
130
131    scalar_mult(
132        out.try_into()?,
133        &my_private_key,
134        peer_public_key,
135        cpu_features,
136    );
137
138    let zeros: SharedSecret = [0; SHARED_SECRET_LEN];
139    if constant_time::verify_slices_are_equal(out, &zeros).is_ok() {
140        // All-zero output results when the input is a point of small order.
141        return Err(error::Unspecified);
142    }
143
144    Ok(())
145}
146
147#[cfg(all(not(target_os = "ios"), target_arch = "arm"))]
148fn x25519_neon(out: &mut ops::EncodedPoint, scalar: &ops::MaskedScalar, point: &ops::EncodedPoint) {
149    extern "C" {
150        fn GFp_x25519_NEON(
151            out: &mut ops::EncodedPoint,
152            scalar: &ops::MaskedScalar,
153            point: &ops::EncodedPoint,
154        );
155    }
156    unsafe { GFp_x25519_NEON(out, scalar, point) }
157}
158
159const ELEM_AND_SCALAR_LEN: usize = ops::ELEM_LEN;
160
161type PrivateKey = ops::MaskedScalar;
162const PRIVATE_KEY_LEN: usize = ELEM_AND_SCALAR_LEN;
163
164// An X25519 public key as an encoded Curve25519 point.
165type PublicKey = [u8; PUBLIC_KEY_LEN];
166const PUBLIC_KEY_LEN: usize = ELEM_AND_SCALAR_LEN;
167
168// An X25519 shared secret as an encoded Curve25519 point.
169type SharedSecret = [u8; SHARED_SECRET_LEN];
170const SHARED_SECRET_LEN: usize = ELEM_AND_SCALAR_LEN;