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