@@ -13,16 +13,17 @@ use sha1::Sha1;
13
13
use sha2:: { Sha256 , Sha512 } ;
14
14
15
15
use crate :: otp:: otp_algorithm:: OTPAlgorithm ;
16
+ use crate :: otp:: otp_error:: OtpError ;
16
17
17
- pub fn hotp ( secret : & str , algorithm : OTPAlgorithm , counter : u64 ) -> Result < u32 , String > {
18
+ pub fn hotp ( secret : & str , algorithm : OTPAlgorithm , counter : u64 ) -> Result < u32 , OtpError > {
18
19
match algorithm {
19
20
OTPAlgorithm :: Sha256 => generate_hotp :: < Sha256 > ( secret, counter) ,
20
21
OTPAlgorithm :: Sha512 => generate_hotp :: < Sha512 > ( secret, counter) ,
21
22
_ => generate_hotp :: < Sha1 > ( secret, counter) ,
22
23
}
23
24
}
24
25
25
- fn generate_hotp < D > ( secret : & str , counter : u64 ) -> Result < u32 , String >
26
+ fn generate_hotp < D > ( secret : & str , counter : u64 ) -> Result < u32 , OtpError >
26
27
where
27
28
D : CoreProxy ,
28
29
D :: Core : HashMarker
@@ -37,21 +38,21 @@ where
37
38
// decode the base32 secret
38
39
let secret_decoded = match BASE32_NOPAD . decode ( secret. as_bytes ( ) ) {
39
40
Ok ( result) => result,
40
- Err ( e) => return Err ( format ! ( "{e:?}" ) ) ,
41
+ Err ( e) => return Err ( OtpError :: SecretEncoding ( e . kind , e . position ) ) ,
41
42
} ;
42
43
43
44
let hash = hotp_hash :: < D > ( & secret_decoded, counter) ;
44
45
45
46
// calculate offset
46
47
let offset: usize = match hash. last ( ) {
47
48
Some ( result) => * result & 0xf ,
48
- None => return Err ( String :: from ( "Invalid digest" ) ) ,
49
+ None => return Err ( OtpError :: InvalidOffset ) ,
49
50
} as usize ;
50
51
51
52
// calculate code
52
53
let code_bytes: [ u8 ; 4 ] = match hash[ offset..offset + 4 ] . try_into ( ) {
53
54
Ok ( x) => x,
54
- Err ( _) => return Err ( String :: from ( "Invalid digest" ) ) ,
55
+ Err ( _) => return Err ( OtpError :: InvalidDigest ) ,
55
56
} ;
56
57
Ok ( u32:: from_be_bytes ( code_bytes) & 0x7fffffff )
57
58
}
0 commit comments