bitwarden_crypto/signing/
signing_key.rs

1use std::pin::Pin;
2
3use ciborium::{Value, value::Integer};
4use coset::{
5    CborSerializable, CoseKey, RegisteredLabel, RegisteredLabelWithPrivate,
6    iana::{Algorithm, EllipticCurve, EnumI64, KeyOperation, KeyType, OkpKeyParameter},
7};
8use ed25519_dalek::Signer;
9
10use super::{
11    SignatureAlgorithm, ed25519_signing_key, key_id,
12    verifying_key::{RawVerifyingKey, VerifyingKey},
13};
14use crate::{
15    CoseKeyBytes, CryptoKey,
16    content_format::CoseKeyContentFormat,
17    cose::CoseSerializable,
18    error::{EncodingError, Result},
19    keys::KeyId,
20};
21
22/// A `SigningKey` without the key id. This enum contains a variant for each supported signature
23/// scheme.
24#[derive(Clone)]
25enum RawSigningKey {
26    Ed25519(Pin<Box<ed25519_dalek::SigningKey>>),
27}
28
29/// A signing key is a private key used for signing data. An associated `VerifyingKey` can be
30/// derived from it.
31#[derive(Clone)]
32pub struct SigningKey {
33    pub(super) id: KeyId,
34    inner: RawSigningKey,
35}
36
37// Note that `SigningKey` already implements ZeroizeOnDrop, so we don't need to do anything
38// We add this assertion to make sure that this is still true in the future
39// For any new keys, this needs to be checked
40const _: fn() = || {
41    fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
42    assert_zeroize_on_drop::<ed25519_dalek::SigningKey>();
43};
44impl zeroize::ZeroizeOnDrop for SigningKey {}
45impl CryptoKey for SigningKey {}
46
47impl SigningKey {
48    /// Makes a new signing key for the given signature scheme.
49    pub fn make(algorithm: SignatureAlgorithm) -> Self {
50        match algorithm {
51            SignatureAlgorithm::Ed25519 => SigningKey {
52                id: KeyId::make(),
53                inner: RawSigningKey::Ed25519(Box::pin(ed25519_dalek::SigningKey::generate(
54                    &mut rand::thread_rng(),
55                ))),
56            },
57        }
58    }
59
60    pub(super) fn cose_algorithm(&self) -> Algorithm {
61        match &self.inner {
62            RawSigningKey::Ed25519(_) => Algorithm::EdDSA,
63        }
64    }
65
66    /// Derives the verifying key from the signing key. The key id is the same for the signing and
67    /// verifying key, since they are a pair.
68    pub fn to_verifying_key(&self) -> VerifyingKey {
69        match &self.inner {
70            RawSigningKey::Ed25519(key) => VerifyingKey {
71                id: self.id.clone(),
72                inner: RawVerifyingKey::Ed25519(key.verifying_key()),
73            },
74        }
75    }
76
77    /// Signs the given byte array with the signing key.
78    /// This should not be used directly other than for generating namespace separated signatures or
79    /// signed objects.
80    pub(super) fn sign_raw(&self, data: &[u8]) -> Vec<u8> {
81        match &self.inner {
82            RawSigningKey::Ed25519(key) => key.sign(data).to_bytes().to_vec(),
83        }
84    }
85}
86
87impl CoseSerializable<CoseKeyContentFormat> for SigningKey {
88    /// Serializes the signing key to a COSE-formatted byte array.
89    fn to_cose(&self) -> CoseKeyBytes {
90        match &self.inner {
91            RawSigningKey::Ed25519(key) => {
92                coset::CoseKeyBuilder::new_okp_key()
93                    .key_id((&self.id).into())
94                    .algorithm(Algorithm::EdDSA)
95                    .param(
96                        OkpKeyParameter::D.to_i64(), // Signing key
97                        Value::Bytes(key.to_bytes().into()),
98                    )
99                    .param(
100                        OkpKeyParameter::Crv.to_i64(), // Elliptic curve identifier
101                        Value::Integer(Integer::from(EllipticCurve::Ed25519.to_i64())),
102                    )
103                    .add_key_op(KeyOperation::Sign)
104                    .add_key_op(KeyOperation::Verify)
105                    .build()
106                    .to_vec()
107                    .expect("Signing key is always serializable")
108                    .into()
109            }
110        }
111    }
112
113    /// Deserializes a COSE-formatted byte array into a signing key.
114    fn from_cose(bytes: &CoseKeyBytes) -> Result<Self, EncodingError> {
115        let cose_key =
116            CoseKey::from_slice(bytes.as_ref()).map_err(|_| EncodingError::InvalidCoseEncoding)?;
117
118        match (&cose_key.alg, &cose_key.kty) {
119            (
120                Some(RegisteredLabelWithPrivate::Assigned(Algorithm::EdDSA)),
121                RegisteredLabel::Assigned(KeyType::OKP),
122            ) => Ok(SigningKey {
123                id: key_id(&cose_key)?,
124                inner: RawSigningKey::Ed25519(Box::pin(ed25519_signing_key(&cose_key)?)),
125            }),
126            _ => Err(EncodingError::UnsupportedValue(
127                "COSE key type or algorithm",
128            )),
129        }
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn test_cose_roundtrip_encode_signing() {
139        let signing_key = SigningKey::make(SignatureAlgorithm::Ed25519);
140        let cose = signing_key.to_cose();
141        let parsed_key = SigningKey::from_cose(&cose).unwrap();
142
143        assert_eq!(signing_key.to_cose(), parsed_key.to_cose());
144    }
145
146    #[test]
147    fn test_sign_rountrip() {
148        let signing_key = SigningKey::make(SignatureAlgorithm::Ed25519);
149        let signature = signing_key.sign_raw("Test message".as_bytes());
150        let verifying_key = signing_key.to_verifying_key();
151        assert!(
152            verifying_key
153                .verify_raw(&signature, "Test message".as_bytes())
154                .is_ok()
155        );
156    }
157}