如何检查sha256哈希值?

3
从所有可打印字符开始,我想逐个获取sha256字符,并将它们与从输入中获取的sha256进行比较。
我的代码如下:
use hex_literal::hex;
use sha2::{Digest, Sha256};
use std::io;


fn main() {
    let printable = vec![b" ", b"!", b"#"];
    enter code here
    let 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");
        }
    }
}


我不知道如何将从输入中读取的sha值传递给hex函数。

这个回答解决了您的问题吗?如何将十六进制字符串转换为u8切片? - cdhowie
1个回答

1

hex_literal crate的文档所述, hex_literal::hex!宏适用于十六进制字面量,因此无法处理运行时生成的字符串作为输入。

要将十六进制字符串转换为u8切片,您可以使用hex crate,如下所示。

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

完整的例子,根据原始代码进行了一些小修补:

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");
        }
    }
}

嗨,@kotatsuyaki 謝謝你的回答。 我測試了你的代碼,但是沒有起作用!你知道在 Rust 中檢查兩個 sha256 的最佳方式是什麼嗎? - Emad Deve
我在使用你的答案(@kotatsuyaki)时遇到了“线程'main'恐慌,无法解码十六进制字符串:OddLength”错误。 - Emad Deve
正如hex::FromHexError文档所建议的,你得到的错误意味着你传递给hex::decode的字符串长度是奇数,而应该是偶数。你传递给hex::decode什么了?你能打印出来以进行调试吗? - kotatsuyaki
我明白你的意思,但它不起作用。我不知道原因,你自己尝试过这段代码吗?恐慌发生在完全相同的行。我无法打印它。 - Emad Deve
感谢您的耐心和支持。您的代码已经生效。 - Emad Deve
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接