diff options
author | Robin Krahl <robin.krahl@ireas.org> | 2019-01-06 00:16:59 +0100 |
---|---|---|
committer | Daniel Mueller <deso@posteo.net> | 2019-01-13 18:37:02 -0800 |
commit | 38e7e1d92ce4aea7840d78bcda6246bd61c423ac (patch) | |
tree | fa8a9be8fa32a995e11822fceb474532f2f915f5 | |
parent | 53a2893ee725e4ad678b2060fd71729ff55e6cee (diff) | |
download | nitrocli-38e7e1d92ce4aea7840d78bcda6246bd61c423ac.tar.gz nitrocli-38e7e1d92ce4aea7840d78bcda6246bd61c423ac.tar.bz2 |
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.
-rw-r--r-- | nitrocli/src/commands.rs | 26 |
1 files 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::<Vec<_>>() + .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<String> { +fn prepare_ascii_secret(secret: &str) -> Result<String> { if secret.is_ascii() { - Ok( - secret - .as_bytes() - .iter() - .map(|c| format!("{:x}", c)) - .collect::<Vec<String>>() - .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()); } } |