aboutsummaryrefslogtreecommitdiffstats
path: root/src/cipherstring.rs
blob: 2398b070e8bfe0174a161a6aac949e39e101dbe0 (plain) (blame)
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
use crate::prelude::*;

use block_modes::BlockMode as _;
use hmac::Mac as _;
use rand::RngCore as _;

pub struct CipherString {
    ty: u8,
    iv: Vec<u8>,
    ciphertext: Vec<u8>,
    mac: Option<Vec<u8>>,
}

impl CipherString {
    pub fn new(s: &str) -> Result<Self> {
        let parts: Vec<&str> = s.split('.').collect();
        if parts.len() != 2 {
            return Err(Error::InvalidCipherString);
        }

        let ty = parts[0].as_bytes();
        if ty.len() != 1 {
            return Err(Error::InvalidCipherString);
        }

        let ty = ty[0] - b'0';
        let contents = parts[1];

        let parts: Vec<&str> = contents.split('|').collect();
        if parts.len() < 2 || parts.len() > 3 {
            return Err(Error::InvalidCipherString);
        }

        let iv =
            base64::decode(parts[0]).context(crate::error::InvalidBase64)?;
        let ciphertext =
            base64::decode(parts[1]).context(crate::error::InvalidBase64)?;
        let mac = if parts.len() > 2 {
            Some(
                base64::decode(parts[2])
                    .context(crate::error::InvalidBase64)?,
            )
        } else {
            None
        };

        Ok(Self {
            ty,
            iv,
            ciphertext,
            mac,
        })
    }

    pub fn encrypt(
        keys: &crate::locked::Keys,
        plaintext: &[u8],
    ) -> Result<Self> {
        let iv = random_iv();

        let cipher = block_modes::Cbc::<
            aes::Aes256,
            block_modes::block_padding::Pkcs7,
        >::new_var(keys.enc_key(), &iv)
        .context(crate::error::CreateBlockMode)?;
        let ciphertext = cipher.encrypt_vec(plaintext);

        let mut digest =
            hmac::Hmac::<sha2::Sha256>::new_varkey(keys.mac_key())
                .map_err(|_| Error::InvalidMacKey)?;
        digest.input(&iv);
        digest.input(&ciphertext);
        let mac = digest.result().code().to_vec();

        Ok(Self {
            ty: 2,
            iv,
            ciphertext,
            mac: Some(mac),
        })
    }

    pub fn decrypt(&self, keys: &crate::locked::Keys) -> Result<Vec<u8>> {
        let cipher = self.decrypt_common(keys)?;
        cipher
            .decrypt_vec(&self.ciphertext)
            .context(crate::error::Decrypt)
    }

    pub fn decrypt_locked(
        &self,
        keys: &crate::locked::Keys,
    ) -> Result<crate::locked::Vec> {
        let mut res = crate::locked::Vec::new();
        res.extend(self.ciphertext.iter().copied());
        let cipher = self.decrypt_common(keys)?;
        cipher
            .decrypt(res.data_mut())
            .context(crate::error::Decrypt)?;
        Ok(res)
    }

    fn decrypt_common(
        &self,
        keys: &crate::locked::Keys,
    ) -> Result<
        block_modes::Cbc<aes::Aes256, block_modes::block_padding::Pkcs7>,
    > {
        if self.ty != 2 {
            unimplemented!()
        }

        if let Some(mac) = &self.mac {
            let mut digest =
                hmac::Hmac::<sha2::Sha256>::new_varkey(keys.mac_key())
                    .map_err(|_| Error::InvalidMacKey)?;
            digest.input(&self.iv);
            digest.input(&self.ciphertext);
            let calculated_mac = digest.result().code();

            if !macs_equal(mac, &calculated_mac, keys.mac_key())? {
                return Err(Error::InvalidMac);
            }
        }

        Ok(block_modes::Cbc::<
            aes::Aes256,
            block_modes::block_padding::Pkcs7,
        >::new_var(keys.enc_key(), &self.iv)
        .context(crate::error::CreateBlockMode)?)
    }
}

impl std::fmt::Display for CipherString {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let iv = base64::encode(&self.iv);
        let ciphertext = base64::encode(&self.ciphertext);
        if let Some(mac) = &self.mac {
            let mac = base64::encode(&mac);
            write!(f, "{}.{}|{}|{}", self.ty, iv, ciphertext, mac)
        } else {
            write!(f, "{}.{}|{}", self.ty, iv, ciphertext)
        }
    }
}

fn macs_equal(mac1: &[u8], mac2: &[u8], mac_key: &[u8]) -> Result<bool> {
    let mut digest = hmac::Hmac::<sha2::Sha256>::new_varkey(mac_key)
        .map_err(|_| Error::InvalidMacKey)?;
    digest.input(mac1);
    let hmac1 = digest.result().code();

    let mut digest = hmac::Hmac::<sha2::Sha256>::new_varkey(mac_key)
        .map_err(|_| Error::InvalidMacKey)?;
    digest.input(mac2);
    let hmac2 = digest.result().code();

    Ok(hmac1 == hmac2)
}

fn random_iv() -> Vec<u8> {
    let mut iv = vec![0_u8; 16];
    let mut rng = rand::thread_rng();
    rng.fill_bytes(&mut iv);
    iv
}