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
use displaydoc::Display;
use hmac::crypto_mac;
use rand::{rngs::OsRng, RngCore};
use serde_repr::{Deserialize_repr as DeserializeRepr, Serialize_repr as SerializeRepr};
use std::{num::ParseIntError, string::FromUtf8Error};
use thiserror::Error;
pub use cipher_string::CipherString;
pub use keys::Keys;
pub use master_password_hash::MasterPasswordHash;
pub use source_key::SourceKey;
mod cipher_string;
mod keys;
mod master_password_hash;
mod source_key;
#[derive(Debug, Display, Error)]
pub enum CipherParseError {
UnsupportedEncryptionType,
IvNotFound,
CiphertextNotFound,
MacNotFound,
InvalidIvLength,
InvalidMacKeyLength,
ParseType(#[from] ParseIntError),
Decode(#[from] base64::DecodeError),
}
#[derive(Debug, Clone, Display, Error)]
pub enum CipherDecryptionError {
MacVerification(#[from] crypto_mac::MacError),
BlockMode(#[from] block_modes::BlockModeError),
}
#[derive(Debug, Clone, Error)]
pub enum CipherDecryptionStringError {
#[error(transparent)]
Other(#[from] CipherDecryptionError),
#[error("Decrypted data contains invalid UTF-8")]
InvalidUtf8(#[from] FromUtf8Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, SerializeRepr, DeserializeRepr)]
#[repr(u8)]
pub enum KdfType {
Pbkdf2Sha256 = 0,
}
pub(crate) fn generate_iv() -> [u8; 16] {
let mut iv = [0; 16];
OsRng.fill_bytes(&mut iv);
iv
}
pub fn generate_protected_symmetric_key(source_key: &SourceKey) -> CipherString {
let (enc, mac) = source_key.expand();
let keys = Keys::generate();
CipherString::encrypt(keys.into_vec(), &enc, &mac)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encrypt_decrypt() {
let keys = Keys::generate();
let plaintext = "test123";
let encrypted = CipherString::encrypt_with_keys(plaintext, &keys);
let decrypted = encrypted.decrypt_with_keys(&keys).unwrap();
assert_eq!(plaintext, decrypted);
}
}