Ciframos una cadena en JS con este código por esta biblioteca JS :
CryptoJS.AES.encrypt("Message", "Key").toString()y luego guárdelo en la base de datos para futuros casos de uso. Ahora queremos descifrar ese hash en PHP con este código:
openssl_decrypt( "Message", "aes-128-ctr", "Key")pero nos da un valor nulo! ¿Cómo podemos hacerlo sin hacer ningún cambio en el código JS?
En el lado JS haz esto:
var CryptoJSAesJson = { stringify: function (cipherParams) { var j = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; if (cipherParams.iv) j.iv = cipherParams.iv.toString(); if (cipherParams.salt) js = cipherParams.salt.toString(); return JSON.stringify(j); }, parse: function (jsonStr) { var j = JSON.parse(jsonStr); var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(j.ct), }); if (j.iv) cipherParams.iv = CryptoJS.enc.Hex.parse(j.iv); if (js) cipherParams.salt = CryptoJS.enc.Hex.parse(js); return cipherParams; }, }; let data = CryptoJS.AES.encrypt("Text", "Key", { format: CryptoJSAesJson, }).toString(); //store the "data" in DB or another placey en PHP Side haz esto:
function cryptoJsAesDecrypt($passphrase, $jsonString){ $jsondata = json_decode($jsonString, true); $salt = hex2bin($jsondata["s"]); $ct = base64_decode($jsondata["ct"]); $iv = hex2bin($jsondata["iv"]); $concatedPassphrase = $passphrase.$salt; $md5 = array(); $md5[0] = md5($concatedPassphrase, true); $result = $md5[0]; for ($i = 1; $i < 3; $i++) { $md5[$i] = md5($md5[$i - 1].$concatedPassphrase, true); $result .= $md5[$i]; } $key = substr($result, 0, 32); $data = openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv); return $data; } echo cryptoJsAesDecrypt("Key",data); // will show "Text"fuente: este enlace