2
2
// SPDX-License-Identifier: Apache-2.0
3
3
//! AEAD block cipher mechanism types
4
4
5
+ use crate :: error:: Error ;
5
6
use crate :: types:: Ulong ;
6
7
use cryptoki_sys:: * ;
7
8
use std:: convert:: TryInto ;
@@ -31,12 +32,10 @@ impl<'a> GcmParams<'a> {
31
32
/// `tag_bits` - The length, in **bits**, of the authentication tag. Must
32
33
/// be between 0 and 128. The tag is appended to the end of the
33
34
/// ciphertext.
34
- ///
35
- /// # Panics
36
- ///
37
- /// This function panics if the length of `iv` or `aad` does not
35
+ /// # Errors
36
+ /// This function returns an error if the length of `iv` or `aad` does not
38
37
/// fit into an [Ulong].
39
- pub fn new ( iv : & ' a mut [ u8 ] , aad : & ' a [ u8 ] , tag_bits : Ulong ) -> Self {
38
+ pub fn new ( iv : & ' a mut [ u8 ] , aad : & ' a [ u8 ] , tag_bits : Ulong ) -> Result < Self , Error > {
40
39
// The ulIvBits parameter seems to be missing from the 2.40 spec,
41
40
// although it is included in the header file. In [1], OASIS clarified
42
41
// that the header file is normative. In 3.0, they added the parameter
@@ -53,23 +52,24 @@ impl<'a> GcmParams<'a> {
53
52
// set it to zero.
54
53
//
55
54
// [1]: https://www.oasis-open.org/committees/document.php?document_id=58032&wg_abbrev=pkcs11
56
- GcmParams {
55
+
56
+ let iv_len = iv. len ( ) ;
57
+ // Some HSMs may require the ulIvBits field to be populated, while others don't pay attention to it.
58
+ let iv_bit_len = iv_len * 8 ;
59
+
60
+ Ok ( GcmParams {
57
61
inner : CK_GCM_PARAMS {
58
62
pIv : iv. as_mut_ptr ( ) ,
59
- ulIvLen : iv
60
- . len ( )
61
- . try_into ( )
62
- . expect ( "iv length does not fit in CK_ULONG" ) ,
63
- ulIvBits : 0 ,
63
+ ulIvLen : iv_len. try_into ( ) ?,
64
+ // Since this field isn't universally used, set it to 0 if it doesn't fit in CK_ULONG.
65
+ // If the HSM doesn't require the field, it won't mind; and it it does, it would break anyways.
66
+ ulIvBits : iv_bit_len. try_into ( ) . unwrap_or_default ( ) ,
64
67
pAAD : aad. as_ptr ( ) as * mut _ ,
65
- ulAADLen : aad
66
- . len ( )
67
- . try_into ( )
68
- . expect ( "aad length does not fit in CK_ULONG" ) ,
68
+ ulAADLen : aad. len ( ) . try_into ( ) ?,
69
69
ulTagBits : tag_bits. into ( ) ,
70
70
} ,
71
71
_marker : PhantomData ,
72
- }
72
+ } )
73
73
}
74
74
75
75
/// The initialization vector.
0 commit comments