From 8350ac6afb2d678b74581000a6aafe1994b72231 Mon Sep 17 00:00:00 2001 From: Daniel Mueller Date: Wed, 16 Jan 2019 17:26:30 -0800 Subject: Update nitrokey crate to 0.3.3 This change updates the nitrokey crate to version 0.3.3. Along with that change we update rand to 0.6.4 because rand 0.6.1 does not yet contain a publicly accessible rand_os. Note that we no longer require all crates in rand's workspace, but only rand_os and rand_core, which is a significant reduction in the number of lines of code compiled. Import subrepo nitrokey/:nitrokey at 7cf747d56ddc0b7eeedc3caf36dcc909907a171c Import subrepo rand/:rand at 4336232dda03323634b10ec72ddf27914aebc3a2 --- nitrokey/src/util.rs | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) (limited to 'nitrokey/src/util.rs') diff --git a/nitrokey/src/util.rs b/nitrokey/src/util.rs index cb109d0..567c478 100644 --- a/nitrokey/src/util.rs +++ b/nitrokey/src/util.rs @@ -4,7 +4,8 @@ use std::fmt; use std::os::raw::{c_char, c_int}; use libc::{c_void, free}; -use rand::Rng; +use rand_core::RngCore; +use rand_os::OsRng; /// Error types returned by Nitrokey device or by the library. #[derive(Clone, Copy, Debug, PartialEq)] @@ -44,6 +45,8 @@ pub enum CommandError { InvalidHexString, /// The target buffer was smaller than the source. TargetBufferTooSmall, + /// An error occurred during random number generation. + RngError, } /// Log level for libnitrokey. @@ -80,10 +83,13 @@ pub fn result_from_string(ptr: *const c_char) -> Result { unsafe { let s = owned_str_from_ptr(ptr); free(ptr as *mut c_void); + // An empty string can both indicate an error or be a valid return value. In this case, we + // have to check the last command status to decide what to return. if s.is_empty() { - return Err(get_last_error()); + get_last_result().map(|_| s) + } else { + Ok(s) } - return Ok(s); } } @@ -106,10 +112,11 @@ pub fn get_last_error() -> CommandError { }; } -pub fn generate_password(length: usize) -> Vec { +pub fn generate_password(length: usize) -> Result, CommandError> { + let mut rng = OsRng::new()?; let mut data = vec![0u8; length]; - rand::thread_rng().fill(&mut data[..]); - return data; + rng.fill_bytes(&mut data[..]); + Ok(data) } pub fn get_cstring>>(s: T) -> Result { @@ -146,6 +153,7 @@ impl CommandError { "The supplied string is not in hexadecimal format".into() } CommandError::TargetBufferTooSmall => "The target buffer is too small".into(), + CommandError::RngError => "An error occurred during random number generation".into(), } } } @@ -178,6 +186,12 @@ impl From for CommandError { } } +impl From for CommandError { + fn from(_error: rand_core::Error) -> Self { + CommandError::RngError + } +} + impl Into for LogLevel { fn into(self) -> i32 { match self { -- cgit v1.2.1