use crate::error::Error;
#[cfg(feature = "hmac")]
use hmac::Hmac;
#[cfg(feature = "pbkdf2")]
use pbkdf2::pbkdf2;
use rand_os::{rand_core::RngCore, OsRng};
#[cfg(feature = "sha2")]
use sha2::Sha256;
use std::fmt::{self, Debug};
use zeroize::Zeroize;
pub const AUTHENTICATION_KEY_SIZE: usize = 32;
pub const DEFAULT_PASSWORD: &[u8] = b"password";
pub const DEFAULT_PBKDF2_SALT: &[u8] = b"Yubico";
pub const DEFAULT_PBKDF2_ITERATIONS: usize = 10_000;
#[derive(Clone)]
pub struct AuthenticationKey(pub(crate) [u8; AUTHENTICATION_KEY_SIZE]);
impl AuthenticationKey {
pub fn random() -> Self {
let mut rng = OsRng::new().expect("RNG failure!");
let mut challenge = [0u8; AUTHENTICATION_KEY_SIZE];
rng.fill_bytes(&mut challenge);
AuthenticationKey(challenge)
}
#[cfg(feature = "passwords")]
pub fn derive_from_password(password: &[u8]) -> Self {
let mut kdf_output = [0u8; AUTHENTICATION_KEY_SIZE];
pbkdf2::<Hmac<Sha256>>(
password,
DEFAULT_PBKDF2_SALT,
DEFAULT_PBKDF2_ITERATIONS,
&mut kdf_output,
);
Self::new(kdf_output)
}
pub fn from_slice(key_slice: &[u8]) -> Result<Self, AuthenticationKeyError> {
ensure!(
key_slice.len() == AUTHENTICATION_KEY_SIZE,
AuthenticationKeyErrorKind::SizeInvalid,
"expected {}-byte key, got {}",
AUTHENTICATION_KEY_SIZE,
key_slice.len()
);
let mut key_bytes = [0u8; AUTHENTICATION_KEY_SIZE];
key_bytes.copy_from_slice(key_slice);
Ok(AuthenticationKey(key_bytes))
}
pub fn new(key_bytes: [u8; AUTHENTICATION_KEY_SIZE]) -> Self {
AuthenticationKey(key_bytes)
}
pub fn as_secret_slice(&self) -> &[u8] {
&self.0
}
pub(crate) fn enc_key(&self) -> &[u8] {
&self.0[..16]
}
pub(crate) fn mac_key(&self) -> &[u8] {
&self.0[16..]
}
}
impl Debug for AuthenticationKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "yubihsm::AuthenticationKey(...)")
}
}
#[cfg(feature = "passwords")]
impl Default for AuthenticationKey {
fn default() -> Self {
AuthenticationKey::derive_from_password(DEFAULT_PASSWORD)
}
}
impl Drop for AuthenticationKey {
fn drop(&mut self) {
self.0.zeroize();
}
}
impl From<[u8; AUTHENTICATION_KEY_SIZE]> for AuthenticationKey {
fn from(key_bytes: [u8; AUTHENTICATION_KEY_SIZE]) -> AuthenticationKey {
AuthenticationKey::new(key_bytes)
}
}
impl_array_serializers!(AuthenticationKey, AUTHENTICATION_KEY_SIZE);
pub type AuthenticationKeyError = Error<AuthenticationKeyErrorKind>;
#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)]
pub enum AuthenticationKeyErrorKind {
#[fail(display = "invalid size")]
SizeInvalid,
}