-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmod.rs
More file actions
87 lines (75 loc) · 2.34 KB
/
Copy pathmod.rs
File metadata and controls
87 lines (75 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//! Hashing API module.
pub mod argon2;
mod blake3;
mod sha3;
use crate::core::error::CryptoError;
use crate::core::traits::Hasher;
use flutter_rust_bridge::frb;
use std::sync::Mutex;
/// Opaque handle wrapping any hasher implementation.
///
/// Uses Mutex for interior mutability since Hasher::update requires &mut self.
#[frb(opaque)]
pub struct HasherHandle {
inner: Mutex<Box<dyn Hasher>>,
}
impl HasherHandle {
fn new(hasher: Box<dyn Hasher>) -> Self {
Self {
inner: Mutex::new(hasher),
}
}
}
/// Create a BLAKE3 hasher handle.
pub fn create_blake3() -> HasherHandle {
HasherHandle::new(Box::new(blake3::Blake3Hasher::new()))
}
/// Create a SHA-3 hasher handle.
pub fn create_sha3() -> HasherHandle {
HasherHandle::new(Box::new(sha3::Sha3Hasher::new()))
}
/// Feed data into the hasher.
pub fn hasher_update(handle: &HasherHandle, data: Vec<u8>) -> Result<(), CryptoError> {
let mut guard = handle
.inner
.lock()
.map_err(|_| CryptoError::HashingFailed("Hasher lock poisoned".into()))?;
guard.update(&data)
}
/// Reset the hasher to its initial state.
pub fn hasher_reset(handle: &HasherHandle) -> Result<(), CryptoError> {
let mut guard = handle
.inner
.lock()
.map_err(|_| CryptoError::HashingFailed("Hasher lock poisoned".into()))?;
guard.reset()
}
/// Finalize and return the digest.
pub fn hasher_finalize(handle: &HasherHandle) -> Result<Vec<u8>, CryptoError> {
let guard = handle
.inner
.lock()
.map_err(|_| CryptoError::HashingFailed("Hasher lock poisoned".into()))?;
guard.finalize()
}
/// Get the algorithm identifier for the hasher.
pub fn hasher_algorithm_id(handle: &HasherHandle) -> Result<String, CryptoError> {
let guard = handle
.inner
.lock()
.map_err(|_| CryptoError::HashingFailed("Hasher lock poisoned".into()))?;
Ok(guard.algorithm_id().to_string())
}
/// One-shot BLAKE3 hash function.
///
/// Convenience function for hashing data in a single call.
pub fn blake3_hash(data: Vec<u8>) -> Vec<u8> {
::blake3::hash(&data).as_bytes().to_vec()
}
/// One-shot SHA-3 hash function.
///
/// Convenience function for hashing data in a single call.
pub fn sha3_hash(data: Vec<u8>) -> Vec<u8> {
use ::sha3::{Digest, Sha3_256 as Sha3Digest};
Sha3Digest::digest(&data).to_vec()
}