简体   繁体   中英

aes-256-gcm encrypt with PHP, decrypt with javascript

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

The answer can be found here: Encrypt string in PHP and decrypt in Node.js

It might need a bit of tuning for your own set-up but it should work !

Cheers.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM