99 */
1010#include "ossl.h"
1111
12- #define NewHMAC (klass ) \
13- TypedData_Wrap_Struct((klass), &ossl_hmac_type, 0)
1412#define GetHMAC (obj , ctx ) do { \
1513 TypedData_Get_Struct((obj), EVP_MD_CTX, &ossl_hmac_type, (ctx)); \
1614 if (!(ctx)) { \
@@ -49,16 +47,7 @@ static const rb_data_type_t ossl_hmac_type = {
4947static VALUE
5048ossl_hmac_alloc (VALUE klass )
5149{
52- VALUE obj ;
53- EVP_MD_CTX * ctx ;
54-
55- obj = NewHMAC (klass );
56- ctx = EVP_MD_CTX_new ();
57- if (!ctx )
58- ossl_raise (eHMACError , "EVP_MD_CTX" );
59- RTYPEDDATA_DATA (obj ) = ctx ;
60-
61- return obj ;
50+ return TypedData_Wrap_Struct (klass , & ossl_hmac_type , NULL );
6251}
6352
6453
@@ -98,18 +87,25 @@ ossl_hmac_initialize(VALUE self, VALUE key, VALUE digest)
9887 const EVP_MD * md ;
9988 VALUE md_holder ;
10089
101- GetHMAC (self , ctx );
90+ ossl_want_uninitialized (self , & ossl_hmac_type );
10291 StringValue (key );
10392 md = ossl_evp_md_fetch (digest , & md_holder );
10493 pkey = EVP_PKEY_new_raw_private_key (EVP_PKEY_HMAC , NULL ,
10594 (unsigned char * )RSTRING_PTR (key ),
10695 RSTRING_LENINT (key ));
10796 if (!pkey )
10897 ossl_raise (eHMACError , "EVP_PKEY_new_raw_private_key" );
98+ ctx = EVP_MD_CTX_new ();
99+ if (!ctx ) {
100+ EVP_PKEY_free (pkey );
101+ ossl_raise (eHMACError , "EVP_MD_CTX_new" );
102+ }
109103 if (EVP_DigestSignInit (ctx , NULL , md , NULL , pkey ) != 1 ) {
104+ EVP_MD_CTX_free (ctx );
110105 EVP_PKEY_free (pkey );
111106 ossl_raise (eHMACError , "EVP_DigestSignInit" );
112107 }
108+ RTYPEDDATA_DATA (self ) = ctx ;
113109 rb_ivar_set (self , id_md_holder , md_holder );
114110 /* Decrement reference counter; EVP_MD_CTX still keeps it */
115111 EVP_PKEY_free (pkey );
@@ -123,13 +119,18 @@ ossl_hmac_copy(VALUE self, VALUE other)
123119{
124120 EVP_MD_CTX * ctx1 , * ctx2 ;
125121
126- rb_check_frozen (self );
127- if (self == other ) return self ;
128-
129- GetHMAC (self , ctx1 );
122+ ossl_want_uninitialized (self , & ossl_hmac_type );
130123 GetHMAC (other , ctx2 );
131- if (EVP_MD_CTX_copy (ctx1 , ctx2 ) != 1 )
124+
125+ ctx1 = EVP_MD_CTX_new ();
126+ if (!ctx1 )
127+ ossl_raise (eHMACError , "EVP_MD_CTX_new" );
128+ if (EVP_MD_CTX_copy (ctx1 , ctx2 ) != 1 ) {
129+ EVP_MD_CTX_free (ctx1 );
132130 ossl_raise (eHMACError , "EVP_MD_CTX_copy" );
131+ }
132+ RTYPEDDATA_DATA (self ) = ctx1 ;
133+
133134 return self ;
134135}
135136
0 commit comments