workflow_encryption/
hash.rs

1use crate::imports::*;
2use argon2::Argon2;
3use sha2::{Digest, Sha256};
4
5/// Produces `SHA256` hash of the given data.
6#[inline]
7pub fn sha256(data: &[u8]) -> Secret {
8    let mut hash = Sha256::default();
9    hash.update(data);
10    Secret::new(hash.finalize().to_vec())
11}
12
13/// Produces `SHA256d` hash of the given data.
14#[inline]
15pub fn sha256d(data: &[u8]) -> Secret {
16    let mut hash = Sha256::default();
17    hash.update(data);
18    sha256(hash.finalize().as_slice())
19}
20
21/// Produces an argon2(sha256(data)) hash of the given data.
22pub fn argon2_sha256(data: &[u8], byte_length: usize) -> Result<Secret> {
23    let salt = sha256(data);
24    let mut key = vec![0u8; byte_length];
25    Argon2::default().hash_password_into(data, salt.as_ref(), &mut key)?;
26    Ok(key.into())
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32    use workflow_core::hex::ToHex;
33
34    #[test]
35    fn test_wallet_argon2() {
36        println!("testing argon2 hash");
37        let password = b"user_password";
38        let hash = argon2_sha256(password, 32).unwrap();
39        let hash_hex = hash.as_ref().to_hex();
40        // println!("argon2hash: {:?}", hash_hex);
41        assert_eq!(
42            hash_hex,
43            "a79b661f0defd1960a4770889e19da0ce2fde1e98ca040f84ab9b2519ca46234"
44        );
45    }
46}