1+ use std:: time:: Duration ;
2+
13use aes:: Aes256 ;
24use cipher:: {
35 generic_array:: { typenum:: U32 , GenericArray } ,
@@ -7,11 +9,13 @@ use sha2::{Digest, Sha256};
79
810use super :: CryptographyError ;
911
10- pub ( crate ) trait Kdf {
12+ pub trait Kdf {
1113 fn transform_key (
1214 & self ,
1315 composite_key : & GenericArray < u8 , U32 > ,
1416 ) -> Result < GenericArray < u8 , U32 > , CryptographyError > ;
17+
18+ fn benchmark ( & self , duration : Duration ) -> usize ;
1519}
1620
1721pub struct AesKdf {
@@ -39,6 +43,23 @@ impl Kdf for AesKdf {
3943
4044 Ok ( digest. finalize ( ) )
4145 }
46+
47+ fn benchmark ( & self , duration : Duration ) -> usize {
48+ let composite_key: GenericArray < u8 , U32 > = GenericArray :: clone_from_slice ( & [ 0 ; 32 ] ) ;
49+ let mut rounds = 0 ;
50+
51+ let cipher = Aes256 :: new ( & GenericArray :: clone_from_slice ( & self . seed ) ) ;
52+ let mut block1 = GenericArray :: clone_from_slice ( & composite_key[ ..16 ] ) ;
53+ let mut block2 = GenericArray :: clone_from_slice ( & composite_key[ 16 ..] ) ;
54+
55+ let start_time = std:: time:: Instant :: now ( ) ;
56+ while start_time. elapsed ( ) < duration {
57+ cipher. encrypt_block ( & mut block1) ;
58+ cipher. encrypt_block ( & mut block2) ;
59+ rounds = rounds + 1 ;
60+ }
61+ rounds
62+ }
4263}
4364
4465pub struct Argon2Kdf {
@@ -71,16 +92,31 @@ impl Kdf for Argon2Kdf {
7192
7293 Ok ( * GenericArray :: from_slice ( & key) )
7394 }
74- }
7595
76- /*
77- pub(crate) fn transform_key_argon2(
78- composite_key: &GenericArray<u8, U32>,
79- ) -> Result<GenericArray<u8, U32>> {
80- let version = match version {
81- 0x10 => argon2::Version::Version10,
82- 0x13 => argon2::Version::Version13,
83- _ => return Err(DatabaseIntegrityError::InvalidKDFVersion { version: version }.into()),
84- };
96+ fn benchmark ( & self , duration : Duration ) -> usize {
97+ let composite_key: GenericArray < u8 , U32 > = GenericArray :: clone_from_slice ( & [ 0 ; 32 ] ) ;
98+
99+ let config = argon2:: Config {
100+ thread_mode : argon2:: ThreadMode :: Parallel ,
101+ ad : & [ ] ,
102+ hash_length : 32 ,
103+ lanes : self . parallelism ,
104+ mem_cost : ( self . memory / 1024 ) as u32 ,
105+ secret : & [ ] ,
106+ time_cost : 1 , // benchmark for one iteration
107+ variant : self . variant ,
108+ version : self . version ,
109+ } ;
110+
111+ let start_time = std:: time:: Instant :: now ( ) ;
112+ let _ = argon2:: hash_raw ( & composite_key, & self . salt , & config) ;
113+ let elapsed = start_time. elapsed ( ) ;
114+
115+ if elapsed. is_zero ( ) {
116+ // Should not happen, but to be safe
117+ return 0 ;
118+ }
119+
120+ ( duration. as_nanos ( ) / elapsed. as_nanos ( ) ) as usize
121+ }
85122}
86- */
0 commit comments