Remove .unwrap() in SCRAM code.

This commit is contained in:
Emmanuel Gil Peyrot 2019-01-18 00:26:41 +01:00
commit 0c426b4d17
3 changed files with 21 additions and 17 deletions

View file

@ -33,7 +33,7 @@ pub trait ScramProvider {
fn hash(data: &[u8]) -> Vec<u8>;
/// A function which performs an HMAC using the hash function.
fn hmac(data: &[u8], key: &[u8]) -> Vec<u8>;
fn hmac(data: &[u8], key: &[u8]) -> Result<Vec<u8>, String>;
/// A function which does PBKDF2 key derivation using the hash function.
fn derive(data: &Password, salt: &[u8], iterations: usize) -> Result<Vec<u8>, String>;
@ -43,7 +43,6 @@ pub trait ScramProvider {
pub struct Sha1;
impl ScramProvider for Sha1 {
// TODO: look at all these unwraps
type Secret = secret::Pbkdf2Sha1;
fn name() -> &'static str {
@ -57,14 +56,17 @@ impl ScramProvider for Sha1 {
vec
}
fn hmac(data: &[u8], key: &[u8]) -> Vec<u8> {
fn hmac(data: &[u8], key: &[u8]) -> Result<Vec<u8>, String> {
type HmacSha1 = Hmac<Sha1_hash>;
let mut mac = HmacSha1::new_varkey(key).unwrap();
let mut mac = match HmacSha1::new_varkey(key) {
Ok(mac) => mac,
Err(err) => return Err(format!("{}", err)),
};
mac.input(data);
let result = mac.result();
let mut vec = Vec::with_capacity(Sha1_hash::output_size());
vec.extend_from_slice(result.code().as_slice());
vec
Ok(vec)
}
fn derive(password: &Password, salt: &[u8], iterations: usize) -> Result<Vec<u8>, String> {
@ -105,7 +107,6 @@ impl ScramProvider for Sha1 {
pub struct Sha256;
impl ScramProvider for Sha256 {
// TODO: look at all these unwraps
type Secret = secret::Pbkdf2Sha256;
fn name() -> &'static str {
@ -119,14 +120,17 @@ impl ScramProvider for Sha256 {
vec
}
fn hmac(data: &[u8], key: &[u8]) -> Vec<u8> {
fn hmac(data: &[u8], key: &[u8]) -> Result<Vec<u8>, String> {
type HmacSha256 = Hmac<Sha256_hash>;
let mut mac = HmacSha256::new_varkey(key).unwrap();
let mut mac = match HmacSha256::new_varkey(key) {
Ok(mac) => mac,
Err(err) => return Err(format!("{}", err)),
};
mac.input(data);
let result = mac.result();
let mut vec = Vec::with_capacity(Sha256_hash::output_size());
vec.extend_from_slice(result.code().as_slice());
vec
Ok(vec)
}
fn derive(password: &Password, salt: &[u8], iterations: usize) -> Result<Vec<u8>, String> {