use core::fmt;
use subtle::ConstantTimeEq;
use zeroize::{Zeroize, ZeroizeOnDrop};
use crate::error::{Error, ErrorCode, Result};
#[cfg(feature = "rustcrypto")]
mod rustcrypto;
#[cfg(feature = "rustcrypto")]
pub use rustcrypto::*;
#[cfg(feature = "rustcrypto")]
mod spake2p;
#[cfg(feature = "rustcrypto")]
pub use spake2p::{
Confirmation, SharedSecret, Spake2pProver, Spake2pVerifier, Spake2pVerifierData, context,
};
pub const PRIVACY_KEY_INFO: &[u8] = b"PrivacyKey";
pub const HASH_LEN_BYTES: usize = 32;
pub const GROUP_SIZE_BYTES: usize = 32;
pub const PUBLIC_KEY_SIZE_BYTES: usize = (2 * GROUP_SIZE_BYTES) + 1;
pub const SYMMETRIC_KEY_LENGTH_BYTES: usize = 16;
pub const AEAD_MIC_LENGTH_BYTES: usize = 16;
pub const AEAD_NONCE_LENGTH_BYTES: usize = 13;
pub const PRIVACY_NONCE_LENGTH_BYTES: usize = 13;
pub const SIGNATURE_LEN_BYTES: usize = 2 * GROUP_SIZE_BYTES;
pub const W_SIZE_BYTES: usize = GROUP_SIZE_BYTES + 8;
pub const PBKDF_ITERATIONS_MIN: u32 = 1_000;
pub const PBKDF_ITERATIONS_MAX: u32 = 100_000;
pub const PBKDF_SALT_MIN_BYTES: usize = 16;
pub const PBKDF_SALT_MAX_BYTES: usize = 32;
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct SymmetricKey([u8; SYMMETRIC_KEY_LENGTH_BYTES]);
impl SymmetricKey {
#[must_use]
pub const fn new(bytes: [u8; SYMMETRIC_KEY_LENGTH_BYTES]) -> Self {
Self(bytes)
}
pub fn from_slice(bytes: &[u8]) -> Result<Self> {
let Some(head) = bytes.get(..SYMMETRIC_KEY_LENGTH_BYTES) else {
return Err(Error::new(ErrorCode::InvalidArgument));
};
let mut out = [0u8; SYMMETRIC_KEY_LENGTH_BYTES];
out.copy_from_slice(head);
Ok(Self(out))
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; SYMMETRIC_KEY_LENGTH_BYTES] {
&self.0
}
}
impl fmt::Debug for SymmetricKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SymmetricKey(<redacted>)")
}
}
impl PartialEq for SymmetricKey {
fn eq(&self, other: &Self) -> bool {
self.0.ct_eq(&other.0).into()
}
}
impl Eq for SymmetricKey {}
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct Secret<const N: usize>([u8; N]);
impl<const N: usize> Secret<N> {
#[must_use]
pub const fn new(bytes: [u8; N]) -> Self {
Self(bytes)
}
#[must_use]
pub const fn zeroed() -> Self {
Self([0u8; N])
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; N] {
&self.0
}
pub const fn as_mut(&mut self) -> &mut [u8; N] {
&mut self.0
}
}
impl<const N: usize> fmt::Debug for Secret<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Secret(<redacted>)")
}
}
impl<const N: usize> PartialEq for Secret<N> {
fn eq(&self, other: &Self) -> bool {
self.0.ct_eq(&other.0).into()
}
}
impl<const N: usize> Eq for Secret<N> {}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct PublicKey([u8; PUBLIC_KEY_SIZE_BYTES]);
impl PublicKey {
#[must_use]
pub const fn from_bytes(bytes: [u8; PUBLIC_KEY_SIZE_BYTES]) -> Self {
Self(bytes)
}
pub fn from_slice(bytes: &[u8]) -> Result<Self> {
let Ok(arr) = <[u8; PUBLIC_KEY_SIZE_BYTES]>::try_from(bytes) else {
return Err(Error::new(ErrorCode::InvalidArgument));
};
Ok(Self(arr))
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; PUBLIC_KEY_SIZE_BYTES] {
&self.0
}
}
impl fmt::Debug for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let head = self.0.get(..4).unwrap_or(&[]);
write!(f, "PublicKey({head:02x?}…)")
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Signature([u8; SIGNATURE_LEN_BYTES]);
impl Signature {
#[must_use]
pub const fn from_bytes(bytes: [u8; SIGNATURE_LEN_BYTES]) -> Self {
Self(bytes)
}
pub fn from_slice(bytes: &[u8]) -> Result<Self> {
let Ok(arr) = <[u8; SIGNATURE_LEN_BYTES]>::try_from(bytes) else {
return Err(Error::new(ErrorCode::InvalidArgument));
};
Ok(Self(arr))
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; SIGNATURE_LEN_BYTES] {
&self.0
}
}
impl fmt::Debug for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Signature(..)")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct KeyHandle(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum KeyPurpose {
DeviceAttestation,
Operational,
Ephemeral,
}
pub trait KeyStore {
fn generate(
&mut self,
purpose: KeyPurpose,
random: &[u8; GROUP_SIZE_BYTES],
) -> Result<(KeyHandle, PublicKey)>;
fn import(&mut self, purpose: KeyPurpose, secret: &[u8; GROUP_SIZE_BYTES])
-> Result<KeyHandle>;
fn public_key(&self, handle: KeyHandle) -> Result<PublicKey>;
fn sign(&self, handle: KeyHandle, message: &[u8]) -> Result<Signature>;
fn ecdh(&self, handle: KeyHandle, peer: &PublicKey) -> Result<Secret<GROUP_SIZE_BYTES>>;
fn remove(&mut self, handle: KeyHandle) -> Result<()>;
}
pub fn verify(public: &PublicKey, message: &[u8], signature: &Signature) -> Result<bool> {
#[cfg(feature = "rustcrypto")]
{
rustcrypto::verify_impl(public, message, signature)
}
#[cfg(not(feature = "rustcrypto"))]
{
let _ = (public, message, signature);
Err(Error::new(ErrorCode::Platform))
}
}
#[must_use]
pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
a.ct_eq(b).into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constants_match_chapter_3() {
assert_eq!(HASH_LEN_BYTES, 32);
assert_eq!(GROUP_SIZE_BYTES, 32);
assert_eq!(PUBLIC_KEY_SIZE_BYTES, 65);
assert_eq!(SYMMETRIC_KEY_LENGTH_BYTES, 16);
assert_eq!(AEAD_MIC_LENGTH_BYTES, 16);
assert_eq!(AEAD_NONCE_LENGTH_BYTES, 13);
assert_eq!(W_SIZE_BYTES, 40, "CRYPTO_GROUP_SIZE_BYTES + 8");
}
#[cfg(feature = "std")]
#[test]
fn a_key_does_not_print_itself() {
let k = SymmetricKey::new([0xAB; 16]);
let shown = std::format!("{k:?}");
assert!(shown.contains("redacted"), "{shown}");
assert!(!shown.contains("ab"), "{shown}");
}
#[test]
fn keys_compare_by_value() {
assert_eq!(SymmetricKey::new([1; 16]), SymmetricKey::new([1; 16]));
assert_ne!(SymmetricKey::new([1; 16]), SymmetricKey::new([2; 16]));
}
#[test]
fn ct_eq_agrees_with_eq() {
assert!(ct_eq(b"abc", b"abc"));
assert!(!ct_eq(b"abc", b"abd"));
assert!(!ct_eq(b"abc", b"ab"), "different lengths are not equal");
assert!(ct_eq(b"", b""));
}
#[test]
fn a_symmetric_key_from_a_short_slice_is_refused() {
assert!(SymmetricKey::from_slice(&[0u8; 15]).is_err());
assert!(SymmetricKey::from_slice(&[0u8; 16]).is_ok());
assert!(SymmetricKey::from_slice(&[0u8; 32]).is_ok());
}
}