Calculate SHA-256 digest

    0

    1

    Giovanny Gongora

    Codiga's Rust Recipes

    SHA-256 digest of a file

    use data_encoding::HEXUPPER;
    use ring::digest::{Context, Digest, SHA256};
    use std::fs::File;
    use std::io::{BufReader, Read, Write};
    
    fn sha256_digest<R: Read>(mut reader: R) -> Result<Digest> {
      let mut context = Context::new(&SHA256);
      let mut buffer = [0; 1024];
      loop {
        let count = reader.read(&mut buffer)?;
        if count == 0 {
          break;
        }
        context.update(&buffer[..count]);
      }
      Ok(context.finish())
    }
    fn main() -> Result<()> {
      let path = "file.txt";
      let mut output = File::create(path)?;
      write!(output, "We will generate a digest of this text")?;
      let input = File::open(path)?;
      let reader = BufReader::new(input);
      let digest = sha256_digest(reader)?;
      println!("SHA-256 digest is {}", HEXUPPER.encode(digest.as_ref()));
      Ok(())
    }
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.