diff options
Diffstat (limited to 'crates/secd/src/util/mod.rs')
| -rw-r--r-- | crates/secd/src/util/mod.rs | 107 |
1 files changed, 93 insertions, 14 deletions
diff --git a/crates/secd/src/util/mod.rs b/crates/secd/src/util/mod.rs index c26986d..8676f26 100644 --- a/crates/secd/src/util/mod.rs +++ b/crates/secd/src/util/mod.rs @@ -1,21 +1,14 @@ +pub(crate) mod crypter; pub(crate) mod from; -use rand::{thread_rng, Rng}; +use self::crypter::{Crypter, CrypterError}; +use crate::{ + AddressType, Credential, CredentialType, IdentityId, SecdError, Session, SESSION_DURATION, + SESSION_SIZE_BYTES, +}; use sha2::{Digest, Sha256}; +use std::str::from_utf8; use time::OffsetDateTime; -use url::Url; - -use crate::{AddressType, IdentityId, SecdError, Session, SESSION_DURATION, SESSION_SIZE_BYTES}; - -pub(crate) fn remove_trailing_slash(url: &mut Url) -> String { - let mut u = url.to_string(); - - if u.ends_with('/') { - u.pop(); - } - - u -} pub(crate) fn hash(i: &[u8]) -> Vec<u8> { let mut hasher = Sha256::new(); @@ -51,3 +44,89 @@ impl Session { }) } } + +impl Credential { + pub(crate) fn encrypt(&mut self, crypter: &Crypter) -> Result<(), SecdError> { + Ok(match self.t { + CredentialType::Passphrase { + key: _, + ref mut value, + } => { + *value = hex::encode(crypter.encrypt(value.as_bytes())?); + } + _ => {} + }) + } + pub(crate) fn decrypt(&mut self, crypter: &Crypter) -> Result<(), SecdError> { + Ok(match self.t { + CredentialType::Passphrase { + key: _, + ref mut value, + } => { + *value = from_utf8( + &crypter.decrypt( + &hex::decode(value.clone()) + .map_err(|e| CrypterError::DecodeError(e.to_string()))?, + )?, + ) + .map_err(|e| CrypterError::DecodeError(e.to_string()))? + .to_string() + } + _ => {} + }) + } + + pub(crate) fn hash(&mut self, crypter: &Crypter) -> Result<(), SecdError> { + Ok(match self.t { + CredentialType::Passphrase { + key: _, + ref mut value, + } => { + *value = crypter.hash(value.as_bytes())?; + } + _ => {} + }) + } +} + +#[cfg(test)] +mod test { + use uuid::Uuid; + + use super::*; + + #[test] + fn test_credential_encrypt() { + let c = Crypter::new("AMAZING_KEY".as_bytes()); + + let plaintext_secret = "super_password".to_string(); + + let mut credential = Credential { + id: Uuid::new_v4(), + identity_id: Uuid::new_v4(), + t: CredentialType::Passphrase { + key: "super_user".into(), + value: plaintext_secret.clone(), + }, + created_at: OffsetDateTime::now_utc(), + revoked_at: None, + deleted_at: None, + }; + + credential.encrypt(&c).unwrap(); + match &credential.t { + CredentialType::Passphrase { key: _, value } => { + assert_ne!(plaintext_secret.clone(), value.clone()) + } + _ => {} + }; + + credential.decrypt(&c).unwrap(); + match &credential.t { + CredentialType::Passphrase { key: _, value } => { + assert_eq!(plaintext_secret.clone(), value.clone()) + } + _ => {} + }; + } +} |
