我正在尝试使用 sodiumoxide 提供的 SHA256 哈希函数编写一个 hash_string
函数。此函数应接受一个字符串并返回表示为字符串的字符串的哈希值。
这是我目前所拥有的:
extern crate sodiumoxide;
use std::string::String;
use sodiumoxide::crypto::hash::sha256;
pub fn hash_string(s: String) -> String {
let digest = sha256::hash(&s.into_bytes());
String::from_utf8_unchecked(digest).to_owned()
}
显然这是不正确的,但我不知道如何解决。
我能够用 rust-crypto 实现这个 crate 。
pub fn hash_string(input: String) -> String {
let mut sha = Sha256::new();
sha.input_str(&input);
sha.result_str()
}
我想完全按照上面的方法做,但改用氧化钠 crate 。
最佳答案
根据您链接的文档, Digest
定义为:
pub struct Digest(pub [u8; 32]);
您可以使用元组索引符号访问这些字节:foo.0
.它还实现了 AsRef<[u8]>
.
然后您可以只使用现有答案之一将切片转换为十六进制,例如 Show u8 slice in hex representation 中的答案.
extern crate sodiumoxide;
use sodiumoxide::crypto::hash::sha256;
use std::fmt;
pub fn hash_string(s: &str) -> String {
let digest = sha256::hash(s.as_bytes());
format!("{:X}", HexSlice::new(&digest))
}
struct HexSlice<'a>(&'a [u8]);
impl<'a> HexSlice<'a> {
fn new<T>(data: &'a T) -> HexSlice<'a>
where T: ?Sized + AsRef<[u8]> + 'a
{
HexSlice(data.as_ref())
}
}
impl<'a> fmt::UpperHex for HexSlice<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in self.0 {
// Decide if you want upper- or lowercase results,
// padding the values to two characters, spaces
// between bytes, etc.
write!(f, "{:X}", byte)?;
}
Ok(())
}
}
fn main() {
let h = hash_string("hello world");
println!("{}", h);
}
请注意,使用拥有的 String
没有任何好处。因为我们不使用分配。
关于hash - 如何使用氧化钠 crate 对字符串进行哈希处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43968723/