rust - 如何将 crypto::sha2::Sha256 哈希转换为 &[u8] 表示?
问题描述
我目前正在尝试从 SHA256 哈希(通过rust-crypto
crate)生成 ED25519 密钥对:
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()
结果是:
"fc37862cb425ca4368e8e368c54bb6ea0a1f305a225978564d1bdabdc7d99bdb"
这是正确的哈希,而&seed.result_str().as_bytes()
结果是:
[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]
这是我不想要的,完全不同的东西。现在问题分解为:
|
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]
表示形式?
解决方案
API 起初可能有点令人Sha256
困惑,因为它被设计为不会为数据分配任何新内存。这是为了避免浪费内存分配,以防您想自己分配。相反,你给它一个缓冲区来写入:
// 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);
推荐阅读
- html - 轮播指示器,没有引导程序,没有任何功能
- c# - 'ArrayPool 之间的时间比较
.Shared.Rent' 和 'new T[]' - python - TypeError:“Piece”对象在 Python 中的类类型中不可下标
- django - 多对多运行 2n 查询上的 Django DRF 序列化程序方法字段
- php - Laravel 7 Muti Auth 使用 Laravel UI
- javascript - 仅在单击按钮时更改显示
- c - 以未指定的顺序使用具有副作用的函数是未定义的行为吗?
- react-native - 更改主题 Epub 书不适用于 Epubjs-rn 包中的某些 Html 标记
- python - ValueError:长度不匹配:预期轴有 2 个元素,新值有 3 个元素
- internet-explorer - 有没有办法在外部位置实时捕获浏览器>开发工具>控制台>“导航到”值而不访问网络应用程序代码?