如何在Rust中将字符串转换为十六进制?

les*_*how 7 hex type-conversion rust

我想在Rust中将一串字符(SHA256哈希)转换为十六进制:

extern crate crypto;
extern crate rustc_serialize;

use rustc_serialize::hex::ToHex;
use crypto::digest::Digest;
use crypto::sha2::Sha256;

fn gen_sha256(hashme: &str) -> String {
    let mut sh = Sha256::new();
    sh.input_str(hashme);

    sh.result_str()
}

fn main() {
    let hash = gen_sha256("example");

    hash.to_hex()
}
Run Code Online (Sandbox Code Playgroud)

编译器说:

error[E0599]: no method named `to_hex` found for type `std::string::String` in the current scope
  --> src/main.rs:18:10
   |
18 |     hash.to_hex()
   |          ^^^^^^
Run Code Online (Sandbox Code Playgroud)

我可以看到这是真的; 看起来它只是实现了[u8].

我是什么做的?在Rust中没有实现从字符串转换为十六进制的方法吗?

我的Cargo.toml依赖项:

[dependencies]
rust-crypto = "0.2.36"
rustc-serialize = "0.3.24"
Run Code Online (Sandbox Code Playgroud)

编辑我刚刚从rust-crypto库中发现字符串已经是十六进制格式.D'哦.

Mat*_* M. 13

我会在这里走出困境,并建议解决方案是hash类型的Vec<u8>.


问题在于,虽然您确实可以将a转换String&[u8]using as_bytes然后使用to_hex,但您首先需要有一个有效的String对象来开始.

虽然任何String对象都可以转换为a &[u8],但事实并非如此.一个String对象仅意味着持有有效的UTF-8编码的Unicode字符串:不是所有的字节模式出线.

因此,gen_sha256生产a 是不正确的String.更正确的类型Vec<u8>可以确实接受任何字节模式.从那时起,调用to_hex很容易:

hash.as_slice().to_hex()
Run Code Online (Sandbox Code Playgroud)


les*_*how 5

它似乎是ToHex我正在寻找的解决方案的来源.它包含一个测试:

#[test]
pub fn test_to_hex() {
    assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172");
}
Run Code Online (Sandbox Code Playgroud)

我修改后的代码是:

let hash = gen_sha256("example");

hash.as_bytes().to_hex()
Run Code Online (Sandbox Code Playgroud)

这似乎有效.如果有人有其他答案,我会花一些时间接受这个解决方案.