literate_crypto/cipher.rs
1use docext::docext;
2
3mod block;
4mod onetimepad;
5
6pub use {
7 block::{
8 aes,
9 Aes128,
10 Aes192,
11 Aes256,
12 BlockCipher,
13 BlockDecrypt,
14 BlockEncrypt,
15 BlockMode,
16 BlockSizeTooSmall,
17 Cbc,
18 Ctr,
19 Ecb,
20 Padding,
21 Pkcs7,
22 },
23 onetimepad::OneTimePad,
24};
25
26/// A cipher encrypts and decrypts data of arbitrary length using a symmetric
27/// key.
28///
29/// The encrypted data is called ciphertext, and the unencrypted data is called
30/// plaintext. Ciphertext should be statistically indistinguishable from random
31/// data.
32///
33/// The following relation must hold between the encrypt and decrypt methods:
34/// $$
35/// decrypt(encrypt(p, k), k) = p \quad \forall p \in \mathbf{P}, k \in
36/// \mathbf{K}
37/// $$
38///
39/// where $\mathbf{P}$ is the set of all possible plaintexts (plaintext space)
40/// and $\mathbf{K}$ is the set of all possible keys (key space). Note that the
41/// key space usually has a fixed size, while the plaintext space is infinite.
42#[docext]
43pub trait Cipher:
44 CipherEncrypt<EncryptionKey = Self::Key> + CipherDecrypt<DecryptionKey = Self::Key>
45{
46 type Key;
47}
48
49/// The encryption half of a [cipher](Cipher).
50pub trait CipherEncrypt {
51 type EncryptionErr;
52 type EncryptionKey;
53
54 /// Encrypt the plaintext.
55 fn encrypt(
56 &self,
57 data: Vec<u8>,
58 key: Self::EncryptionKey,
59 ) -> Result<Vec<u8>, Self::EncryptionErr>;
60}
61
62/// The decryption half of a [cipher](Cipher).
63pub trait CipherDecrypt {
64 type DecryptionErr;
65 type DecryptionKey;
66
67 /// Decrypt the ciphertext. This operation can fail, for example, if the
68 /// ciphertext was not created by this cipher.
69 fn decrypt(
70 &self,
71 data: Vec<u8>,
72 key: Self::DecryptionKey,
73 ) -> Result<Vec<u8>, Self::DecryptionErr>;
74}