gerteb
gerteb

Reputation: 131

Encrypting aes-cbc in webcrypto decrypting aes-256-cbc with openssl_decrypt in php

I have managed to get it working with text not containing chars outside og a-zA-Z0-9 and some special chars, but if i use danish letters like æøåÆØÅ, the decrypted text shows ? instead of the actual letter. All files are saved as UTF-8, and headers charset=utf-8

Javascript --- input: "tester for æøåÆØÅ#¤%&/"

var arrayBufferToString=function(buffer){
  var str = "";
  for (var iii = 0; iii < buffer.byteLength; iii++){
    str += String.fromCharCode(buffer[iii]);
  }
  return str;
}
var stringToArrayBuffer=function(str){
  var bytes = new Uint8Array(str.length);
  for (var iii = 0; iii < str.length; iii++){
    bytes[iii] = str.charCodeAt(iii);
  }
  return bytes;
}
var arrayBufferToHexDec=function(buffer) {
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}

var pwVector,key,sendData={};
var pwGenerateSymmetricKey=function(pw){
  if(this.crypto){
    if(!pwVector)pwVector = crypto.getRandomValues(new Uint8Array(16));
    crypto.subtle.digest({name: "SHA-256"}, stringToArrayBuffer(pw)).then(function(result){
      window.crypto.subtle.importKey("raw", result, {name: "AES-CBC",length:256}, false, ["encrypt", "decrypt"]).then(function(e){

        console.log(e+" gen SHA256 key: "+arrayBufferToHexDec(result));

        sendData.pwVector=btoa(arrayBufferToHexDec(pwVector.buffer));
        sendData.pwKey=btoa(arrayBufferToHexDec(result));

        sendData.pwVectorString=btoa(arrayBufferToString(pwVector));
        sendData.pwKeyString=btoa(arrayBufferToString(new Uint8Array(result)));

        key = e;
      },
      function(e){
        console.log(e);
      });
    });
  }else return;
} 
var pwEncryptData=function(input){
  crypto.subtle.encrypt({name: "AES-CBC", iv: this.pwVector},key,stringToArrayBuffer(input)).then(
    function(result){
      console.log('encrypted',result)

      var pwEncryptedDataArray=new Uint8Array(result);
      var pwEncryptedDataString=arrayBufferToString(pwEncryptedDataArray);

      sendData.pwData=arrayBufferToHexDec(result);
      sendData.pwDataString=btoa(pwEncryptedDataString);
    }, 
    function(e){
      console.log(e.message);
    }
  );
}       

Php:

function strToHex($string){
    $hex = '';
    for ($i=0; $i<strlen($string); $i++){
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0'.$hexCode, -2);
    }
    return $hex;
}

$json_string = file_get_contents('php://input');
$json_object = json_decode($json_string);

$oEncryptedData=hex2bin($json_object->pwData);
$sEncryptedData=hex2bin(strToHex(base64_decode($json_object->pwDataString)));

$aesKey=hex2bin(base64_decode($json_object->pwKey));
$iv=hex2bin(base64_decode($json_object->pwVector));

$aesKeyStr=hex2bin(strToHex(base64_decode($json_object->pwKeyString)));
$ivStr=hex2bin(strToHex(base64_decode($json_object->pwVectorString)));

$oDecryptedData = decrypt($aesKey,$iv,$oEncryptedData);
$sDecryptedData = decrypt($aesKeyStr,$ivStr,$sEncryptedData);

function decrypt($aesKey,$iv, $dataTodecrypt) {
    $output = false;
    $output = openssl_decrypt($dataTodecrypt, 'AES-256-CBC',$aesKey,OPENSSL_RAW_DATA, $iv);
    return $output;
}
echo $oDecryptedData; // output: tester for ??????#?%&/
echo $sDecryptedData; // output: tester for ??????#?%&/

I have tried with options 0, OPENSSL_ZERO_PADDING and OPENSSL_RAW_DATA, with same result. Can anybody help me, because i am stuck right now, and cant find the possible error.

Solution

The problem is solved if the input string is encoded to utf-8 before encryption in Javascript, by chancing this line:

  crypto.subtle.encrypt({name: "AES-CBC", iv: this.pwVector},key,stringToArrayBuffer(input)).then(

To this:

  crypto.subtle.encrypt({name: "AES-CBC", iv: this.pwVector},key,stringToArrayBuffer(unescape(encodeURI(input)))).then(

Pretty simple. Seems strange that the input from HTML is not utf-8 encoded even though

<meta charset="UTF-8">

is set. But there it is :-)

Upvotes: 0

Views: 1782

Answers (1)

rmhrisk
rmhrisk

Reputation: 1856

Javascript side would look like this:

function stringToArrayBuffer(str) {
    var buf = new ArrayBuffer(str.length);
    var bufView = new Uint8Array(buf);
    for (var i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}

function arrayBufferToString(str) {
    var byteArray = new Uint8Array(str);
    var byteString = '';
    for (var i = 0; i < byteArray.byteLength; i++) {
        byteString += String.fromCodePoint(byteArray[i]);
    }
    return byteString;
}

var text = "tester for æøåÆØÅ#¤%&/";
console.log("what we will encrypt:");
console.log(text);

var data = stringToArrayBuffer(text);
console.log("what we encode to:");
console.log(data);

window.crypto.subtle.generateKey({
            name: "AES-CBC",
            length: 256, //can be  128, 192, or 256
        },
        false, //whether the key is extractable (i.e. can be used in exportKey)
        ["encrypt", "decrypt"] //can be "encrypt", "decrypt", "wrapKey", or "unwrapKey"
    )
    .then(function(key) {
        //returns a key object
        console.log("our key:");
        console.log(key);

        window.crypto.subtle.encrypt({
                    name: "AES-CBC",
                    //Don't re-use initialization vectors!
                    //Always generate a new iv every time your encrypt!
                    iv: window.crypto.getRandomValues(new Uint8Array(16)),
                },
                key, //from generateKey or importKey above
                data //ArrayBuffer of data you want to encrypt
            )
            .then(function(encrypted) {
                //returns an ArrayBuffer containing the encrypted data
                console.log("our ciphertext:");
                console.log(new Uint8Array(encrypted));
            })
            .catch(function(err) {
                console.error(err);
            });
    })
    .catch(function(err) {
        console.error(err);
    });

As long as the string is encoded as an array, should just need to turn the array into a string on the other side:

$decrypted = openssl_decrypt(
    $EncryptedData,
    'AES-256-CBC',
    $AesKeyData,
    OPENSSL_NO_PADDING,
    $InitializationVectorData
);

You really should use AES-GCM also, it is an authenticated mode and will surely be supported in PHP also.

Upvotes: 3

Related Questions