@@ -207,6 +207,20 @@ static int X509_up_ref(X509* cert) {
207207
208208#define EVP_MD_CTX_new EVP_MD_CTX_create
209209#define EVP_MD_CTX_free EVP_MD_CTX_destroy
210+
211+ HMAC_CTX* HMAC_CTX_new () {
212+ HMAC_CTX* ctx = Malloc<HMAC_CTX>(1 );
213+ HMAC_CTX_init (ctx);
214+ return ctx;
215+ }
216+
217+ void HMAC_CTX_free (HMAC_CTX* ctx) {
218+ if (ctx == nullptr ) {
219+ return ;
220+ }
221+ HMAC_CTX_cleanup (ctx);
222+ free (ctx);
223+ }
210224#endif // OPENSSL_VERSION_NUMBER < 0x10100000L
211225
212226// Subject DER of CNNIC ROOT CA and CNNIC EV ROOT CA are taken from
@@ -3821,6 +3835,11 @@ void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
38213835}
38223836
38233837
3838+ Hmac::~Hmac () {
3839+ HMAC_CTX_free (ctx_);
3840+ }
3841+
3842+
38243843void Hmac::Initialize (Environment* env, v8::Local<v8::Object> target) {
38253844 Local<FunctionTemplate> t = env->NewFunctionTemplate (New);
38263845
@@ -3847,14 +3866,16 @@ void Hmac::HmacInit(const char* hash_type, const char* key, int key_len) {
38473866 if (md == nullptr ) {
38483867 return env ()->ThrowError (" Unknown message digest" );
38493868 }
3850- HMAC_CTX_init (&ctx_);
38513869 if (key_len == 0 ) {
38523870 key = " " ;
38533871 }
3854- if (!HMAC_Init_ex (&ctx_, key, key_len, md, nullptr )) {
3872+ ctx_ = HMAC_CTX_new ();
3873+ if (ctx_ == nullptr ||
3874+ !HMAC_Init_ex (ctx_, key, key_len, md, nullptr )) {
3875+ HMAC_CTX_free (ctx_);
3876+ ctx_ = nullptr ;
38553877 return ThrowCryptoError (env (), ERR_get_error ());
38563878 }
3857- initialised_ = true ;
38583879}
38593880
38603881
@@ -3871,9 +3892,9 @@ void Hmac::HmacInit(const FunctionCallbackInfo<Value>& args) {
38713892
38723893
38733894bool Hmac::HmacUpdate (const char * data, int len) {
3874- if (!initialised_ )
3895+ if (ctx_ == nullptr )
38753896 return false ;
3876- int r = HMAC_Update (& ctx_, reinterpret_cast <const unsigned char *>(data), len);
3897+ int r = HMAC_Update (ctx_, reinterpret_cast <const unsigned char *>(data), len);
38773898 return r == 1 ;
38783899}
38793900
@@ -3918,10 +3939,10 @@ void Hmac::HmacDigest(const FunctionCallbackInfo<Value>& args) {
39183939 unsigned char md_value[EVP_MAX_MD_SIZE];
39193940 unsigned int md_len = 0 ;
39203941
3921- if (hmac->initialised_ ) {
3922- HMAC_Final (& hmac->ctx_ , md_value, &md_len);
3923- HMAC_CTX_cleanup (& hmac->ctx_ );
3924- hmac->initialised_ = false ;
3942+ if (hmac->ctx_ != nullptr ) {
3943+ HMAC_Final (hmac->ctx_ , md_value, &md_len);
3944+ HMAC_CTX_free ( hmac->ctx_ );
3945+ hmac->ctx_ = nullptr ;
39253946 }
39263947
39273948 Local<Value> error;
0 commit comments