Skip to main content

otplus_core/
lib.rs

1pub mod cipher;
2pub use cipher::Cipher;
3pub use cipher::RootKey;
4pub use cipher::RootKeyMetadata;
5pub use cipher::DerivedKey;
6pub mod header;
7pub mod helpers;
8pub use helpers::Helpers;
9
10#[cfg(test)]
11mod lib_tests {
12  use super::*;
13  use chacha20poly1305::{aead::{OsRng, AeadCore}, ChaCha20Poly1305};
14
15  #[test]
16  fn test_cipher() {
17    let cipher = Cipher::default();
18    let plaintext = b"hello world";
19    let ciphertext = cipher.encrypt(plaintext);
20    let decrypted = cipher.decrypt(&ciphertext);
21    assert_eq!(plaintext, decrypted.as_slice());
22  }
23
24  #[test]
25  fn test_full_flow() {
26    // Passphrase from user
27    let passphrase = "password";
28
29    // Root key is a 32 byte key used to encrypt and decrypt user data (randomly generated)
30    let root_key = RootKey::default();
31
32    // Key use to encrypt root key (derived from passphrase)
33    let derived_key = DerivedKey::new(passphrase.to_string(), vec![0; 16], 32);
34
35    // Encrypt root key with derived key
36    let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng::default());
37
38    let cipher = Cipher::new(derived_key.get_value(), nonce);
39
40    let encrypted_root_key = cipher.encrypt(root_key.value.as_slice());
41
42    let base64_root_key = Helpers::base64_encode(&encrypted_root_key);
43    println!("Root key encrypted: {:?}", base64_root_key);
44
45    let decrypted_root_key = cipher.decrypt(&encrypted_root_key);
46    println!("Root key decrypted: {:?}", decrypted_root_key);
47    assert_eq!(root_key.value.as_slice(), decrypted_root_key.as_slice());
48  }
49}