【问题标题】:How to convert the hash as string? [duplicate]如何将哈希转换为字符串? [复制]
【发布时间】:2020-12-05 00:27:17
【问题描述】:

如何将哈希打印为字符串?

use sha3::{Digest, Keccak256};

fn main() {
    let vote = "Alice".to_owned();
    let mut hasher = Keccak256::new();
    hasher.update(vote.as_bytes());
    let result = hasher.finalize();
    let hashstring = result.to_owned();
    println!("{:?}", hashstring);
    // [129, 55, 107, 152, 104, 178, 146, 164, 106, 28, 72, 109, 52, 78, 66, 122, 48, 136, 101, 127, 218, 98, 155, 95, 74, 100, 120, 34, 211, 41, 205, 106]
    // I need the hex string, instead of numbers
}

sha3 docs

【问题讨论】:

  • 通常将二进制数据转换为十六进制字符串以显示它(Function hex::encode)。或者您可以使用 base-64 (base64)。
  • 是的@Herohtar 谢谢。

标签: rust sha


【解决方案1】:

根据 Andrew Morton,这是我的回答:

use sha3::{Digest, Keccak256};
use hex;

fn main() {
    let vote = "Alice".to_owned();
    let mut hasher = Keccak256::new();
    hasher.update(vote.as_bytes());
    let result = hasher.finalize();
    println!("{:?}", hex::encode(result));
    // "81376b9868b292a46a1c486d344e427a3088657fda629b5f4a647822d329cd6a"
}

【讨论】:

    【解决方案2】:

    您不需要任何额外的板条箱。只需将其格式化为大写或小写十六进制:

    use sha3::{Digest, Keccak256};
    
    fn main() {
        let vote = "Alice".to_owned();
        let mut hasher = Keccak256::new();
        hasher.update(vote.as_bytes());
        let result = hasher.finalize();
        println!("{:x}", result); // 81376b9868b292a46a1c486d344e427a3088657fda629b5f4a647822d329cd6a
        println!("{:X}", result); // 81376B9868B292A46A1C486D344E427A3088657FDA629B5F4A647822D329CD6A
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2016-10-21
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2019-08-26
      相关资源
      最近更新 更多