From 38e7e1d92ce4aea7840d78bcda6246bd61c423ac Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Sun, 6 Jan 2019 00:16:59 +0100 Subject: Refactor prepare_secret function This patch refactors the prepare_secret function by renaming it to prepare_ascii_secret and by moving the formatting of a bytes slice as a hex string into the format_bytes function. This prepares for adding a the base32 format in a future patch. --- nitrocli/src/commands.rs | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/nitrocli/src/commands.rs b/nitrocli/src/commands.rs index c1942e8..71b2bdd 100644 --- a/nitrocli/src/commands.rs +++ b/nitrocli/src/commands.rs @@ -433,21 +433,23 @@ pub fn otp_get( Ok(()) } +/// Format a byte vector as a hex string. +fn format_bytes(bytes: &[u8]) -> String { + bytes + .iter() + .map(|c| format!("{:x}", c)) + .collect::>() + .join("") +} + /// Prepare an ASCII secret string for libnitrokey. /// /// libnitrokey expects secrets as hexadecimal strings. This function transforms an ASCII string /// into a hexadecimal string or returns an error if the given string contains non-ASCII /// characters. -fn prepare_secret(secret: &str) -> Result { +fn prepare_ascii_secret(secret: &str) -> Result { if secret.is_ascii() { - Ok( - secret - .as_bytes() - .iter() - .map(|c| format!("{:x}", c)) - .collect::>() - .join(""), - ) + Ok(format_bytes(&secret.as_bytes())) } else { Err(Error::Error( "The given secret is not an ASCII string despite --format ascii being set".to_string(), @@ -465,7 +467,7 @@ pub fn otp_set( secret_format: args::OtpSecretFormat, ) -> Result<()> { let secret = match secret_format { - args::OtpSecretFormat::Ascii => prepare_secret(&data.secret)?, + args::OtpSecretFormat::Ascii => prepare_ascii_secret(&data.secret)?, args::OtpSecretFormat::Hex => data.secret, }; let data = nitrokey::OtpSlotData { secret, ..data }; @@ -700,7 +702,7 @@ mod tests { #[test] fn prepare_secret_ascii() { - let result = prepare_secret("12345678901234567890"); + let result = prepare_ascii_secret("12345678901234567890"); assert_eq!( "3132333435363738393031323334353637383930".to_string(), result.unwrap() @@ -709,7 +711,7 @@ mod tests { #[test] fn prepare_secret_non_ascii() { - let result = prepare_secret("Österreich"); + let result = prepare_ascii_secret("Österreich"); assert!(result.is_err()); } } -- cgit v1.2.1