use base64::prelude::*; use hmac::{Hmac, Mac}; use pbkdf2::pbkdf2_hmac; use sha2::{Digest, Sha256}; pub(crate) fn compute_client_proof( password: &str, salt: &[u8], iterations: u32, client_first_bare: &str, server_first: &str, client_final_without_proof: &str, ) -> String { // 1. SaltedPassword = PBKDF2(password, salt, iterations) let mut salted_password = [0u8; 32]; pbkdf2_hmac::(password.as_bytes(), salt, iterations, &mut salted_password); // 2. ClientKey = HMAC(SaltedPassword, "Client Key") let mut mac = Hmac::::new_from_slice(&salted_password).unwrap(); mac.update(b"Client Key"); let client_key = mac.finalize().into_bytes(); // 3. StoredKey = SHA256(ClientKey) let stored_key = Sha256::digest(client_key); // 4. AuthMessage = client_first_bare + "," + server_first + "," + client_final_without_proof let auth_message = format!( "{},{},{}", client_first_bare, server_first, client_final_without_proof ); // 5. ClientSignature = HMAC(StoredKey, AuthMessage) let mut mac = Hmac::::new_from_slice(&stored_key).unwrap(); mac.update(auth_message.as_bytes()); let client_signature = mac.finalize().into_bytes(); // 6. ClientProof = ClientKey XOR ClientSignature let client_proof: Vec = client_key .iter() .zip(client_signature.iter()) .map(|(a, b)| a ^ b) .collect(); // 7. Base64 encode the proof BASE64_STANDARD.encode(client_proof) } /// Computes the server signature for SCRAM-SHA-256 (for AuthenticationSASLFinal). /// Returns the base64-encoded server signature (the value for "v="). pub(crate) fn compute_server_signature( password: &str, salt: &[u8], iterations: u32, client_first_bare: &str, server_first: &str, client_final_without_proof: &str, ) -> String { // 1. SaltedPassword = PBKDF2(password, salt, iterations) let mut salted_password = [0u8; 32]; pbkdf2_hmac::(password.as_bytes(), salt, iterations, &mut salted_password); // 2. ServerKey = HMAC(SaltedPassword, "Server Key") let mut mac = Hmac::::new_from_slice(&salted_password).unwrap(); mac.update(b"Server Key"); let server_key = mac.finalize().into_bytes(); // 3. AuthMessage = client_first_bare + "," + server_first + "," + client_final_without_proof let auth_message = format!( "{},{},{}", client_first_bare, server_first, client_final_without_proof ); // 4. ServerSignature = HMAC(ServerKey, AuthMessage) let mut mac = Hmac::::new_from_slice(&server_key).unwrap(); mac.update(auth_message.as_bytes()); let server_signature = mac.finalize().into_bytes(); // 5. Base64 encode the server signature BASE64_STANDARD.encode(server_signature) }