Sha256 Hashes in Rust
Here’s the translation of the SHA256 hashes example from Go to Rust:
Our first program demonstrates how to compute SHA256 hashes in Rust. SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature.
use sha2::{Sha256, Digest};
fn main() {
let s = "sha256 this string";
// Create a new SHA256 hasher
let mut hasher = Sha256::new();
// Update the hasher with the input data
hasher.update(s);
// Finalize the hash and get the result
let result = hasher.finalize();
println!("{}", s);
println!("{:x}", result);
}Rust implements several hash functions in the sha2 crate. To use it, you need to add it to your Cargo.toml file:
[dependencies]
sha2 = "0.10.6"In this example, we start by creating a new SHA256 hasher. Then, we update the hasher with our input string. Finally, we finalize the hash and get the result.
The update method expects a reference to a slice of bytes. If you have a string s, you can pass it directly as s.as_bytes().
The finalize method consumes the hasher and returns the final hash result.
Running the program computes the hash and prints it in a human-readable hex format.
$ cargo run
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...You can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, you can use Sha512::new() from the same sha2 crate.
Note that if you need cryptographically secure hashes, you should carefully research hash strength!