Search code examples
rustsha256sha

How to convert a crypto::sha2::Sha256 hash into a &[u8] representation?


I'm currently trying to generate an ED25519 keypair from a SHA256 hash (via rust-crypto crate):

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
}

However, I totally fail to understand how to correctly pass the SHA256 to the ed25519::keypair() function. I traced down that &seed.result_str() results in:

"fc37862cb425ca4368e8e368c54bb6ea0a1f305a225978564d1bdabdc7d99bdb"

This is the correct hash, while &seed.result_str().as_bytes() results in:

[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]

Which is something I do not want, something entirely different. The question now breaks down to:

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

How to correctly convert the crypto::sha2::Sha256 hash into a [u8] representation?


Solution

  • The Sha256 API may be a little confusing at first because it is designed so that it doesn't allocate any new memory for the data. That's to avoid wasting a memory allocation, in case you want to allocate it yourself. Instead, you give it a buffer to write to:

    // 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);