Skip to main content

bitwarden_crypto_primitives/rustcrypto/
ed25519.rs

1use ed25519_dalek::Signer;
2use zeroize::Zeroizing;
3
4use crate::{
5    Error,
6    ed25519::{PUBLIC_KEY_LEN, SEED_LEN, SIGNATURE_LEN},
7    random::SystemRng,
8};
9
10#[derive(Clone)]
11pub(crate) struct SigningKey(ed25519_dalek::SigningKey);
12
13// The wrapped key wipes itself on drop.
14impl zeroize::ZeroizeOnDrop for SigningKey {}
15const _: fn() = || {
16    fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
17    assert_zeroize_on_drop::<ed25519_dalek::SigningKey>();
18};
19
20impl SigningKey {
21    pub(crate) fn generate() -> Self {
22        Self(ed25519_dalek::SigningKey::generate(&mut SystemRng))
23    }
24
25    pub(crate) fn from_seed(seed: &[u8; SEED_LEN]) -> Self {
26        Self(ed25519_dalek::SigningKey::from_bytes(seed))
27    }
28
29    pub(crate) fn seed(&self) -> Zeroizing<[u8; SEED_LEN]> {
30        Zeroizing::new(self.0.to_bytes())
31    }
32
33    pub(crate) fn verifying_key(&self) -> VerifyingKey {
34        VerifyingKey(self.0.verifying_key())
35    }
36
37    pub(crate) fn sign(&self, msg: &[u8]) -> [u8; SIGNATURE_LEN] {
38        self.0.sign(msg).to_bytes()
39    }
40}
41
42#[derive(Clone, PartialEq, Eq)]
43pub(crate) struct VerifyingKey(ed25519_dalek::VerifyingKey);
44
45impl VerifyingKey {
46    pub(crate) fn from_bytes(bytes: &[u8; PUBLIC_KEY_LEN]) -> Result<Self, Error> {
47        ed25519_dalek::VerifyingKey::from_bytes(bytes)
48            .map(Self)
49            .map_err(|_| Error::InvalidKey)
50    }
51
52    pub(crate) fn to_bytes(&self) -> [u8; PUBLIC_KEY_LEN] {
53        self.0.to_bytes()
54    }
55
56    /// Strict verification: rejects small-order keys and non-canonical signatures.
57    pub(crate) fn verify(&self, msg: &[u8], sig: &[u8; SIGNATURE_LEN]) -> Result<(), Error> {
58        let sig = ed25519_dalek::Signature::from_bytes(sig);
59        self.0
60            .verify_strict(msg, &sig)
61            .map_err(|_| Error::InvalidSignature)
62    }
63}