Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hash output of sha256 with sha256 in rust

I've written some rust code which has a lifetime problem.

let mut sha256 = Sha256::new();
sha256.input_str(input.as_slice());

for i in range(0i,16) {
    println!("i == {}, hash == {}", i, sha256.result_str());
    let bytes = sha256.result_bytes().as_slice();
    sha256.input(bytes);
}

The error is:

$ cargo build && ./target/hello_world asdfasdf
   Compiling hello_world v0.1.0 (file:///home/chris/hello_world)
src/hello_world.rs:41:21: 41:42 error: borrowed value does not live long enough
src/hello_world.rs:41         let bytes = sha256.result_bytes().as_slice();
                                          ^~~~~~~~~~~~~~~~~~~~~
src/hello_world.rs:39:27: 43:6 note: reference must be valid for the block at 39:26...
src/hello_world.rs:39     for i in range(0i,16) {
src/hello_world.rs:40         println!("i == {}, hash == {}", i, sha256.result_str());
src/hello_world.rs:41         let bytes = sha256.result_bytes().as_slice();
src/hello_world.rs:42         sha256.input(bytes);
src/hello_world.rs:43     }
src/hello_world.rs:41:9: 41:53 note: ...but borrowed value is only valid for the statement at 41:8; consider using a `let` binding to increase its lifetime
src/hello_world.rs:41         let bytes = sha256.result_bytes().as_slice();
                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `hello_world`.

To learn more, run the command again with --verbose.

How can I alter this, and still let it execute efficiently?

like image 306
fadedbee Avatar asked Oct 06 '14 16:10

fadedbee


People also ask

Can you decode a SHA256 hash?

SHA-256 is a cryptographic (one-way) hash function, so there is no direct way to decode it. The entire purpose of a cryptographic hash function is that you can't undo it.

Is SHA-2 and SHA-256 the same?

If you see “SHA-2,” “SHA-256” or “SHA-256 bit,” those names are referring to the same thing. If you see “SHA-224,” “SHA-384,” or “SHA-512,” those are referring to the alternate bit-lengths of SHA-2.


1 Answers

That's because the result from result_bytes() is being discarded after that line and as_slice() is getting a reference to it. The borrow checker won't let it happen.

For it to work you should write it like:

let mut sha256 = Sha256::new();
sha256.input_str(input.as_slice());

for i in range(0i,16) {
    println!("i == {}, hash == {}", i, sha256.result_str());
    let bytes = sha256.result_bytes();
    sha256.reset();
    sha256.input(bytes.as_slice());
}

Hope it helped.

like image 85
snf Avatar answered Oct 13 '22 09:10

snf