home ~ projects ~ socials

Create A Sha2 (Sha256 or Sha512) Hash From A File

This is from a string right now. todo make it from a file.

---
[dependencies]
anyhow = "1.0.98"
sha2 = "0.10.8"
---

use anyhow::Result;
use sha2::{Digest, Sha256};

fn main() -> Result<()> {
  let input = "hello, world".to_string();
  let output = get_string_as_sha256_hash(&input)?;
  println!("{}", output);
  Ok(())
}

fn get_string_as_sha256_hash(input: &String) -> Result<String> {
  let mut hasher = Sha256::new();
  hasher.update(input.as_bytes());
  let result: String = format!("{:X}", hasher.finalize());
  Ok(result)
}
Output:
09CA7E4EAA6E8AE9C7D261167129184883644D07DFBA7CBFBC4C8A2E08360D5B
-- end of line --

References