Skip to main content

embedded_cal_rustcrypto/
dh.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// SPDX-FileCopyrightText: Inria-AIO, Cryspen, and Christian Amsüss
3
4use super::*;
5use embedded_cal::{Cal, DhProvider, ImportError, util::Either};
6
7impl<Base> DhProvider for RustcryptoCalExtender<Base>
8where
9    Base: Cal + rand_core::TryCryptoRng<Error = core::convert::Infallible>,
10{
11    type Algorithm = DhAlgorithm<DhAlgorithmOf<Base>>;
12    type VisibleSecretKey = VisibleSecretKey<DhVisibleSecretKeyOf<Base>>;
13    type SecretKey = SecretKey<DhSecretKeyOf<Base>>;
14    type PublicKey = PublicKey<DhPublicKeyOf<Base>>;
15    type SharedSecret = SharedSecret<DhSharedSecretOf<Base>>;
16
17    fn generate_visible(&mut self, alg: Self::Algorithm) -> Self::VisibleSecretKey {
18        // We're not wrapping anything, so no point in deferring to the self RNG.
19        use p256::elliptic_curve::Generate;
20        match alg {
21            DhAlgorithm::P256 => VisibleSecretKey::P256(p256::SecretKey::generate_from_rng(self)),
22            DhAlgorithm::X25519 => {
23                VisibleSecretKey::X25519(x25519_dalek::StaticSecret::random_from_rng(self))
24            }
25            DhAlgorithm::Direct(d) => VisibleSecretKey::Direct(self.base.dh().generate_visible(d)),
26        }
27    }
28
29    fn export_secretkey_bytes<'s>(
30        &mut self,
31        secret: &'s Self::VisibleSecretKey,
32    ) -> impl AsRef<[u8]> + use<'s, Base> {
33        const MAX_SECRET_BYTES_LEN: usize = 32;
34        match secret {
35            VisibleSecretKey::P256(secret_key) => {
36                Either::Own(heapless::vec::Vec::<u8, MAX_SECRET_BYTES_LEN>::from(<[u8;
37                    32]>::from(
38                    secret_key.to_bytes(),
39                )))
40            }
41            VisibleSecretKey::X25519(secret_key) => Either::Own(secret_key.to_bytes().into()),
42            VisibleSecretKey::Direct(d) => Either::Direct(self.base.dh().export_secretkey_bytes(d)),
43        }
44    }
45
46    fn import_secretkey_bytes(
47        &mut self,
48        alg: Self::Algorithm,
49        secret: &[u8],
50    ) -> Result<Self::VisibleSecretKey, ImportError> {
51        Ok(match alg {
52            DhAlgorithm::P256 => VisibleSecretKey::P256(
53                #[allow(
54                    clippy::unnecessary_fallible_conversions,
55                    reason = "GenericArray has panicking From for slices"
56                )]
57                p256::SecretKey::from_bytes(secret.try_into().map_err(|_| ImportError)?)
58                    .map_err(|_| ImportError)?,
59            ),
60            // It's one of the nice aspects of x25519 that all values of [u8; 32] are valid curve
61            // points, so the only fallible point is the key length.
62            DhAlgorithm::X25519 => VisibleSecretKey::X25519(x25519_dalek::StaticSecret::from(
63                <[u8; 32]>::try_from(secret).map_err(|_| ImportError)?,
64            )),
65            DhAlgorithm::Direct(d) => {
66                VisibleSecretKey::Direct(self.base.dh().import_secretkey_bytes(d, secret)?)
67            }
68        })
69    }
70
71    fn shared_secret(
72        &mut self,
73        private: &Self::SecretKey,
74        public: &Self::PublicKey,
75    ) -> Result<Self::SharedSecret, embedded_cal::IncompatibleKeys> {
76        Ok(match (private, public) {
77            (SecretKey::P256(secret_key), PublicKey::P256(public_key)) => SharedSecret::Length32(
78                (*p256::ecdh::diffie_hellman(
79                    secret_key.to_nonzero_scalar(),
80                    public_key.as_affine(),
81                )
82                .raw_secret_bytes())
83                .into(),
84            ),
85            (SecretKey::X25519(secret_key), PublicKey::X25519(public_key)) => {
86                SharedSecret::Length32(secret_key.diffie_hellman(public_key).to_bytes())
87            }
88            (SecretKey::Direct(secret_key), PublicKey::Direct(public_key)) => {
89                SharedSecret::Direct(self.base.dh().shared_secret(secret_key, public_key)?)
90            }
91            _ => return Err(embedded_cal::IncompatibleKeys),
92        })
93    }
94
95    fn public_key(&mut self, private: &Self::SecretKey) -> Self::PublicKey {
96        match private {
97            SecretKey::P256(secret_key) => PublicKey::P256(secret_key.public_key()),
98            SecretKey::X25519(secret_key) => PublicKey::X25519(secret_key.into()),
99            SecretKey::Direct(d) => PublicKey::Direct(self.base.dh().public_key(d)),
100        }
101    }
102
103    fn raw_secret_bytes<'s>(
104        &mut self,
105        secret: &'s Self::SharedSecret,
106    ) -> impl AsRef<[u8]> + use<'s, Base> {
107        match &secret {
108            SharedSecret::Length32(inner) => Either::Own(inner),
109            SharedSecret::Direct(d) => Either::Direct(self.base.dh().raw_secret_bytes(d)),
110        }
111    }
112
113    fn export_publickey_bytes<'p>(
114        &mut self,
115        public: &'p Self::PublicKey,
116    ) -> impl AsRef<[u8]> + use<'p, Base> {
117        use p256::elliptic_curve::sec1::ToSec1Point;
118        match public {
119            PublicKey::P256(public_key) => Either::Own(
120                *public_key
121                    .to_sec1_point(false)
122                    .x()
123                    .unwrap()
124                    .as_array()
125                    .unwrap(),
126            ),
127            // FIXME: If we're only supporting X25519, we could do without the dereferencing and
128            // shove less data around.
129            PublicKey::X25519(public_key) => Either::Own(*public_key.as_bytes()),
130            PublicKey::Direct(d) => Either::Direct(self.base.dh().export_publickey_bytes(d)),
131        }
132    }
133
134    fn import_publickey_bytes(
135        &mut self,
136        alg: Self::Algorithm,
137        data: &[u8],
138    ) -> Result<Self::PublicKey, ImportError> {
139        use p256::elliptic_curve::point::DecompressPoint;
140        match alg {
141            DhAlgorithm::P256 => Ok(PublicKey::P256(
142                p256::PublicKey::from_affine(
143                    p256::AffinePoint::decompress(
144                        &<[u8; 32]>::try_from(data).map_err(|_| ImportError)?.into(),
145                        // Using the trick from
146                        // https://datatracker.ietf.org/doc/html/rfc9528#name-compact-representation,
147                        // picking an arbitrary version for the compact import
148                        0.into(),
149                    )
150                    // FIXME Should we try to stay subtle?
151                    .into_option()
152                    .ok_or(ImportError)?,
153                )
154                .map_err(|_| ImportError)?,
155            )),
156            DhAlgorithm::X25519 => Ok(PublicKey::X25519(x25519_dalek::PublicKey::from(
157                <[u8; 32]>::try_from(data).map_err(|_| ImportError)?,
158            ))),
159            DhAlgorithm::Direct(d) => self
160                .base
161                .dh()
162                .import_publickey_bytes(d, data)
163                .map(PublicKey::Direct),
164        }
165    }
166}
167
168#[derive(PartialEq, Eq, Debug, Clone)]
169pub enum DhAlgorithm<BA> {
170    P256,
171    X25519,
172    Direct(BA),
173}
174
175impl<BA: embedded_cal::DhAlgorithm> embedded_cal::DhAlgorithm for DhAlgorithm<BA> {
176    fn output_length(&self) -> usize {
177        match self {
178            DhAlgorithm::P256 => 32,
179            DhAlgorithm::X25519 => 32,
180            DhAlgorithm::Direct(d) => d.output_length(),
181        }
182    }
183
184    #[inline]
185    fn from_cose_ecdh(curve: impl Into<i128>) -> Option<Self> {
186        let curve: i128 = curve.into();
187        if let Some(d) = BA::from_cose_ecdh(curve) {
188            return Some(DhAlgorithm::Direct(d));
189        };
190        Some(match curve {
191            1 => DhAlgorithm::P256,
192            4 => DhAlgorithm::X25519,
193            _ => return None,
194        })
195    }
196}
197
198pub enum VisibleSecretKey<BVSK> {
199    P256(p256::SecretKey),
200    X25519(x25519_dalek::StaticSecret),
201    Direct(BVSK),
202}
203
204impl<BVSK, BSK> From<VisibleSecretKey<BVSK>> for SecretKey<BSK>
205where
206    BVSK: Into<BSK>,
207{
208    fn from(value: VisibleSecretKey<BVSK>) -> Self {
209        match value {
210            VisibleSecretKey::P256(k) => SecretKey::P256(k),
211            VisibleSecretKey::X25519(k) => SecretKey::X25519(k),
212            VisibleSecretKey::Direct(d) => SecretKey::Direct(d.into()),
213        }
214    }
215}
216
217pub enum SecretKey<BSK> {
218    P256(p256::SecretKey),
219    // FIXME: x25519_dalek differentiates between StaticSecret and ReusableSecret, could do that here
220    // too (probably we'd have a ReusableSecret here but a StaticSecret in VisibleSecretKey)
221    X25519(x25519_dalek::StaticSecret),
222    Direct(BSK),
223}
224
225pub enum PublicKey<BPK> {
226    P256(p256::PublicKey),
227    X25519(x25519_dalek::PublicKey),
228    Direct(BPK),
229}
230
231pub enum SharedSecret<BSS> {
232    Length32([u8; 32]),
233    Direct(BSS),
234}