Skip to main content

postgres_protocol/authentication/
mod.rs

1//! Authentication protocol support.
2use crate::hex::LowerHexWrapper;
3use md5::{Digest, Md5};
4
5pub mod sasl;
6
7/// Hashes authentication information in a way suitable for use in response
8/// to an `AuthenticationMd5Password` message.
9///
10/// The resulting string should be sent back to the database in a
11/// `PasswordMessage` message.
12#[inline]
13pub fn md5_hash(username: &[u8], password: &[u8], salt: [u8; 4]) -> String {
14    let mut md5 = Md5::new();
15    md5.update(password);
16    md5.update(username);
17    let output = LowerHexWrapper(md5.finalize_reset());
18    md5.update(format!("{output:x}"));
19    md5.update(salt);
20    format!("md5{:x}", LowerHexWrapper(md5.finalize()))
21}
22
23#[cfg(test)]
24mod test {
25    use super::*;
26
27    #[test]
28    fn md5() {
29        let username = b"md5_user";
30        let password = b"password";
31        let salt = [0x2a, 0x3d, 0x8f, 0xe0];
32
33        assert_eq!(
34            md5_hash(username, password, salt),
35            "md562af4dd09bbb41884907a838a3233294"
36        );
37    }
38}