iop_keyvault/ed25519/
sk.rs

1use super::*;
2
3/// The size of the private key in the format used by [`to_bytes`]
4///
5/// [`to_bytes`]: #method.to_bytes
6pub const PRIVATE_KEY_SIZE: usize = ed::SECRET_KEY_LENGTH;
7
8/// Implementation of Ed25519::PrivateKey
9pub struct EdPrivateKey(ed::Keypair);
10
11impl EdPrivateKey {
12    /// The private key serialized in a format that can be fed to [`from_bytes`]
13    ///
14    /// [`from_bytes`]: #method.from_bytes
15    pub fn to_bytes(&self) -> Vec<u8> {
16        let mut res = Vec::with_capacity(PRIVATE_KEY_SIZE);
17        res.extend_from_slice(self.0.secret.as_bytes());
18        res
19    }
20
21    /// Creates a public key from a byte slice possibly returned by the [`to_bytes`] method.
22    ///
23    /// # Error
24    /// If `bytes` is rejected by `ed25519_dalek::SecretKey::from_bytes`
25    ///
26    /// [`to_bytes`]: #method.to_bytes
27    pub fn from_bytes<D: AsRef<[u8]>>(bytes: D) -> Result<Self> {
28        let secret = ed::SecretKey::from_bytes(bytes.as_ref())?;
29        let public = ed::PublicKey::from(&secret);
30        let key_pair = ed::Keypair { secret, public };
31        Ok(Self(key_pair))
32    }
33}
34
35impl Clone for EdPrivateKey {
36    fn clone(&self) -> Self {
37        let secret_bytes = self.0.secret.as_bytes();
38        let public_bytes = self.0.public.as_bytes();
39        let secret = ed::SecretKey::from_bytes(secret_bytes).unwrap();
40        let public = ed::PublicKey::from_bytes(public_bytes).unwrap();
41        Self(ed::Keypair { secret, public })
42    }
43}
44
45impl PrivateKey<Ed25519> for EdPrivateKey {
46    fn public_key(&self) -> EdPublicKey {
47        let pk = self.0.public;
48        pk.into()
49    }
50    fn sign<D: AsRef<[u8]>>(&self, data: D) -> EdSignature {
51        let sig = self.0.sign(data.as_ref());
52        sig.into()
53    }
54}
55
56impl From<ed::Keypair> for EdPrivateKey {
57    fn from(sk: ed::Keypair) -> Self {
58        Self(sk)
59    }
60}
61
62impl From<EdPrivateKey> for ed::Keypair {
63    fn from(sk: EdPrivateKey) -> ed::Keypair {
64        sk.0
65    }
66}