密码是一种最常用来验证身份的机制,例如在登录用户帐号时,常会搭配密码一起输入,以确保访问这个帐号的人是帐号的拥有人或是代理人。由于密码就像是身份证一样的东西,因此不能太简单,太简单就会容易被人猜到,或是被电脑程序破解。在撰写程序的时候,我们常会需要检查、验证及保存用户输入的密码,或是产生出密码以供用户或是系统本身使用。若是使用 Rust 编程语言的话,要如何处理密码的相关功能呢?

Passwords

「Passwords」是笔者开发的套件,提供四大功能:密码产生(Generator)、密码哈希(Hasher)、密码分析(Analyzer)和密码评分(Scorer)。

Crates.io

Cargo.toml

passwords = "*"

使用方法

密码产生

使用 use 关键字来将 passwords 这个 crate 底下的 PasswordGenerator 结构体给引用到当前的程序范围下。PasswordGenerator 结构体拥有以下几个字段,可以控制其实体产生密码的规则:

  • length:密码长度。
  • numbers:是否要包含数字(0123456789)。
  • lowercase_letters:是否要包含小写英文字母(abcdefghijklmnopqrstuvwxyz)。
  • uppercase_letters:是否要包含大写英文字母(ABCDEFGHIJKLMNOPQRSTUVWXYZ)。
  • symbols:是否要包含符号(!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~)。
  • spaces:是否要包含空白字符( )。
  • exclude_similar_characters:见底下说明。
  • strict:是否每种激活的字符都要包含。

由于 0(零)、O(大写欧)、o(小写欧)和 i、l、I、1、| 以及 "、'、` 很像,在某些特定字体下甚至完全无法将它们区分。所以 PasswordGenerator 结构体还有提供 exclude_similar_characters 字段,可以不用以上枚举的易混淆字符来产生密码。

PasswordGenerator 结构体产生出来的实体有两个主要的方法,generate_one 方法会产生出一组密码,generate 会产生出多组密码。

举例来说:

use passwords::PasswordGenerator;

let pg = PasswordGenerator {
       length: 8,
       numbers: true,
       lowercase_letters: true,
       uppercase_letters: true,
       symbols: true,
       spaces: true,
       exclude_similar_characters: true,
       strict: true,
};

println!("{}", pg.generate_one().unwrap());
println!("{:?}", pg.generate(5).unwrap());

PasswordGenerator 结构体有支持 Fluent Interface,用法如下:

use passwords::PasswordGenerator;

let pg = PasswordGenerator::new().length(8).numbers(true).lowercase_letters(true).uppercase_letters(true).symbols(true).spaces(true).exclude_similar_characters(true).strict(true);

println!("{}", pg.generate_one().unwrap());
println!("{:?}", pg.generate(5).unwrap());

generate 方法有针对产生多组密码进行优化,不要重复使用 generate_one 方法来产生密码。如果我们没有办法事先确定好密码的数量,可以使用 PasswordGenerator 结构实体提供的 try_iter 方法来创建 PasswordGeneratorIter 结构实体,它有实作 Iterator 特性,且可以更有效率地重复产生密码,因为它不像 PasswordGenerator 结构实体在每次调用方法来产生密码前都要创建新的字符池(Character Pool)。

use passwords::PasswordGenerator;

let pgi = PasswordGenerator::new().try_iter().unwrap();

println!("{}", pgi.generate_one());
println!("{:?}", pgi.generate(5));
use passwords::PasswordGenerator;

let mut pgi = PasswordGenerator::new().try_iter().unwrap();

println!("{}", pgi.next().unwrap());
println!("{}", pgi.next().unwrap());
密码哈希

若需要将密码哈希之后保存下来,可以激活「Passwords」套件的 crypto 特色,Cargo.toml 设置档的写法如下:

[dependencies.passwords]
version = "*"
features = ["crypto"]

crypto 特色激活之后,就可以使用 use 关键字来将 passwords 这个 crate 底下的 hasher 模块给引用到当前的程序范围下。hasher 模块有 6 个函数,gen_salt 函数可以产生出 16 个字节的盐;bcrypt 函数可以利用 bcrypt 算法来计算密码明文的哈希值;identify_bcrypt 函数可以用来判断一个密码明文在哈希之后是否和一个已知的 bcrypt 哈希值是吻合的;bcrypt_format 函数可以利用 bcrypt 算法来计算密码明文的哈希值,并且将结果格式化成 MCF (Modular Crypt Format);identify_bcrypt_format 函数可以用来判断一个密码明文在哈希之后是否和一个已知的 MCF 是吻合的;get_password_with_null_terminated_byte 函数可以用来将密码明文转成以 \0 结尾的数据(以符合 bcrypt 的规定)。

