title: AES-256-GCM decryption in nodejs
body: <p>i am trying to decrypt the data stored in my database before sending it to the client side.</p>
  <p>I am using the builtin crypto module with AES-256-GCM encryption.</p>
  <p>I have successfully implemented the encryption and it is working properly my problem is i am trying to decrypt the data in a different file but i keep getting an error.</p>
  <p>this is the error:</p>
  <p><code>(node:35798) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The &quot;iv&quot; argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined</code></p>
  <p>1.js</p>
  <pre><code>router.post(
  &quot;/&quot;,
  async(req, res) =&gt; {
  
  function getFullAddress({housenumber, address1, address2, city, postcode, country}) {
  return [housenumber, address1, ...(address2 ? [address2]: []), city, postcode, country].join(&quot;, &quot;);
  }
  
  const aes256gcm = (key) =&gt; {
  
  const encrypt = (str) =&gt; {
  const iv = new crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
  
  let enc = cipher.update(str, 'utf8', 'base64');
  enc += cipher.final('base64');
  return Buffer.concat([Buffer.from(enc), iv, cipher.getAuthTag()]).toString(&quot;base64&quot;);
  };
  
  return {
  encrypt,
  };
  };
  
  const aesCipher = aes256gcm(key);
  
  const hashedPasscode = await bcrypt.hash(req.body.passcode, 12);
  
          await User.create({
                              email: req.body.email,
                              mobilenumber: aesCipher.encrypt(req.body.mobilenumber),
                              passcode: hashedPasscode,
                              address: aesCipher.encrypt(getFullAddress(req.body))
  
                            })
  </code></pre>
  <p>2.js</p>
  <pre><code>router.get(
  &quot;/&quot;,
  async(req, res) =&gt; {
  
  const aes256gcm = (key) =&gt; {
  
    const decrypt = (enc, iv, authTag) =&gt; {
      const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
      decipher.setAuthTag(authTag);
      let str = decipher.update(enc, 'base64', 'utf8');
      str += decipher.final('utf8');
      return str;
    };
  
    return {
      decrypt,
    };
  };
  
  const aesCipher = aes256gcm(key);
  
  const decrypted_MobileNumber = aesCipher.decrypt(user.mobilenumber);
  const decrypted_address = aesCipher.decrypt(user.address);
  
  console.log('decrypted_MobileNumber',decrypted_MobileNumber)
  console.log('decrypted_address',decrypted_address)
  </code></pre>
  <p>here is an example of the data stored in my database</p>
  <p><code>mobilenumber: 'Sm4xQjA2bmUwUUdEdW4zQkZ3PT3QEq5fBbTJ9ht4TgpQXTLmPYBSoQA836977j0rr3GYwg==',</code></p>