1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#![cfg(feature = "crypto")]

extern crate rand;

use std::borrow::Cow;

use rand::RngCore;

/// Generate a random 16-byte salt.
#[inline]
pub fn gen_salt() -> [u8; 16] {
    let mut salt = [0u8; 16];

    rand::thread_rng().fill_bytes(&mut salt);

    salt
}

/// Check the password and make it terminated with a null byte, `0u8`.
pub fn get_password_with_null_terminated_byte<T: ?Sized + AsRef<[u8]>>(
    password: &T,
) -> Cow<[u8]> {
    let password = password.as_ref();

    let password_len = password.len();

    if password_len > 0 {
        let mut i = 0;

        while i < password_len && password[i] > 0 {
            i += 1;
        }

        if i == password_len - 1 {
            Cow::from(password)
        } else {
            let mut new_password = Vec::with_capacity(i + 1);

            new_password.extend_from_slice(&password[..i]);

            new_password.push(0);

            Cow::from(new_password)
        }
    } else {
        Cow::from(password)
    }
}

/// Use bcrypt to hash a password (the null-terminated byte will not be added automatically) whose length is not bigger than 72 bytes to 24 bytes data. If the salt is not 16 bytes, it will be MD5 hashed first.
#[inline]
pub fn bcrypt<T: ?Sized + AsRef<[u8]>, K: ?Sized + AsRef<[u8]>>(
    cost: u8,
    salt: &K,
    password: &T,
) -> Result<[u8; 24], &'static str> {
    if cost >= 32 {
        return Err("Cost needs to be smaller than 32.");
    }

    let password = password.as_ref();

    let password_len = password.len();

    if password_len == 0 {
        return Err("The password is empty.");
    }

    if password_len > 72 {
        return Err("The length of the password should not be bigger than 72.");
    }

    let salt = salt.as_ref();

    let mut hash = [0u8; 24];

    if salt.len() != 16 {
        let new_salt = md5::compute(salt);
        bcrypt::bcrypt(cost as u32, &*new_salt, password, &mut hash);
    } else {
        bcrypt::bcrypt(cost as u32, salt, password, &mut hash);
    }

    Ok(hash)
}

/// Identify a password (the null-terminated byte will not be added automatically) by using the bcrypt-hashed data we've stored before.
///
/// Use this function carefully because it assumes its input parameters are always correct.
///
/// Typically, the unidentified password should be hashed on the client-side instead of using this function on the server-side.
#[allow(clippy::missing_safety_doc)]
#[inline]
pub unsafe fn identify_bcrypt<T: ?Sized + AsRef<[u8]>, K: ?Sized + AsRef<[u8]>>(
    cost: u8,
    salt: &K,
    password: &T,
    hashed: &[u8],
) -> bool {
    match bcrypt(cost, salt, password) {
        Ok(hash) => hashed[..23].eq(&hash[..23]),
        Err(_) => false,
    }
}

/// Use bcrypt to hash a password (the null-terminated byte will not be added automatically) whose length is not bigger than 72 bytes to 24 bytes data. The result will be in Modular Crypt Format. If the salt is not 16 bytes, it will be MD5 hashed first.
pub fn bcrypt_format<T: ?Sized + AsRef<[u8]>, K: ?Sized + AsRef<[u8]>>(
    cost: u8,
    salt: &K,
    password: &T,
) -> Result<String, &'static str> {
    if cost >= 32 {
        return Err("Cost needs to be smaller than 32.");
    }

    let password = password.as_ref();

    let password_len = password.len();

    if password_len == 0 {
        return Err("The password is empty.");
    }

    if password_len > 72 {
        return Err("The length of the password should not be bigger than 72.");
    }

    let salt = salt.as_ref();

    let mut hash = [0u8; 24];

    let salt = if salt.len() != 16 {
        let new_salt = *md5::compute(salt);
        bcrypt::bcrypt(cost as u32, &new_salt, password, &mut hash);

        base64::encode_config(&new_salt, base64::BCRYPT)
    } else {
        bcrypt::bcrypt(cost as u32, salt, password, &mut hash);

        base64::encode_config(salt, base64::BCRYPT)
    };

    let hash = base64::encode_config(&hash[..23], base64::BCRYPT);

    Ok(format!("$2b${:02}${}{}", cost, salt, hash))
}

/// Identify a password (the null-terminated byte will not be added automatically) by using the bcrypt-hashed data in Modular Crypt Format we've stored before.
///
/// Use this function carefully because it assumes its input parameters are always correct.
///
/// Typically, the unidentified password should be hashed on the client-side instead of using this function on the server-side.
#[allow(clippy::missing_safety_doc)]
pub unsafe fn identify_bcrypt_format<T: ?Sized + AsRef<[u8]>, S: AsRef<str>>(
    password: &T,
    hashed_format: S,
) -> bool {
    let hashed_format = hashed_format.as_ref();
    let hashed_format_len = hashed_format.len();

    let cost_index = if hashed_format_len == 59 {
        // $2$
        3
    } else if hashed_format_len == 60 {
        // $2a$, $2b$, ...
        4
    } else {
        return false;
    };

    let cost = match hashed_format[cost_index..cost_index + 2].parse::<u8>() {
        Ok(cost) => cost,
        Err(_) => return false,
    };

    let salt = match base64::decode_config(
        &hashed_format[cost_index + 3..cost_index + 25],
        base64::BCRYPT,
    ) {
        Ok(salt) => salt,
        Err(_) => return false,
    };

    let hashed = match base64::decode_config(&hashed_format[cost_index + 25..], base64::BCRYPT) {
        Ok(hashed) => hashed,
        Err(_) => return false,
    };

    identify_bcrypt(cost, &salt, password, &hashed)
}