@@ -32,11 +32,7 @@ impl<'a> GcmParams<'a> {
3232 /// be between 0 and 128. The tag is appended to the end of the
3333 /// ciphertext.
3434 ///
35- /// # Panics
36- ///
37- /// This function panics if the length of `iv` or `aad` does not
38- /// fit into an [Ulong].
39- pub fn new ( iv : & ' a mut [ u8 ] , aad : & ' a [ u8 ] , tag_bits : Ulong ) -> Self {
35+ pub fn new ( iv : & ' a mut [ u8 ] , aad : & ' a [ u8 ] , tag_bits : Ulong ) -> Result < Self , & ' a str > {
4036 // The ulIvBits parameter seems to be missing from the 2.40 spec,
4137 // although it is included in the header file. In [1], OASIS clarified
4238 // that the header file is normative. In 3.0, they added the parameter
@@ -53,23 +49,35 @@ impl<'a> GcmParams<'a> {
5349 // set it to zero.
5450 //
5551 // [1]: https://www.oasis-open.org/committees/document.php?document_id=58032&wg_abbrev=pkcs11
56- GcmParams {
52+
53+ let iv_len = iv. len ( ) ;
54+ // Some HSMs may require the ulIvBits field to be populated, while others don't pay attention to it.
55+ let iv_bit_len = iv_len* 8 ;
56+
57+ Ok ( GcmParams {
5758 inner : CK_GCM_PARAMS {
5859 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 ,
60+ ulIvLen : match iv_len. try_into ( ) {
61+ Ok ( len) => len,
62+ Err ( _e) => return Err ( "iv length does not fit in CK_ULONG" ) ,
63+ } ,
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 : match iv_bit_len. try_into ( ) {
67+ Ok ( len) => len,
68+ Err ( _e) => 0 ,
69+ } ,
6470 pAAD : aad. as_ptr ( ) as * mut _ ,
65- ulAADLen : aad
71+ ulAADLen : match aad
6672 . len ( )
67- . try_into ( )
68- . expect ( "aad length does not fit in CK_ULONG" ) ,
73+ . try_into ( ) {
74+ Ok ( len) => len,
75+ Err ( _e) => return Err ( "aad length does not fit in CK_ULONG" ) ,
76+ } ,
6977 ulTagBits : tag_bits. into ( ) ,
7078 } ,
7179 _marker : PhantomData ,
72- }
80+ } )
7381 }
7482
7583 /// The initialization vector.
0 commit comments