I have some problems to decrypt my data in javascript side. I successfully with aes-256-cbc but with aes-256-gcm, I have some trouble.
So I have an API in PHP and a front end in Reactjs.
See below the PHP side:
$algo = "aes-256-gcm";
$sKey = openssl_random_pseudo_bytes(16);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$sEncrypted = openssl_encrypt(
json_encode($aData, true),
$algo,
$sKey,
$options=0,
$iv,
$tag
);
$aEncrypt = [
"ciphertext" => base64_encode($sEncrypted),
"iv" => base64_encode($iv),
"tag" => base64_encode($tag)
];
return $aEncrypt;
on my javascript side:
import crypto from 'crypto';
// Retrieve json
let obj_json = JSON.parse(data);
// Define variable from API call
let algo = 'aes-256-gcm';
let key = "xx"; // Retrieved previously
let encrypted_data = obj_json.ciphertext; // Seems no need to decode b64 since update function will do it
let tag = atob(obj_json.tag); // b64 decode
let iv = atob(obj_json.iv); // b64 decode
// Let's decrypt
let decipher = crypto.createDecipheriv(algo, key, iv);
decipher.setAuthTag(tag);
let decrypted = decipher.update(encrypted_data, 'base64','utf8');
decrypted += decipher.final('utf8');
I get :
Error: Unsupported state or unable to authenticate data
I tried different library (reactjs) but I get always this error. Is there a problem with encoding iv or tag ?
Thank you :D
I finally found the problem.
just replace
let tag = atob(obj_json.tag); // b64 decode
let iv = atob(obj_json.iv); // b64 decode
by
let tag = Buffer.from(obj_json.tag, 'base64');
let iv = Buffer.from(obj_json.iv, 'base64');