askar_crypto/
repr.rs

1//! Traits for exposing key data representations
2
3#[cfg(feature = "alloc")]
4use crate::buffer::SecretBytes;
5use crate::{
6    buffer::WriteBuffer,
7    error::Error,
8    generic_array::{typenum::Unsigned, ArrayLength},
9    random::KeyMaterial,
10};
11
12/// Raw key generation operations
13pub trait KeyGen: Sized {
14    /// Create a new key from a key material generator.
15    fn generate(rng: impl KeyMaterial) -> Result<Self, Error>;
16
17    /// Generate a new random key.
18    #[cfg(feature = "getrandom")]
19    fn random() -> Result<Self, Error> {
20        Self::generate(crate::random::default_rng())
21    }
22}
23
24/// Convert between key instance and key secret bytes
25pub trait KeySecretBytes: KeyMeta {
26    /// Create a new key instance from a slice of key secret bytes.
27    fn from_secret_bytes(key: &[u8]) -> Result<Self, Error>
28    where
29        Self: Sized;
30
31    /// Access a temporary slice of the key secret bytes, if any.
32    fn with_secret_bytes<O>(&self, f: impl FnOnce(Option<&[u8]>) -> O) -> O;
33}
34
35/// Object-safe trait for exporting key secret bytes
36pub trait ToSecretBytes {
37    /// Get the length of a secret key
38    fn secret_bytes_length(&self) -> Result<usize, Error>;
39
40    /// Write the key secret bytes to a buffer.
41    fn write_secret_bytes(&self, out: &mut dyn WriteBuffer) -> Result<(), Error>;
42
43    #[cfg(feature = "alloc")]
44    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
45    /// Write the key secret bytes to a new allocated buffer.
46    fn to_secret_bytes(&self) -> Result<SecretBytes, Error> {
47        let mut buf = SecretBytes::with_capacity(128);
48        self.write_secret_bytes(&mut buf)?;
49        Ok(buf)
50    }
51}
52
53impl<K> ToSecretBytes for K
54where
55    K: KeySecretBytes,
56{
57    fn secret_bytes_length(&self) -> Result<usize, Error> {
58        Ok(<Self as KeyMeta>::KeySize::USIZE)
59    }
60
61    fn write_secret_bytes(&self, out: &mut dyn WriteBuffer) -> Result<(), Error> {
62        self.with_secret_bytes(|buf| {
63            if let Some(buf) = buf {
64                out.buffer_write(buf)
65            } else {
66                Err(err_msg!(MissingSecretKey))
67            }
68        })
69    }
70}
71
72/// Convert between key instance and key public bytes.
73pub trait KeyPublicBytes: KeypairMeta {
74    /// Create a new key instance from a slice of public key bytes.
75    fn from_public_bytes(key: &[u8]) -> Result<Self, Error>
76    where
77        Self: Sized;
78
79    /// Access a temporary slice of the key public bytes.
80    fn with_public_bytes<O>(&self, f: impl FnOnce(&[u8]) -> O) -> O;
81}
82
83/// Object-safe trait for exporting key public bytes
84pub trait ToPublicBytes {
85    /// Get the length of a public key
86    fn public_bytes_length(&self) -> Result<usize, Error>;
87
88    /// Write the key public bytes to a buffer.
89    fn write_public_bytes(&self, out: &mut dyn WriteBuffer) -> Result<(), Error>;
90
91    #[cfg(feature = "alloc")]
92    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
93    /// Write the key public bytes to a new allocated buffer.
94    fn to_public_bytes(&self) -> Result<SecretBytes, Error> {
95        let mut buf = SecretBytes::with_capacity(128);
96        self.write_public_bytes(&mut buf)?;
97        Ok(buf)
98    }
99}
100
101impl<K> ToPublicBytes for K
102where
103    K: KeyPublicBytes,
104{
105    fn public_bytes_length(&self) -> Result<usize, Error> {
106        Ok(<Self as KeypairMeta>::PublicKeySize::USIZE)
107    }
108
109    fn write_public_bytes(&self, out: &mut dyn WriteBuffer) -> Result<(), Error> {
110        self.with_public_bytes(|buf| out.buffer_write(buf))
111    }
112}
113
114/// Convert between keypair instance and keypair (secret and public) bytes
115pub trait KeypairBytes {
116    /// Create a new key instance from a slice of keypair bytes.
117    fn from_keypair_bytes(key: &[u8]) -> Result<Self, Error>
118    where
119        Self: Sized;
120
121    /// Create a new key instance from a slice of keypair bytes.
122    fn with_keypair_bytes<O>(&self, f: impl FnOnce(Option<&[u8]>) -> O) -> O;
123
124    /// Write the keypair bytes to a buffer.
125    fn to_keypair_bytes_buffer<B: WriteBuffer>(&self, out: &mut B) -> Result<(), Error> {
126        self.with_keypair_bytes(|buf| {
127            if let Some(buf) = buf {
128                out.buffer_write(buf)
129            } else {
130                Err(err_msg!(MissingSecretKey))
131            }
132        })
133    }
134
135    #[cfg(feature = "alloc")]
136    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
137    /// Write the keypair bytes to a new allocated buffer.
138    fn to_keypair_bytes(&self) -> Result<SecretBytes, Error> {
139        let mut buf = SecretBytes::with_capacity(128);
140        self.to_keypair_bytes_buffer(&mut buf)?;
141        Ok(buf)
142    }
143}
144
145/// For concrete secret key types
146pub trait KeyMeta {
147    /// The size of the key secret bytes
148    type KeySize: ArrayLength<u8>;
149}
150
151/// For concrete secret + public key types
152pub trait KeypairMeta: KeyMeta {
153    /// The size of the key public bytes
154    type PublicKeySize: ArrayLength<u8>;
155    /// The size of the secret bytes and public bytes combined
156    type KeypairSize: ArrayLength<u8>;
157}