Browse Source

encoder++

fix-typo
Coin de Gamma 3 months ago
parent
commit
3cea889755
  1. 3
      Cargo.toml
  2. 49
      src/encoder.rs

3
Cargo.toml

@ -6,9 +6,10 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
base64 = "0.22.1"
aes-gcm = "0.10.3"
clap = { version = "4.5.16", features = ["derive"] }
hex = "0.4.3"
once_cell = "1.19.0"
rpassword = "7.3.1"
tempfile = "3.12.0"

49
src/encoder.rs

@ -1,3 +1,8 @@
use aes_gcm::{
aead::{Aead, AeadCore, KeyInit, OsRng},
Aes256Gcm, Key, Nonce
};
use std::io;
@ -25,20 +30,52 @@ impl Encoder {
result
}
// TODO: get by ref
pub fn encode(&self, line: &String) -> String {
return line.clone();
// TODO: error type
// TODO: rename to encrypt
pub fn encode(&self, plain_text: &String) -> String {
let key = Key::<Aes256Gcm>::from_slice(self.passphrase.as_bytes());
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
let cipher = Aes256Gcm::new(key);
// TODO: mar error inted of expect
let ciphered_data = cipher.encrypt(&nonce, plain_text.as_bytes())
.expect("failed to encrypt");
// combining nonce and encrypted data together
// for storage purpose
let mut encrypted_data: Vec<u8> = nonce.to_vec();
encrypted_data.extend_from_slice(&ciphered_data);
hex::encode(encrypted_data)
}
// TODO: review error type
pub fn decode(&self, line: String) -> io::Result<String> {
// TODO: rename to decrypt
pub fn decode(&self, encrypted_data: String) -> io::Result<String> {
let encrypted_data = hex::decode(encrypted_data)
.expect("failed to decode hex string into vec");
let key = Key::<Aes256Gcm>::from_slice(self.passphrase.as_bytes());
let (nonce_arr, ciphered_data) = encrypted_data.split_at(12);
let nonce = Nonce::from_slice(nonce_arr);
let cipher = Aes256Gcm::new(key);
let plaintext = cipher.decrypt(nonce, ciphered_data)
.expect("failed to decrypt data");
let result = String::from_utf8(plaintext)
.expect("failed to convert vector of bytes to string");
//.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
//match String::from_utf8(content) {
// Ok(s) => Ok(s),
// Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e))
//}
return Ok(line.clone());
Ok(result)
}
pub fn test_encoded_passphrase(&self, piassphrase_encoded: String) -> bool {

Loading…
Cancel
Save