1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use criterion::{criterion_group, criterion_main, Criterion};
16
17 use crypto_provider::hmac::Hmac;
18 use crypto_provider::{CryptoProvider, CryptoRng};
19 use crypto_provider_openssl::Openssl;
20 use crypto_provider_rustcrypto::RustCrypto;
21 use rand_ext::random_bytes;
22
23 // simple benchmark, which creates a new hmac, updates once, then finalizes
hmac_sha256_operations<C: CryptoProvider>(c: &mut Criterion)24 fn hmac_sha256_operations<C: CryptoProvider>(c: &mut Criterion) {
25 let mut rng = C::CryptoRng::new();
26 let key: [u8; 32] = rand_ext::random_bytes::<32, C>(&mut rng);
27 let update_data: [u8; 16] = rand_ext::random_bytes::<16, C>(&mut rng);
28
29 c.bench_function("bench for hmac sha256 single update", |b| {
30 b.iter(|| {
31 let mut hmac = C::HmacSha256::new_from_key(key);
32 hmac.update(&update_data);
33 let _result = hmac.finalize();
34 });
35 });
36 }
37
hmac_sha512_operations<C: CryptoProvider>(c: &mut Criterion)38 fn hmac_sha512_operations<C: CryptoProvider>(c: &mut Criterion) {
39 let mut rng = C::CryptoRng::new();
40 let key: [u8; 64] = rand_ext::random_bytes::<64, C>(&mut rng);
41 let update_data: [u8; 16] = random_bytes::<16, C>(&mut rng);
42
43 c.bench_function("bench for hmac sha512 single update", |b| {
44 b.iter(|| {
45 let mut hmac = C::HmacSha512::new_from_key(key);
46 hmac.update(&update_data);
47 let _result = hmac.finalize();
48 });
49 });
50 }
51
52 criterion_group!(
53 benches,
54 hmac_sha256_operations::<RustCrypto>,
55 hmac_sha256_operations::<Openssl>,
56 hmac_sha512_operations::<RustCrypto>,
57 hmac_sha512_operations::<Openssl>
58 );
59
60 criterion_main!(benches);
61