utf-8rustbcryptprintln

Rust println! prints weird characters under certain circumstances


I'm trying to write a short program (short enough that it has a simple main function). First, I should list the dependency in the cargo.toml file:

[dependencies]

passwords = {version = "3.1.3", features = ["crypto"]}

Then when I use the crate in main.rs:

extern crate passwords;

use passwords::hasher;

fn main() {
    let args: Vec<String> = std::env::args().collect();

    if args.len() < 2
    {
        println!("Error! Needed second argument to demonstrate BCrypt Hash!");
        return;
    }

    let password = args.get(1).expect("Expected second argument to exist!").trim();

    let hash_res = hasher::bcrypt(10, "This_is_salt", password);

    match hash_res
    {
        Err(_) => {println!("Failed to generate a hash!");},
        Ok(hash) => { 
            let str_hash = String::from_utf8_lossy(&hash);
            println!("Hash generated from password {} is {}", password, str_hash);
        }
    }
}

The issue arises when I run the following command:

$ target/debug/extern_crate.exe trooper1

And this becomes the output:

?sC�M����k��ed from password trooper1 is ���Ka .+:�

However, this input:

$ target/debug/extern_crate.exe trooper3

produces this:

Hash generated from password trooper3 is ��;��l�ʙ�Y1�>R��G�Ѡd

I'm pretty content with the second output, but is there something within UTF-8 that could cause the "Hash generat" portion of the output statement to be overwritten? And is there code I could use to prevent this?

Note: Code was developed in Visual Studio Code in Windows 10, and was compiled and run using an embedded Git Bash Terminal.

P.S.: I looked at similar questions such as Rust println! problem - weird behavior inside the println macro and Why does my string not match when reading user input from stdin? but those issues seem to be issues with new-line and I don't think that's the problem here.


Solution

  • You could convert the hash to hex before printing it to prevent this