Help hashing a password using bcrypt_pbkdf and the crypto crate


#1

I have the following program but it’s outputting a strange result and I have no idea what I am doing :smile:

extern crate crypto;

use crypto::bcrypt_pbkdf::{bcrypt_pbkdf};

fn main() {
    
    let mut out = [0u8; 32];
    bcrypt_pbkdf(b"password", b"salt", 5, &mut out);
    
    let mut password_hash = String::with_capacity(out.len());
    
    for c in out.iter() {
        password_hash.push(*c as char);
    }
    
    println!("Hash: {}", password_hash);
    
    // Hash: A7ÿÜ(8)%i⎺Õ;Ž¡ÚØ÷›│·H­¾┬±Î[▮
}

I tried to use a function to create a String from a [u8] array, but that blows up in the unwrap

extern crate crypto;

use crypto::bcrypt_pbkdf::{bcrypt_pbkdf};

fn main() {
    
    let mut out = [0u8; 32];
    bcrypt_pbkdf(b"password", b"salt", 5, &mut out);
    
    let vector: Vec<u8> = Vec::from(&out[..]);
    let password_hash = String::from_utf8(vector).unwrap();
    println!("Hash: {}", password_hash);
}

This is the error:

thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: FromUtf8Error { bytes: [65, 55, 255, 5, 220, 40, 56, 41, 37, 105, 14, 111, 213, 59, 142, 161, 18, 218, 2, 216, 247, 155, 120, 126, 72, 173, 190, 119, 177, 206, 91, 48], error: Utf8Error { valid_up_to: 2 } }', /home/rustbuild/src/rust-buildbot/slave/stable-dist-rustc-linux/build/src/libcore/result.rs:729
    An unknown error occurred

#2

A hash output is binary. The pretty strings you usually see and seem to expect are produced by converting that into hexadecimal or some other printable representation. String::from_utf8 returns an error because the data you give it is not a [valid utf-8] string but some random bytes.

This will (inefficiently) produce a hexadecimal string.

    let mut password_hash = String::with_capacity(out.len() * 2);
    for c in out.iter() {
        password_hash.push_str(&format!("{:02x}", c));
    }

Trying to make bcrypt hashes with crypto
#3

Hi thanks for pointing that out!

Question: Why are you using binary.len() * 2 as the length? Is that just to make sure the String has extra capacity?


#4

Each byte is represented by two characters 00, 01, …, ff.


#5

I guess I should go do some reading up :slight_smile: http://kunststube.net/encoding/