首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将密码::sha2::sha2 256散列转换为&[u8]表示?

如何将密码::sha2::sha2 256散列转换为&[u8]表示?
EN

Stack Overflow用户
提问于 2018-04-26 08:47:37
回答 1查看 2.1K关注 0票数 9

我目前正在尝试从一个ED25519哈希(通过rust-crypto机箱)生成一个rust-crypto键区:

代码语言:javascript
复制
extern crate crypto; // rust-crypto = "0.2.36"

use crypto::ed25519;
use crypto::sha2::Sha256;
use crypto::digest::Digest;

fn main() {
    let phrase = "purchase hobby popular celery evil fantasy someone party position gossip host gather";
    let mut seed = Sha256::new();
    seed.input_str(&phrase);
    let (_priv, _publ) = ed25519::keypair(&seed); // expects slice
}

但是,我完全不理解如何正确地将SHA256传递给ed25519::keypair()函数。我追踪到&seed.result_str()的结果是:

代码语言:javascript
复制
"fc37862cb425ca4368e8e368c54bb6ea0a1f305a225978564d1bdabdc7d99bdb"

这是正确的哈希,而&seed.result_str().as_bytes()的结果是:

代码语言:javascript
复制
[102, 99, 51, 55, 56, 54, 50, 99, 98, 52, 50, 53, 99, 97, 52, 51, 54, 56, 101, 56, 101, 51, 54, 56, 99, 53, 52, 98, 98, 54, 101, 97, 48, 97, 49, 102, 51, 48, 53, 97, 50, 50, 53, 57, 55, 56, 53, 54, 52, 100, 49, 98, 100, 97, 98, 100, 99, 55, 100, 57, 57, 98, 100, 98]

这是我不想要的,完全不同的东西。现在的问题主要是:

代码语言:javascript
复制
   |
36 |     let (_priv, _publ) = ed25519::keypair(&seed);
   |                                           ^^^^^ expected slice, found struct `crypto::sha2::Sha256`
   |
   = note: expected type `&[u8]`
              found type `&crypto::sha2::Sha256`

如何正确地将crypto::sha2::Sha256哈希转换为[u8]表示?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-26 12:09:34

最初,Sha256 API可能有点混乱,因为它的设计目的是不为数据分配任何新内存。这是为了避免浪费内存分配,以防您自己分配内存。相反,您给它一个可以写入的缓冲区:

代码语言:javascript
复制
// Create a buffer in which to write the bytes, making sure it's
// big enough for the size of the hash
let mut bytes = vec![0; seed.output_bytes()];
// Write the raw bytes from the hash into the buffer
seed.result(&mut bytes);

// A reference to a Vec can be coerced to a slice
let (_priv, _publ) = ed25519::keypair(&bytes);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50038666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档