summaryrefslogtreecommitdiffstats
path: root/openpgp/src/crypto/backend/openssl/symmetric.rs
blob: efc27227ed39e8cf79433f404d70a06fd88617de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
use crate::crypto::symmetric::Mode;

use crate::types::SymmetricAlgorithm;
use crate::{Error, Result};

use openssl::cipher::{Cipher, CipherRef};
use openssl::cipher_ctx::CipherCtx;

struct OpenSslMode {
    ctx: CipherCtx,
}

impl OpenSslMode {
    fn new(ctx: CipherCtx) -> Self {
        Self { ctx }
    }
}

impl Mode for OpenSslMode {
    fn block_size(&self) -> usize {
        self.ctx.block_size()
    }

    fn encrypt(&mut self, dst: &mut [u8], src: &[u8]) -> Result<()> {
        // Note that for cipher constructions that OpenSSL considers
        // "streaming" (such as CFB mode) the block size will be
        // always "1" instead of the real block size of the underlying
        // cipher.
        let block_size = self.ctx.block_size();

        // SAFETY: If this is a block cipher we require the source length
        // to be exactly one block long not to populate OpenSSL's
        // cipher cache.
        if block_size > 1 && src.len() != block_size {
            return Err(Error::InvalidArgument("src need to be one block".into()).into());
        }

        // SAFETY: `dst` must be big enough to hold decrypted data.
        if dst.len() < src.len() {
            return Err(Error::InvalidArgument(
                "dst need to be big enough to hold decrypted data".into(),
            )
            .into());
        }

        // SAFETY: This call is safe because either: this is a streaming cipher
        // (block_size == 1) or block cipher (block_size > 1) and `src` is
        // exactly one block and `dst` is big enough to hold the decrypted
        // data.
        unsafe {
            self.ctx.cipher_update_unchecked(src, Some(dst))?;
        }
        eprintln!("src = {src:?}, dst = {dst:?}");
        Ok(())
    }

    fn decrypt(&mut self, dst: &mut [u8], src: &[u8]) -> Result<()> {
        self.encrypt(dst, src)
    }
}

impl SymmetricAlgorithm {
    /// Returns whether this algorithm is supported by the crypto backend.
    pub(crate) fn is_supported_by_backend(&self) -> bool {
        let cipher: &CipherRef = if let Ok(cipher) = (*self).make_cfb_cipher() {
            cipher
        } else {
            return false;
        };

        let mut ctx = if let Ok(ctx) = CipherCtx::new() {
            ctx
        } else {
            return false;
        };
        ctx.encrypt_init(Some(cipher), None, None).is_ok()
    }

    /// Creates a OpenSSL context for encrypting in CFB mode.
    pub(crate) fn make_encrypt_cfb(self, key: &[u8], iv: Vec<u8>) -> Result<Box<dyn Mode>> {
        let cipher = self.make_cfb_cipher()?;
        let mut ctx = CipherCtx::new()?;
        eprintln!("IV = ({}) {:?}", iv.len(), iv);
        eprintln!("Key = ({}) {:?}", key.len(), key);
        ctx.encrypt_init(Some(cipher), Some(key), Some(&iv))?;
        Ok(Box::new(OpenSslMode::new(ctx)))
    }

    /// Creates a OpenSSL context for decrypting in CFB mode.
    pub(crate) fn make_decrypt_cfb(self, key: &[u8], iv: Vec<u8>) -> Result<Box<dyn Mode>> {
        let cipher = self.make_cfb_cipher()?;
        let mut ctx = CipherCtx::new()?;
        eprintln!("IV = ({}) {:?}", iv.len(), iv);
        eprintln!("Key = ({}) {:?}", key.len(), key);
        ctx.decrypt_init(Some(cipher), Some(key), Some(&iv))?;
        Ok(Box::new(OpenSslMode::new(ctx)))
    }

    /// Creates a OpenSSL context for encrypting in ECB mode.
    pub(crate) fn make_encrypt_ecb(self, key: &[u8]) -> Result<Box<dyn Mode>> {
        let cipher = self.make_ecb_cipher()?;
        let mut ctx = CipherCtx::new()?;
        ctx.encrypt_init(Some(cipher), Some(key), None)?;
        ctx.set_padding(false);
        Ok(Box::new(OpenSslMode::new(ctx)))
    }

