我想将字符串( 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()
}编译器说:
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()
| ^^^^^^我可以看出这是真的;它看起来像[u8]。
我该怎么办?有没有实现从字符串转换为十六进制的方法?
我的Cargo.toml依赖关系:
[dependencies]
rust-crypto = "0.2.36"
rustc-serialize = "0.3.24"编辑我刚刚意识到字符串已经是六进制格式从锈迹密码库。哦哦。
发布于 2014-12-16 07:58:03
我将在这里讨论一下,并建议hash是Vec<u8>类型的解决方案。
问题是,虽然您确实可以使用String将&[u8]转换为as_bytes,然后使用to_hex,但首先需要有一个有效的String对象。
虽然可以将任何String对象转换为&[u8],但情况并非如此。String对象仅用于保存有效的UTF-8编码的Unicode字符串:并非所有字节模式都符合条件。
因此,gen_sha256生成String是不正确的。更正确的类型是Vec<u8>,它确实可以接受任何字节模式。从那时起,调用to_hex就很容易了:
hash.as_slice().to_hex()发布于 2014-12-15 21:47:17
看来ToHex的源代码有我正在寻找的解决方案。它包含一个测试:
#[test]
pub fn test_to_hex() {
assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172");
}我修改的代码是:
let hash = gen_sha256("example");
hash.as_bytes().to_hex()这似乎奏效了。如果有人有其他的答案,我会花一些时间接受这个解决方案。
发布于 2018-01-28 11:22:52
可以使用如下函数生成十六进制表示:
pub fn hex_push(buf: &mut String, blob: &[u8]) {
for ch in blob {
fn hex_from_digit(num: u8) -> char {
if num < 10 {
(b'0' + num) as char
} else {
(b'A' + num - 10) as char
}
}
buf.push(hex_from_digit(ch / 16));
buf.push(hex_from_digit(ch % 16));
}
}这比当前用该语言实现的泛型基格式设置更有效率。
这是一个基准测试
test bench_specialized_hex_push ... bench: 12 ns/iter (+/- 0) = 250 MB/s
test bench_specialized_fomat ... bench: 42 ns/iter (+/- 12) = 71 MB/s
test bench_specialized_format ... bench: 47 ns/iter (+/- 2) = 63 MB/s
test bench_specialized_hex_string ... bench: 76 ns/iter (+/- 9) = 39 MB/s
test bench_to_hex ... bench: 82 ns/iter (+/- 12) = 36 MB/s
test bench_format ... bench: 97 ns/iter (+/- 8) = 30 MB/shttps://stackoverflow.com/questions/27492969
复制相似问题