Starting with all the printable characters, I want to get the sha256 characters one by one and compare them to the sha256 taken from the input.

My code is :

use hex_literal::hex;use sha2::{Digest, Sha256};use std::io;fn main() {let printable = vec![b" ", b"!", b"#"];enter code herelet mut hash_target = String::new();io::stdin().read_line(&mut hash_target).expect("Something Wrong!").to_owned();let hash_target = &hash_target[..];for i in 0..printable.len() {let mut sha256 = Sha256::new();sha256.update(printable[i]);let result = sha256.finalize();if result[..]== hex!(hash_target)[..]{println!("True");}}}

I do not know how to give the value of the sha read from the input to the hex function.

1

Best Answer


As stated in the documentation of the hex_literal crate,the hex_literal::hex! macro is intended for hex literals and thus does not work with runtime-generated strings as the input.

To convert a hex string into a u8 slice, you may want to use the hex crate like this.

let target = hex::decode(hash_target).expect("Failed to decode hex string");

A full example adapted from the original code with some minor fixes:

use sha2::{Digest, Sha256};use std::io;fn main() {let printables = vec![b" ", b"!", b"#"];let mut input = String::new();io::stdin().read_line(&mut input).expect("Failed to read input");let input_hash = hex::decode(input.trim()).expect("Failed to decode");for printable in printables.iter() {let mut sha256 = Sha256::new();sha256.update(printable);let expected_hash = sha256.finalize();if &expected_hash[..] == &input_hash[..] {println!("True");}}}