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
200
201
202
203
204
205
206
207
208
209
210
211
212
use aes_gcm::aead::{generic_array::GenericArray, Aead, NewAead};
use aes_gcm::Aes256Gcm;

pub enum Cipher {
    Key(Vec<u8>),
    Data(Vec<u8>),
}

impl Cipher {
    pub fn unwrap_key(self) -> Result<Vec<u8>, String> {
        match self {
            Cipher::Key(k) => Ok(k),
            Cipher::Data(_) => Err("This is data, not a key".to_string()),
        }
    }

    pub fn unwrap_data(self) -> Result<Vec<u8>, String> {
        match self {
            Cipher::Data(d) => Ok(d),
            Cipher::Key(_) => Err("This is a key, not data".to_string()),
        }
    }

    /// Do NOT call this unless absolutely sure about the enum type.
    /// Call [`unwrap_key`] or [`unwrap_data`] instead.
    pub fn unwrap(self) -> Vec<u8> {
        match self {
            Cipher::Key(k) => k,
            Cipher::Data(d) => d,
        }
    }

    pub fn unwrap_to_num_string(self) -> String {
        let mut x = String::new();

        match self {
            Cipher::Key(k) => {
                for i in k {
                    x.push_str((i.to_string() + " ").as_str());
                }
                x.pop();
            }
            Cipher::Data(d) => {
                for i in d {
                    x.push_str((i.to_string() + " ").as_str());
                }
                x.pop();
            }
        };

        x
    }

    /// Only call this function when you are sure that the enum contains
    /// decrypted data and is [`Cipher::Data`]
    pub fn unwrap_to_string_from_dat(self) -> Result<String, String> {
        let mut x = String::new();
        let mut y: Result<String, String> = Ok("".to_string());

        match self {
            Cipher::Data(k) => {
                for i in k {
                    x.push(i as char);
                }
            }
            Cipher::Key(_) => y = Err("Not Data".to_string()),
        };

        match y {
            Ok(_) => Ok(x),
            Err(_) => y,
        }
    }
}

pub struct Data {
    key: String,
    nonce: String,
}

impl Data {
    /// `key` should be 32 chars long. `nonce` should be 12 chars long.
    pub fn new(key: &str, nonce: &str) -> Data {
        if key.len() != 32 {
            panic!(format!(
                "Key isn't 32 chars long. It is {} chars long.",
                key.len()
            ))
        }

        if nonce.len() != 12 {
            panic!(format!(
                "Nonce isn't 12 chars long. It is {} chars long.",
                key.len()
            ))
        }

        let tmp = Data {
            key: key.to_string(),
            nonce: nonce.to_string(),
        };

        tmp
    }

    /// Check key and data using [`Cipher`] enum and match
    pub fn encrypt_wkey(&self, data: Vec<u8>) -> (Cipher, Cipher) {
        let key = GenericArray::from_slice(self.key.as_bytes());
        let enc = Aes256Gcm::new(key);

        let non = GenericArray::from_slice(self.nonce.as_bytes());

        let ciphertext = enc
            .encrypt(non, data.as_ref())
            .expect("Encryption of data failed");

        let cipherkey = enc
            .encrypt(non, self.key.as_ref())
            .expect("Encryption of key failed");

        (Cipher::Key(cipherkey), Cipher::Data(ciphertext))
    }

    /// Check key and data using [`Cipher`] enum and match
    pub fn encrypt(&self, data: Vec<u8>) -> Cipher {
        let key = GenericArray::from_slice(self.key.as_bytes());
        let enc = Aes256Gcm::new(key);

        let non = GenericArray::from_slice(self.nonce.as_bytes());

        let ciphertext = enc
            .encrypt(non, data.as_ref())
            .expect("Encryption of data failed");

        Cipher::Data(ciphertext)
    }

    /// data should be [`Vec<u8>`]
    pub fn decrypt(&self, data: Vec<u8>) -> Cipher {
        let key = GenericArray::from_slice(self.key.as_bytes());
        let enc = Aes256Gcm::new(key);

        let non = GenericArray::from_slice(self.nonce.as_bytes());

        let plaintext = enc
            .encrypt(non, data.as_ref())
            .expect("Encryption of data failed");

        Cipher::Data(plaintext)
    }

    /// Direct decryption to string
    pub fn decrypt_to_string(&self, data: Vec<u8>) -> String {
        let key = GenericArray::from_slice(self.key.as_bytes());
        let enc = Aes256Gcm::new(key);

        let non = GenericArray::from_slice(self.nonce.as_bytes());

        let plaintext = enc
            .encrypt(non, data.as_ref())
            .expect("Encryption of data failed");

        let mut out = String::new();

        for i in plaintext {
            out.push(i as char);
        }

        out
    }

    /// Directly encrypts data from string, returns key and data
    pub fn parse_enc_wkey(&self, s: &str, is_str: bool) -> (Cipher, Cipher) {
        let mut tmp: Vec<u8> = Vec::new();
        if is_str {
            for i in s.as_bytes().iter() {
                tmp.push(*i)
            }
        } else {
            tmp = s.split(' ').map(|s| s.parse::<u8>().unwrap()).collect();
        }

        self.encrypt_wkey(tmp)
    }

    /// Directly encrypts data from [`&str`] OR [`Vec<u8>`], returns data only
    pub fn parse_enc(&self, s: &str, is_str: bool) -> Cipher {
        let mut tmp: Vec<u8> = Vec::new();
        if is_str {
            for i in s.as_bytes().iter() {
                tmp.push(*i)
            }
        } else {
            tmp = s.split(' ').map(|s| s.parse::<u8>().unwrap()).collect();
        }

        self.encrypt(tmp)
    }

    pub fn parse_dec(&self, s: &str, is_str: bool) -> Cipher {
        let mut tmp: Vec<u8> = Vec::new();
        if is_str {
            for i in s.as_bytes().iter() {
                tmp.push(*i)
            }
        } else {
            tmp = s.split(' ').map(|s| s.parse::<u8>().unwrap()).collect();
        }

        self.decrypt(tmp)
    }
}