    /// Creates a OpenSSL context for decrypting in ECB mode.
    pub(crate) fn make_decrypt_ecb(self, key: &[u8]) -> Result<Box<dyn Mode>> {
        let cipher = self.make_ecb_cipher()?;
        let mut ctx = CipherCtx::new()?;
        ctx.decrypt_init(Some(cipher), Some(key), None)?;
        ctx.set_padding(false);
        Ok(Box::new(OpenSslMode::new(ctx)))
    }

    fn make_cfb_cipher(self) -> Result<&'static CipherRef> {
        Ok(match self {
            #[cfg(not(osslconf = "OPENSSL_NO_IDEA"))]
            SymmetricAlgorithm::IDEA => Cipher::idea_cfb64(),

            SymmetricAlgorithm::AES128 => Cipher::aes_128_cfb128(),
            SymmetricAlgorithm::AES192 => Cipher::aes_192_cfb128(),
            SymmetricAlgorithm::AES256 => Cipher::aes_256_cfb128(),

            SymmetricAlgorithm::TripleDES => Cipher::des_ede3_cfb64(),

            #[cfg(not(osslconf = "OPENSSL_NO_CAMELLIA"))]
            SymmetricAlgorithm::Camellia128 => Cipher::camellia128_cfb128(),
            #[cfg(not(osslconf = "OPENSSL_NO_CAMELLIA"))]
            SymmetricAlgorithm::Camellia192 => Cipher::camellia192_cfb128(),
            #[cfg(not(osslconf = "OPENSSL_NO_CAMELLIA"))]
            SymmetricAlgorithm::Camellia256 => Cipher::camellia256_cfb128(),

            #[cfg(not(osslconf = "OPENSSL_NO_BF"))]
            SymmetricAlgorithm::Blowfish => Cipher::bf_cfb64(),

            #[cfg(not(osslconf = "OPENSSL_NO_CAST"))]
            SymmetricAlgorithm::CAST5 => Cipher::cast5_cfb64(),
            _ => return Err(Error::UnsupportedSymmetricAlgorithm(self))?,
        })
    }

    fn make_ecb_cipher(self) -> Result<&'static CipherRef> {
        Ok(match self {
            #[cfg(not(osslconf = "OPENSSL_NO_IDEA"))]
            SymmetricAlgorithm::IDEA => Cipher::idea_ecb(),

            SymmetricAlgorithm::AES128 => Cipher::aes_128_ecb(),
            SymmetricAlgorithm::AES192 => Cipher::aes_192_ecb(),
            SymmetricAlgorithm::AES256 => Cipher::aes_256_ecb(),

            SymmetricAlgorithm::TripleDES => Cipher::des_ecb(),

            #[cfg(not(osslconf = "OPENSSL_NO_CAMELLIA"))]
            SymmetricAlgorithm::Camellia128 => Cipher::camellia128_ecb(),
            #[cfg(not(osslconf = "OPENSSL_NO_CAMELLIA"))]
            SymmetricAlgorithm::Camellia192 => Cipher::camellia192_ecb(),
            #[cfg(not(osslconf = "OPENSSL_NO_CAMELLIA"))]
            SymmetricAlgorithm::Camellia256 => Cipher::camellia256_ecb(),

            #[cfg(not(osslconf = "OPENSSL_NO_BF"))]
            SymmetricAlgorithm::Blowfish => Cipher::bf_ecb(),

            #[cfg(not(osslconf = "OPENSSL_NO_CAST"))]
            SymmetricAlgorithm::CAST5 => Cipher::cast5_ecb(),
            _ => Err(Error::UnsupportedSymmetricAlgorithm(self))?,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Anchors the constants used in Sequoia with the ones from
    /// OpenSSL.
    #[test]
    fn key_size() -> Result<()> {
        for a in SymmetricAlgorithm::variants() {
            if let Ok(cipher) = a.make_cfb_cipher() {
                assert_eq!(a.key_size()?, cipher.key_length());
            }
        }
        Ok(())
    }

    /// Anchors the constants used in Sequoia with the ones from
    /// OpenSSL.
    #[test]
    fn block_size() -> Result<()> {
        for a in SymmetricAlgorithm::variants() {