简体   繁体   English

Rust:如何 hash 一个字符串?

[英]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.我正在尝试在 Rust 中创建一个控制台应用程序,您必须在其中输入密码才能访问文件的 rest,所以我想确保您不能只读取文件来查找密码,所以我想存储密码为 hash,因此它(不可能)不可逆。

I looked up hashing in Rust, but they seem to be only usable with structs, while I'm trying to insert a String.我在 Rust 中查找了散列,但它们似乎只能用于结构,而我正在尝试插入一个字符串。 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. Rust 中的内置 Hash class 旨在处理数据以进入 Z063A5BC470661C37C75ZE 或 HashSetB7E。 This isn't suitable for password verification.这不适用于密码验证。

If you want to perform password verification, you should use a password hash like Argon2id or scrypt.如果要执行密码验证,则应使用密码 hash,如 Argon2id 或 scrypt。 You can find these in the argon2 and scrypt crates.您可以在argon2scrypt板条箱中找到这些。 Password hashes always take bytes, so you will want to access your String as a &[u8] .密码哈希总是占用字节,因此您需要将 String 作为&[u8]访问。 The password_hash crate provides traits you can use to turn these into a serialized password. password_hash crate 提供了可以用来将它们转换为序列化密码的特征。

If your goal is to encrypt the remainder of the file with the password, then you should use one of the bindings to NaCl.如果您的目标是使用密码加密文件的其余部分,那么您应该使用与 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.您将使用密码 hash 功能和随机盐来生成密钥,然后将其用作具有随机随机数的秘密框的密钥输入。 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.还有其他方法可以做到这一点,但除非您精通密码学,否则使用 NaCl 是一个明智的选择,因为它更难被滥用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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