title: how to decrypt aes-256-gcm in PHP using IV & TAG
body: <p>I've found a difficult way to decrypt a string using aes-256-gcm, iv, and TAG.
  Here are the parameters that I get.    </p>
  
  <pre><code>$password = 'code1234';
  $data = 'f4oGPQaf9ZolRc9oh8VLRiJWK2B35tkHq9L6WvrE+jbjS1mfi0fJB7re+0kVM2RRLiAEPBSFtIQzlJ5055yRlntIZwwpRvAN1cUBS0ze3hb+FrcO43vtBuuqftDw0exfmorPM5SOaKj3KtEQjB2ypwtbnQNCtegNizs6niqAdvs/XztlZPbq08Y=';
  
  $ivstring = 'D7GVFFLn+K0sNj+YRskGTw==';
  $tagstring = '9GSCia0QDujWTn3zpIRbCw==';
  </code></pre>
  
  <p>I use this function to decrypt</p>
  
  <pre><code>openssl_decrypt($data, 'aes-256-gcm', $password, OPENSSL_RAW_DATA, $ivstring, $tagstring);
  </code></pre>
  
  <p>but it always returns with the following error</p>
  
  <blockquote>
    <p>Setting tag for AEAD cipher decryption failed</p>
  </blockquote>
  
  <p>how to decrypt aes-256-gcm in PHP using IV &amp; TAG </p>
  
  <p>UPDATE :
  the encryption are come from main app using node js. I tried to decrypt within nodejs app, it's working normally. I tried to convert decrypt function to PHP, but always get errors. Here the encrypt and decrypt script function</p>
  
  <pre><code>const crypto = require('crypto');
  
  // Demo implementation of using `aes-256-gcm` with node.js's `crypto` lib.
  const aes256gcm = (key) =&gt; {
      const ALGO = 'aes-256-gcm';
      const aes_password = key || 'code1234';
      const aes_key = crypto.createHash('md5').update(aes_password, 'utf-8').digest('hex').toUpperCase();
  
      // encrypt returns base64-encoded ciphertext
      const encrypt = (str) =&gt; {
  
          const iv = new Buffer(crypto.randomBytes(16), 'utf8');
          const cipher = crypto.createCipheriv(ALGO, aes_key, iv);
  
          let enc = cipher.update(str, 'utf8', 'base64');
          enc += cipher.final('base64');
  
          const ivString = iv.toString('base64');
          const authTagString = cipher.getAuthTag().toString('base64')
          return [enc, ivString, authTagString];
      };
  
      // decrypt decodes base64-encoded ciphertext into a utf8-encoded string
      const decrypt = (enc, ivString, authTagString) =&gt; {
          const iv = new Buffer(ivString, 'base64');
          const authTag = new Buffer(authTagString, 'base64');
  //console.log(iv);
    //      console.log(authTag);
          const decipher = crypto.createDecipheriv(ALGO, aes_key, iv);
     //     console.log(iv);
          decipher.setAuthTag(authTag);
          let str = decipher.update(enc, 'base64', 'utf8');
          console.log(str);
          str += decipher.final('utf8');
          return str;
      };
  
      return {
          encrypt,
          decrypt,
      };
  };
  
  module.exports = aes256gcm;
  </code></pre>