1use blowfish::Blowfish;
2
3fn setup(cost: u32, salt: &[u8], key: &[u8]) -> Blowfish {
4 assert!(cost < 32);
5 let mut state = Blowfish::bc_init_state();
6
7 state.salted_expand_key(salt, key);
8 for _ in 0..1u32 << cost {
9 state.bc_expand_key(key);
10 state.bc_expand_key(salt);
11 }
12
13 state
14}
15
16pub fn bcrypt(cost: u32, salt: [u8; 16], password: &[u8]) -> [u8; 24] {
17 assert!(!password.is_empty() && password.len() <= 72);
18
19 let mut output = [0; 24];
20
21 let state = setup(cost, &salt, password);
22 #[allow(clippy::unreadable_literal)]
24 let mut ctext = [
25 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274,
26 ];
27 for i in 0..3 {
28 let i: usize = i * 2;
29 for _ in 0..64 {
30 let [l, r] = state.bc_encrypt([ctext[i], ctext[i + 1]]);
31 ctext[i] = l;
32 ctext[i + 1] = r;
33 }
34
35 let buf = ctext[i].to_be_bytes();
36 output[i * 4..][..4].copy_from_slice(&buf);
37 let buf = ctext[i + 1].to_be_bytes();
38 output[(i + 1) * 4..][..4].copy_from_slice(&buf);
39 }
40
41 output
42}
43
44#[cfg(test)]
45mod tests {
46 use super::bcrypt;
47
48 #[test]
49 fn raw_bcrypt() {
50 let pw = b"\0";
55 let cost = 6;
56 let salt = [
57 0x14, 0x4b, 0x3d, 0x69, 0x1a, 0x7b, 0x4e, 0xcf, 0x39, 0xcf, 0x73, 0x5c, 0x7f, 0xa7,
58 0xa7, 0x9c,
59 ];
60 let result = [
61 0x55, 0x7e, 0x94, 0xf3, 0x4b, 0xf2, 0x86, 0xe8, 0x71, 0x9a, 0x26, 0xbe, 0x94, 0xac,
62 0x1e, 0x16, 0xd9, 0x5e, 0xf9, 0xf8, 0x19, 0xde, 0xe0,
63 ];
64 assert_eq!(bcrypt(cost, salt, pw)[..23], result);
65
66 let pw = b"a\0";
68 let cost = 6;
69 let salt = [
70 0xa3, 0x61, 0x2d, 0x8c, 0x9a, 0x37, 0xda, 0xc2, 0xf9, 0x9d, 0x94, 0xda, 0x3, 0xbd,
71 0x45, 0x21,
72 ];
73 let result = [
74 0xe6, 0xd5, 0x38, 0x31, 0xf8, 0x20, 0x60, 0xdc, 0x8, 0xa2, 0xe8, 0x48, 0x9c, 0xe8,
75 0x50, 0xce, 0x48, 0xfb, 0xf9, 0x76, 0x97, 0x87, 0x38,
76 ];
77 assert_eq!(bcrypt(cost, salt, pw)[..23], result);
78
79 let pw = b"abcdefghijklmnopqrstuvwxyz\0";
81 let cost = 8;
82 let salt = [
83 0x71, 0x5b, 0x96, 0xca, 0xed, 0x2a, 0xc9, 0x2c, 0x35, 0x4e, 0xd1, 0x6c, 0x1e, 0x19,
84 0xe3, 0x8a,
85 ];
86 let result = [
87 0x98, 0xbf, 0x9f, 0xfc, 0x1f, 0x5b, 0xe4, 0x85, 0xf9, 0x59, 0xe8, 0xb1, 0xd5, 0x26,
88 0x39, 0x2f, 0xbd, 0x4e, 0xd2, 0xd5, 0x71, 0x9f, 0x50,
89 ];
90 assert_eq!(bcrypt(cost, salt, pw)[..23], result);
91 }
92}