英文:
How to get a sha256 as an `&[u8; 32]`?
问题
sha256::digest() 函数 返回一个 String。
我可以自己将其转换为 [u8; 32],但对于这个 crate 将字节转换为十六进制字符串,然后我再将这个十六进制字符串转回字节似乎有些浪费。
我如何将 [u8] 切片的 sha256 摘要获取为 &[u8; 32],或者至少作为 &[u8]?
英文:
The sha256::digest() function returns a String.
I can turn this into a [u8; 32] myself, but it seems wasteful for this crate to turn bytes into a hex string, and for me to then turn this hex string back into bytes.
How can I get the sha256 digest of a [u8] slice as an &[u8; 32], or at worst, as an &[u8]?
答案1
得分: 3
如果您查看sha256 crate的源代码,在该接口的下面几个层次中,有一段等效于以下代码的代码:
use sha2::{Digest, Sha256};
impl sha256 {
fn digest(data: &[u8]) -> String {
hex::encode(Sha256::digest(data))
}
}
因此,我认为您的解决方案是直接使用sha2::Sha256的digest()函数。(由于sha2 crate大量使用泛型,文档有点混乱,但我认为它基本上等同于您需要的内容,只是它返回一个GenericArray<u8, 32>而不是[u8; 32],但它应该基本上表现相同,如果需要,可以使用try_into().unwrap()转换为数组。)
英文:
If you look at the source code of the sha256 crate, a few layers below that interface, there is a code equivalent to this:
use sha2::{Digest, Sha256};
impl sha256 {
fn digest(data: &[u8]) -> String {
hex::encode(Sha256::digest(data))
}
}
So I think your solution is to just use the sha2::Sha256::digest() function directly. (The documentation is a bit messy because of the heave use of generics of the sha2 crate, but I think that it is more or less equivalent to what you need, except that it returns a GenericArray<u8, 32> instead of a [u8; 32], but it should behave basically the same, and can be converted into an array if needed with try_into().unwrap().
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论