use std::fmt;
#[derive(Debug, Clone)]
pub enum CryptoError {
InvalidHashAlgorithm(String),
HashMismatch,
SignatureInvalid(String),
InvalidPublicKey(String),
InvalidSignature(String),
Other(String),
}
impl fmt::Display for CryptoError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidHashAlgorithm(msg) => write!(f, "Invalid hash algorithm: {msg}"),
Self::HashMismatch => write!(f, "Hash verification failed: preimage doesn't match"),
Self::SignatureInvalid(msg) => write!(f, "Signature verification failed: {msg}"),
Self::InvalidPublicKey(msg) => write!(f, "Invalid public key: {msg}"),
Self::InvalidSignature(msg) => write!(f, "Invalid signature: {msg}"),
Self::Other(msg) => write!(f, "Cryptographic error: {msg}"),
}
}
}
impl std::error::Error for CryptoError {}
pub trait HashVerifier {
fn verify_preimage(&self, hash: &[u8], preimage: &[u8]) -> Result<(), CryptoError>;
fn is_algorithm_allowed(&self, codec: u64) -> bool;
fn algorithm_name(&self, codec: u64) -> &str;
}
pub trait SignatureVerifier {
fn verify_signature(
&self,
public_key: &[u8],
signature: &[u8],
message: &[u8],
) -> Result<(), CryptoError>;
}
pub trait EqualityChecker {
fn are_equal(&self, a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (byte_a, byte_b) in a.iter().zip(b.iter()) {
diff |= byte_a ^ byte_b;
}
diff == 0
}
}
impl EqualityChecker for () {}