Created
December 5, 2022 02:23
-
-
Save divi255/7dd739626387a049136f4d009a401fcc to your computer and use it in GitHub Desktop.
hash calc by ChatGPT (FIPS-140 compliant)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate clap; | |
extern crate openssl; | |
use clap::{App, Arg}; | |
use openssl::hash::{Hasher, MessageDigest}; | |
use std::error::Error; | |
use std::fs::File; | |
use std::io::{BufReader, Read}; | |
fn main() -> Result<(), Box<Error>> { | |
// Parse the command-line arguments | |
let matches = App::new("sha256") | |
.arg( | |
Arg::with_name("file") | |
.short("f") | |
.long("file") | |
.value_name("FILE") | |
.help("The file to calculate the hash of") | |
.takes_value(true), | |
) | |
.get_matches(); | |
// Open the file (or use stdin if no file was specified) | |
let file = matches.value_of("file").map_or( | |
Box::new(BufReader::new(std::io::stdin())) as Box<dyn Read>, | |
|file_name| { | |
Box::new(BufReader::new(File::open(file_name)?)) as Box<dyn Read> | |
}, | |
); | |
// Turn on FIPS mode | |
openssl::fips::Fips::activate()?; | |
// Create a hasher with the SHA-256 algorithm | |
let mut hasher = Hasher::new(MessageDigest::sha256())?; | |
// Read the file and update the hasher with its contents | |
let mut buffer = [0; 1024]; | |
loop { | |
let count = file.read(&mut buffer)?; | |
if count == 0 { | |
break; | |
} | |
hasher.update(&buffer[..count])?; | |
} | |
// Calculate the hash and print it as a hexadecimal string | |
let hash = hasher.finish()?; | |
println!("{:x}", hash); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment