22// SPDX-License-Identifier: Apache-2.0
33//! AEAD block cipher mechanism types
44
5+ use crate :: error:: Error ;
56use crate :: types:: Ulong ;
67use cryptoki_sys:: * ;
78use std:: convert:: TryInto ;
@@ -31,12 +32,10 @@ impl<'a> GcmParams<'a> {
3132 /// `tag_bits` - The length, in **bits**, of the authentication tag. Must
3233 /// be between 0 and 128. The tag is appended to the end of the
3334 /// 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
3837 /// 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 > {
4039 // The ulIvBits parameter seems to be missing from the 2.40 spec,
4140 // although it is included in the header file. In [1], OASIS clarified
4241 // that the header file is normative. In 3.0, they added the parameter
@@ -53,23 +52,24 @@ impl<'a> GcmParams<'a> {
5352 // set it to zero.
5453 //
5554 // [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 {
5761 inner : CK_GCM_PARAMS {
5862 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 ( ) ,
6467 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 ( ) ?,
6969 ulTagBits : tag_bits. into ( ) ,
7070 } ,
7171 _marker : PhantomData ,
72- }
72+ } )
7373 }
7474
7575 /// The initialization vector.
0 commit comments