简体   繁体   中英

Rust: How to hash a string?

I'm trying to create a console application in Rust where you have to enter a password to access the rest of the file, so I wanted to ensure that you can't just read the file to find the password, so I wanted to store the password as a hash, so its (improbably) irreversable.

I looked up hashing in Rust, but they seem to be only usable with structs, while I'm trying to insert a String. Is a struct the only way to be able to do this?

Thanks

The built-in Hash class in Rust is designed to process data for the purpose of entry into a HashMap or HashSet. This isn't suitable for password verification.

If you want to perform password verification, you should use a password hash like Argon2id or scrypt. You can find these in the argon2 and scrypt crates. Password hashes always take bytes, so you will want to access your String as a &[u8] . The password_hash crate provides traits you can use to turn these into a serialized password.

If your goal is to encrypt the remainder of the file with the password, then you should use one of the bindings to NaCl. This library has primitives that are designed to be secure. You would use the password hash functionality with a random salt to generate a key, and then use that as the key input to a secret box with a random nonce. There are other ways to do this, but unless you are well versed in cryptography, using NaCl is a smart choice since it is harder to misuse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM