nettext/src/crypto/b2.rs

31 lines
735 B
Rust

use blake2::{Blake2b512, Digest};
use crate::crypto::CryptoError;
/// A Blake2b512 digest
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct Blake2Sum([u8; 64]);
impl Blake2Sum {
/// Create a Blake2Sum object by passing the digest as bytes directly
pub fn from_bytes(bytes: [u8; 64]) -> Self {
Self(bytes)
}
/// 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())
}
/// Check that this digest corresponds to a given slice
pub fn check(&self, buf: &[u8]) -> Result<(), CryptoError> {
if Self::compute(buf) == *self {
Ok(())
} else {
Err(CryptoError::InvalidHash)
}
}
}