pub struct Sha256Std {
inner: native_neural_network::crypto::Sha256Ctx,
}
impl Sha256Std {
pub fn new() -> Self {
Self {
inner: native_neural_network::crypto::Sha256Ctx::new(),
}
}
pub fn update(&mut self, data: &[u8]) {
self.inner.update(data);
}
pub fn finalize(&mut self) -> [u8; 32] {
let mut out = [0u8; 32];
self.inner.finalize(&mut out);
out
}
}
impl Default for Sha256Std {
fn default() -> Self {
Self::new()
}
}
pub struct Sha512Std {
inner: native_neural_network::crypto::Sha512Ctx,
}
impl Sha512Std {
pub fn new() -> Self {
Self {
inner: native_neural_network::crypto::Sha512Ctx::new(),
}
}
pub fn update(&mut self, data: &[u8]) {
self.inner.update(data);
}
pub fn finalize(&mut self) -> [u8; 64] {
let mut out = [0u8; 64];
self.inner.finalize(&mut out);
out
}
}
impl Default for Sha512Std {
fn default() -> Self {
Self::new()
}
}
pub fn sha256_bytes(data: &[u8]) -> [u8; 32] {
let mut c = native_neural_network::crypto::Sha256Ctx::new();
c.update(data);
let mut out = [0u8; 32];
c.finalize(&mut out);
out
}
pub fn sha512_bytes(data: &[u8]) -> [u8; 64] {
let mut c = native_neural_network::crypto::Sha512Ctx::new();
c.update(data);
let mut out = [0u8; 64];
c.finalize(&mut out);
out
}
impl core::fmt::Debug for Sha256Std {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Sha256Std").finish()
}
}
impl core::fmt::Debug for Sha512Std {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Sha512Std").finish()
}
}
pub fn digest_to_hex_lower(digest: &[u8]) -> Option<String> {
if digest.is_empty() {
return Some(String::new());
}
let mut out = String::with_capacity(digest.len() * 2);
for &b in digest {
out.push_str(&format!("{:02x}", b));
}
Some(out)
}
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
native_neural_network::crypto::constant_time_eq(a, b)
}
pub fn verify_sha256(data: &[u8], expected: &[u8]) -> bool {
if expected.len() != 32 {
return false;
}
let exp: &[u8; 32] = match expected.try_into() {
Ok(a) => a,
Err(_) => return false,
};
native_neural_network::crypto::verify_sha256(data, exp)
}
pub fn verify_sha512(data: &[u8], expected: &[u8]) -> bool {
if expected.len() != 64 {
return false;
}
let exp: &[u8; 64] = match expected.try_into() {
Ok(a) => a,
Err(_) => return false,
};
native_neural_network::crypto::verify_sha512(data, exp)
}
pub fn hash(data: &[u8]) -> [u8; 32] {
sha256_bytes(data)
}
pub enum HashAlgorithm {
Sha256,
Sha512,
}
pub fn hash_with(alg: HashAlgorithm, data: &[u8]) -> Vec<u8> {
match alg {
HashAlgorithm::Sha256 => {
let out = sha256_bytes(data);
let mut v = Vec::with_capacity(32);
v.extend_from_slice(&out);
v
}
HashAlgorithm::Sha512 => {
let out = sha512_bytes(data);
let mut v = Vec::with_capacity(64);
v.extend_from_slice(&out);
v
}
}
}
fn crypto_init_hook() -> Result<(), crate::InitError> {
Ok(())
}
pub fn register_module_init_hooks() -> Result<(), crate::RegisterError> {
crate::register_init_hook("crypto", crate::InitSubsystem::Crypto, crypto_init_hook)
}