举例来说:

use passwords::hasher;

let salt = hasher::gen_salt();

let hashed = hasher::bcrypt(10, &salt, "password\0").unwrap();
assert!(unsafe { hasher::identify_bcrypt(10, &salt, "password\0", &hashed) });

let mcf = hasher::bcrypt_format(10, &salt, "password\0").unwrap();
assert!(unsafe { hasher::identify_bcrypt_format("password\0", mcf) });
密码分析

使用 use 关键字来将 passwords 这个 crate 底下的 analyzer 模块给引用到当前的程序范围下。analyzer 模块有一个函数,那就是 analyze 函数。这个 analyze 函数可以输入一组密码,将其分析之后会回传 analyzer 模块下的 AnalyzedPassword 结构实体。这个 AnalyzedPassword 结构实体所带的密码分析结果字段如下:

  • password:移除 ASCII 控制码之后的密码明文。
  • length:密码中所有字符的数量。
  • spaces_count:密码中空白字符的数量。
  • numbers_count:密码中数字的数量。
  • lowercase_letters_count:密码中小写英文字母的数量。
  • uppercase_letters_count:密码中大写英文字母的数量。
  • symbols_count:密码中符号的数量。
  • other_characters_count:其它如中文字的字符。
  • consecutive_count:连续重复出现的字符数量。
  • non_consecutive_count:不连续重复出现的字符数量。
  • progressive_count:照顺序出现的字符数量。

举例来说:

use passwords::analyzer;

let password = "ZYX[$BCkQB中文}%A_3456]  H(\rg";

let analyzed = analyzer::analyze(password);

assert_eq!("ZYX[$BCkQB中文}%A_3456]  H(g", analyzed.password()); // "\r" was filtered
assert_eq!(26, analyzed.length()); // Characters' length, instead of that of UTF-8 bytes
assert_eq!(2, analyzed.spaces_count()); // Two spaces between "]" and "H"
assert_eq!(4, analyzed.numbers_count()); // Numbers are "3456"
assert_eq!(2, analyzed.lowercase_letters_count()); // Lowercase letters are "k" and "g"
assert_eq!(9, analyzed.uppercase_letters_count()); // Uppercase letters are "ZYX", "BC", "QB", "A" and "H"
assert_eq!(7, analyzed.symbols_count()); // Symbols are "[$", "}%", "_", "]" and "("
assert_eq!(2, analyzed.other_characters_count()); // Other characters are "中文". These characters are usually not included on the rainbow table.
assert_eq!(2, analyzed.consecutive_count()); // Consecutive repeated characters are "  " (two spaces)
assert_eq!(2, analyzed.non_consecutive_count()); // Non-consecutive repeated characters are "B" (appears twice)
assert_eq!(7, analyzed.progressive_count()); // Progressive characters are "ZYX" and "3456". "BC" is not counted, because its length is only 2, not three or more.

如果想要判断密码是不是在常用不安全密码的清单内,可以激活「Passwords」套件的 common-password 特色,Cargo.toml 设置档的写法如下:

[dependencies.passwords]
version = "*"
features = ["common-password"]

common-password 特色激活之后,AnalyzedPassword 结构实体就会多出 is_common 方法可以使用。若 is_common 方法回传 true,表示该密码是非常危险的!

密码评分

使用 use 关键字来将 passwords 这个 crate 底下的 scorer 模块给引用到当前的程序范围下。scorer 模块有一个函数,那就是 score 函数。这个 score 函数可以传入一个 AnalyzedPassword 结构实体的参考,来计算其所表示的密码的分数,分数会直接以 f64 类型的数值来回传。

举例来说:

use passwords::analyzer;
use passwords::scorer;

assert_eq!(62f64, scorer::score(&analyzer::analyze("kq4zpz13")));
assert_eq!(100f64, scorer::score(&analyzer::analyze("ZYX[$BCkQB中文}%A_3456]  H(\rg")));

if cfg!(feature = "common-password") {
    assert_eq!(11.2f64, scorer::score(&analyzer::analyze("feelings"))); // "feelings" is common, so the score is punitively the original divided by 5
} else {
    assert_eq!(56f64, scorer::score(&analyzer::analyze("feelings")));
}

不同分数区间的涵意如下:

  • 0 ~ 20:非常危险。(有机会在数秒内就被破解)
  • 20 ~ 40:危险。
  • 40 ~ 60:很弱。
  • 60 ~ 80:弱。
  • 80 ~ 90:好。
  • 90 ~ 95:强。
  • 95 ~ 99:很强。
  • 99 ~ 100:极强(坚不可破)。