nettext/src/crypto/b2.rs

43 lines
1.1 KiB
Rust
Raw Normal View History

2022-11-17 21:53:36 +00:00
use blake2::{Blake2b512, Digest};
use crate::crypto::CryptoError;
2022-11-17 22:58:44 +00:00
use crate::enc;
2022-11-17 21:53:36 +00:00
/// A Blake2b512 digest
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct Blake2Sum([u8; 64]);
impl Blake2Sum {
2022-11-17 22:58:44 +00:00
/// Create a Blake2Sum object by passing the digest as bytes directly
pub fn from_bytes(bytes: [u8; 64]) -> Self {
Self(bytes)
}
2022-11-17 21:53:36 +00:00
2022-11-17 22:58:44 +00:00
/// Compute the Blake2b512 digest of a byte slice
pub fn compute(buf: &[u8]) -> Self {
let mut hasher = Blake2b512::new();
hasher.update(buf);
Self(hasher.finalize()[..].try_into().unwrap())
}
2022-11-17 21:53:36 +00:00
2022-11-17 22:58:44 +00:00
/// Check that this digest corresponds to a given slice
pub fn verify(&self, buf: &[u8]) -> Result<(), CryptoError> {
if Self::compute(buf) == *self {
Ok(())
} else {
Err(CryptoError::InvalidHash)
}
}
/// Return a reference to the inner byte slice
pub fn as_bytes(&self) -> &[u8] {
&self.0[..]
}
}
impl enc::Encode for Blake2Sum {
2022-11-18 11:49:13 +00:00
fn term(&self) -> enc::Result<'_> {
Ok(enc::bytes(self.as_bytes()))
2022-11-17 22:58:44 +00:00
}
2022-11-17 21:53:36 +00:00
}