@@ -3090,8 +3090,17 @@ void CipherBase::InitIv(const char* cipher_type,
30903090 const int expected_iv_len = EVP_CIPHER_iv_length (cipher);
30913091 const int mode = EVP_CIPHER_mode (cipher);
30923092 const bool is_gcm_mode = (EVP_CIPH_GCM_MODE == mode);
3093+ const bool has_iv = iv_len >= 0 ;
30933094
3094- if (is_gcm_mode == false && iv_len != expected_iv_len) {
3095+ // Throw if no IV was passed and the cipher requires an IV
3096+ if (!has_iv && expected_iv_len != 0 ) {
3097+ char msg[128 ];
3098+ snprintf (msg, sizeof (msg), " Missing IV for cipher %s" , cipher_type);
3099+ return env ()->ThrowError (msg);
3100+ }
3101+
3102+ // Throw if an IV was passed which does not match the cipher's fixed IV length
3103+ if (is_gcm_mode == false && has_iv && iv_len != expected_iv_len) {
30953104 return env ()->ThrowError (" Invalid IV length" );
30963105 }
30973106
@@ -3103,11 +3112,13 @@ void CipherBase::InitIv(const char* cipher_type,
31033112 const bool encrypt = (kind_ == kCipher );
31043113 EVP_CipherInit_ex (ctx_, cipher, nullptr , nullptr , nullptr , encrypt);
31053114
3106- if (is_gcm_mode &&
3107- !EVP_CIPHER_CTX_ctrl (ctx_, EVP_CTRL_GCM_SET_IVLEN, iv_len, nullptr )) {
3108- EVP_CIPHER_CTX_free (ctx_);
3109- ctx_ = nullptr ;
3110- return env ()->ThrowError (" Invalid IV length" );
3115+ if (is_gcm_mode) {
3116+ CHECK (has_iv);
3117+ if (!EVP_CIPHER_CTX_ctrl (ctx_, EVP_CTRL_GCM_SET_IVLEN, iv_len, nullptr )) {
3118+ EVP_CIPHER_CTX_free (ctx_);
3119+ ctx_ = nullptr ;
3120+ return env ()->ThrowError (" Invalid IV length" );
3121+ }
31113122 }
31123123
31133124 if (!EVP_CIPHER_CTX_set_key_length (ctx_, key_len)) {
@@ -3135,8 +3146,15 @@ void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
31353146 const node::Utf8Value cipher_type (env->isolate (), args[0 ]);
31363147 ssize_t key_len = Buffer::Length (args[1 ]);
31373148 const char * key_buf = Buffer::Data (args[1 ]);
3138- ssize_t iv_len = Buffer::Length (args[2 ]);
3139- const char * iv_buf = Buffer::Data (args[2 ]);
3149+ ssize_t iv_len;
3150+ const char * iv_buf;
3151+ if (args[2 ]->IsNull ()) {
3152+ iv_buf = nullptr ;
3153+ iv_len = -1 ;
3154+ } else {
3155+ iv_buf = Buffer::Data (args[2 ]);
3156+ iv_len = Buffer::Length (args[2 ]);
3157+ }
31403158 cipher->InitIv (*cipher_type, key_buf, key_len, iv_buf, iv_len);
31413159}
31423160
0 commit comments