Skip to main content

rtci_crypto/
traits.rs

1use std::sync::Arc;
2
3use crate::{
4    AeadAlgorithm, BlockCipherAlgorithm, CbcAlgorithm, CryptoAlgorithm, CryptoError, HashAlgorithm,
5    HeaderMaskAlgorithm, HmacAlgorithm, KeyExchangeAlgorithm, PublicKey, SecretVec,
6    SignatureScheme, StreamCipherAlgorithm,
7};
8
9/// A bundle of cryptographic operations and cryptographically secure randomness.
10pub trait RTCCryptoProvider: Send + Sync {
11    /// Returns a non-secret diagnostic name.
12    fn name(&self) -> &'static str;
13
14    /// Returns the cryptographic operations implementation.
15    fn crypto(&self) -> &dyn RTCCrypto;
16
17    /// Returns the cryptographically secure random source.
18    fn random(&self) -> &dyn RTCRandom;
19}
20
21/// A cryptographically secure random byte generator.
22pub trait RTCRandom: Send + Sync {
23    /// Fills all of `output` with random bytes.
24    fn fill(&self, output: &mut [u8]) -> Result<(), CryptoError>;
25}
26
27/// Provider-neutral cryptographic operations.
28pub trait RTCCrypto: Send + Sync {
29    /// Reports whether an operation is implemented.
30    fn supports(&self, algorithm: CryptoAlgorithm) -> bool;
31
32    /// Hashes `data`.
33    fn hash(&self, algorithm: HashAlgorithm, _data: &[u8]) -> Result<Vec<u8>, CryptoError> {
34        Err(CryptoError::UnsupportedAlgorithm(CryptoAlgorithm::Hash(
35            algorithm,
36        )))
37    }
38
39    /// Encrypts exactly one block in place.
40    fn block_encrypt(
41        &self,
42        algorithm: BlockCipherAlgorithm,
43        _key: &[u8],
44        _block: &mut [u8],
45    ) -> Result<(), CryptoError> {
46        Err(CryptoError::UnsupportedAlgorithm(
47            CryptoAlgorithm::BlockCipher(algorithm),
48        ))
49    }
50
51    /// Creates a keyed MAC.
52    ///
53    /// This is the only HMAC entry point. Deriving the key schedule is the expensive part, so it
54    /// happens here rather than per message; a caller that authenticates many messages with one
55    /// key holds the returned [`Mac`]. One-shot callers simply drop it after a single `sign` or
56    /// `verify`.
57    fn new_hmac(&self, algorithm: HmacAlgorithm, _key: &[u8]) -> Result<Box<dyn Mac>, CryptoError> {
58        Err(CryptoError::UnsupportedAlgorithm(CryptoAlgorithm::Hmac(
59            algorithm,
60        )))
61    }
62
63    /// Creates a keyed stream cipher.
64    fn new_stream_cipher(
65        &self,
66        algorithm: StreamCipherAlgorithm,
67        _key: &[u8],
68    ) -> Result<Box<dyn StreamCipher>, CryptoError> {
69        Err(CryptoError::UnsupportedAlgorithm(
70            CryptoAlgorithm::StreamCipher(algorithm),
71        ))
72    }
73
74    /// Creates a keyed AEAD cipher.
75    fn new_aead(
76        &self,
77        algorithm: AeadAlgorithm,
78        _key: &[u8],
79    ) -> Result<Box<dyn AeadCipher>, CryptoError> {
80        Err(CryptoError::UnsupportedAlgorithm(CryptoAlgorithm::Aead(
81            algorithm,
82        )))
83    }
84
85    /// Creates a keyed record-number mask generator (RFC 9147 section 4.2.3).
86    fn new_header_mask(
87        &self,
88        algorithm: HeaderMaskAlgorithm,
89        _key: &[u8],
90    ) -> Result<Box<dyn HeaderMask>, CryptoError> {
91        Err(CryptoError::UnsupportedAlgorithm(
92            CryptoAlgorithm::HeaderMask(algorithm),
93        ))
94    }
95
96    /// Creates a keyed CBC cipher.
97    fn new_cbc(
98        &self,
99        algorithm: CbcAlgorithm,
100        _key: &[u8],
101    ) -> Result<Box<dyn CbcCipher>, CryptoError> {
102        Err(CryptoError::UnsupportedAlgorithm(CryptoAlgorithm::Cbc(
103            algorithm,
104        )))
105    }
106
107    /// Starts a one-shot ephemeral key exchange.
108    fn start_key_exchange(
109        &self,
110        algorithm: KeyExchangeAlgorithm,
111    ) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
112        Err(CryptoError::UnsupportedAlgorithm(
113            CryptoAlgorithm::KeyExchange(algorithm),
114        ))
115    }
116
117    /// Answers a key exchange the peer started: makes this side's share for `peer_share`
118    /// and the shared secret. For the Diffie-Hellman groups that is a key pair and an
119    /// agreement, which is what the default does; a KEM-based group (X25519MLKEM768)
120    /// encapsulates to the peer's key instead, and its provider overrides this.
121    fn key_exchange_respond(
122        &self,
123        algorithm: KeyExchangeAlgorithm,
124        peer_share: &[u8],
125    ) -> Result<(Vec<u8>, SecretVec), CryptoError> {
126        let exchange = self.start_key_exchange(algorithm)?;
127        let share = exchange.public_key().to_vec();
128        let secret = exchange.complete(peer_share)?;
129        Ok((share, secret))
130    }
131
132    /// Generates an exportable signing key.
133    fn generate_signing_key(
134        &self,
135        scheme: SignatureScheme,
136    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
137        Err(CryptoError::UnsupportedAlgorithm(
138            CryptoAlgorithm::SigningKeyGeneration(scheme),
139        ))
140    }
141
142    /// Imports an exportable PKCS#8 signing key.
143    fn import_signing_key(
144        &self,
145        scheme: SignatureScheme,
146        _pkcs8_der: &[u8],
147    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
148        Err(CryptoError::UnsupportedAlgorithm(
149            CryptoAlgorithm::SigningKeyImport(scheme),
150        ))
151    }
152
153    /// Verifies a signature.
154    fn verify_signature(
155        &self,
156        scheme: SignatureScheme,
157        _public_key: PublicKey<'_>,
158        _message: &[u8],
159        _signature: &[u8],
160    ) -> Result<(), CryptoError> {
161        Err(CryptoError::UnsupportedAlgorithm(
162            CryptoAlgorithm::Signature(scheme),
163        ))
164    }
165}
166
167/// A keyed message authentication code with a reusable key schedule.
168///
169/// Created once per key by [`RTCCrypto::new_hmac`] and used for every message authenticated with
170/// that key, so the ipad/opad derivation is paid once rather than per packet.
171///
172/// `Send` and mutable, like the keyed cipher traits, and for the same reason: `&mut self` lets an
173/// implementation carry per-message state — a reused streaming context, a hardware session
174/// handle — without interior mutability, and does not impose `Sync` on implementors that cannot
175/// offer it. A caller whose own signature is fixed to `&self`, such as STUN's `Setter::add_to`,
176/// can still create a local `Mac` per message and use it mutably.
177pub trait Mac: Send {
178    /// Returns the untruncated tag length in bytes.
179    fn output_len(&self) -> usize;
180
181    /// Writes the tag over the concatenation of `input` into `output`.
182    ///
183    /// `output` must be exactly [`output_len`](Self::output_len) bytes. Protocols that transmit a
184    /// truncated tag — SRTP sends 80 or 32 bits of an SHA-1 tag — truncate the result themselves.
185    fn sign(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<(), CryptoError>;
186
187    /// Verifies a complete untruncated tag in constant time.
188    fn verify(&mut self, input: &[&[u8]], expected: &[u8]) -> Result<(), CryptoError>;
189}
190
191/// A keyed stream cipher with a reusable expanded key.
192pub trait StreamCipher: Send {
193    /// Applies the keystream in place with a fresh IV.
194    fn apply_keystream(&mut self, iv: &[u8], data: &mut [u8]) -> Result<(), CryptoError>;
195}
196
197/// A keyed authenticated cipher with detached tags.
198pub trait AeadCipher: Send {
199    /// Returns the detached tag length in bytes.
200    fn tag_len(&self) -> usize;
201
202    /// Encrypts and authenticates a caller-owned buffer.
203    fn seal_in_place(
204        &mut self,
205        nonce: &[u8],
206        aad: &[u8],
207        plaintext_and_ciphertext: &mut [u8],
208        tag_out: &mut [u8],
209    ) -> Result<(), CryptoError>;
210
211    /// Authenticates and decrypts a caller-owned buffer.
212    fn open_in_place(
213        &mut self,
214        nonce: &[u8],
215        aad: &[u8],
216        ciphertext_and_plaintext: &mut [u8],
217        tag: &[u8],
218    ) -> Result<(), CryptoError>;
219}
220
221/// The length of the ciphertext sample a [`HeaderMask`] is computed from.
222pub const HEADER_MASK_SAMPLE_LEN: usize = 16;
223/// The length of the mask a [`HeaderMask`] returns.
224pub const HEADER_MASK_LEN: usize = 5;
225
226/// A keyed generator of record-number masks.
227///
228/// DTLS 1.3 encrypts the sequence number of a protected record by XORing it with the leading
229/// bytes of a mask computed from the first 16 bytes of the record's ciphertext (RFC 9147
230/// section 4.2.3): AES-ECB of the sample for the AES suites, and for ChaCha20 the keystream
231/// the block function gives with the sample's first four bytes as the block counter and the
232/// other twelve as the nonce. QUIC header protection (RFC 9001 section 5.4) is the same
233/// computation, which is why five bytes come back; DTLS uses one or two of them.
234pub trait HeaderMask: Send {
235    /// Computes the mask for `sample`.
236    fn mask(
237        &mut self,
238        sample: &[u8; HEADER_MASK_SAMPLE_LEN],
239    ) -> Result<[u8; HEADER_MASK_LEN], CryptoError>;
240}
241
242/// A keyed CBC block cipher with a reusable expanded key.
243pub trait CbcCipher: Send {
244    /// Returns the block and IV length in bytes.
245    fn block_len(&self) -> usize;
246
247    /// Encrypts whole blocks in place without applying padding.
248    fn encrypt_blocks(&mut self, iv: &[u8], blocks: &mut [u8]) -> Result<(), CryptoError>;
249
250    /// Decrypts whole blocks in place without removing padding.
251    fn decrypt_blocks(&mut self, iv: &[u8], blocks: &mut [u8]) -> Result<(), CryptoError>;
252}
253
254/// Provider-owned one-shot ephemeral key exchange.
255pub trait ActiveKeyExchange: Send {
256    /// Returns the key-exchange algorithm.
257    fn algorithm(&self) -> KeyExchangeAlgorithm;
258
259    /// Returns the encoded wire public key.
260    fn public_key(&self) -> &[u8];
261
262    /// Consumes the private key and derives the shared secret.
263    fn complete(self: Box<Self>, peer_public_key: &[u8]) -> Result<SecretVec, CryptoError>;
264}
265
266/// A provider-owned signing key, including external or non-exportable keys.
267pub trait SigningKey: Send + Sync {
268    /// Reports whether this key can sign with `scheme`.
269    fn supports(&self, scheme: SignatureScheme) -> bool;
270
271    /// Returns the public key with explicit encoding.
272    fn public_key(&self) -> PublicKey<'_>;
273
274    /// Signs `message`.
275    fn sign(&self, scheme: SignatureScheme, message: &[u8]) -> Result<Vec<u8>, CryptoError>;
276
277    /// Exports PKCS#8 when supported. `Ok(None)` means the key is non-exportable.
278    fn to_pkcs8_der(&self) -> Result<Option<SecretVec>, CryptoError> {
279        Ok(None)
280    }
281}