如何将sha256获取为`&[u8; 32]`?

huangapple go评论65阅读模式
英文:

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::Sha256digest()函数。(由于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: &amp;[u8]) -&gt; 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&lt;u8, 32&gt; 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().

huangapple
  • 本文由 发表于 2023年7月17日 23:51:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76706174.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定