Skip to content

Commit

Permalink
Optimize SASL auth in sqlx-postgres (#3050)
Browse files Browse the repository at this point in the history
* Optimize SASL auth in sqlx-postgres

* fix formatting
  • Loading branch information
mirek26 authored Feb 17, 2024
1 parent a1e4984 commit dd900e5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
2 changes: 1 addition & 1 deletion sqlx-postgres/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ futures-util = { version = "0.3.19", default-features = false, features = ["allo
# Cryptographic Primitives
crc = "3.0.0"
hkdf = "0.12.0"
hmac = { version = "0.12.0", default-features = false }
hmac = { version = "0.12.0", default-features = false, features = ["reset"]}
md-5 = { version = "0.10.0", default-features = false }
rand = { version = "0.8.4", default-features = false, features = ["std", "std_rng"] }
sha1 = { version = "0.10.1", default-features = false }
Expand Down
24 changes: 21 additions & 3 deletions sqlx-postgres/src/connection/sasl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,15 +195,33 @@ fn hi<'a>(s: &'a str, salt: &'a [u8], iter_count: u32) -> Result<[u8; 32], Error
mac.update(&salt);
mac.update(&1u32.to_be_bytes());

let mut u = mac.finalize().into_bytes();
let mut u = mac.finalize_reset().into_bytes();
let mut hi = u;

for _ in 1..iter_count {
let mut mac = Hmac::<Sha256>::new_from_slice(s.as_bytes()).map_err(Error::protocol)?;
mac.update(u.as_slice());
u = mac.finalize().into_bytes();
u = mac.finalize_reset().into_bytes();
hi = hi.iter().zip(u.iter()).map(|(&a, &b)| a ^ b).collect();
}

Ok(hi.into())
}

#[cfg(all(test, not(debug_assertions)))]
#[bench]
fn bench_sasl_hi(b: &mut test::Bencher) {
use test::black_box;

let mut rng = rand::thread_rng();
let nonce: Vec<u8> = std::iter::repeat(())
.map(|()| rng.sample(rand::distributions::Alphanumeric))
.take(64)
.collect();
b.iter(|| {
let _ = hi(
test::black_box("secret_password"),
test::black_box(&nonce),
test::black_box(4096),
);
});
}

0 comments on commit dd900e5

Please sign in to comment.