1

I work with CryptoJS and php 5.5.12 using example code from Brain Foo Long.

I crypt client side with the following code:

var msg = 'String to crypt';
var key = 'password';
var crypt_text = CryptoJS.AES.encrypt(JSON.stringify(msg), key, {format: CryptoJSAesJson}).toString();
sendString = "msg=" + crypt_text +"&key=" + k ; 
//... call jQuery.ajax

I decrypt server side with the following code:

function cryptoJsAesDecrypt($passphrase, $jsonString){
    $jsondata = json_decode($jsonString, true);
    try {
        $salt = hex2bin($jsondata["s"]);
        $iv  = hex2bin($jsondata["iv"]);
    } catch(Exception $e) { return null; }
    $ct = base64_decode($jsondata["ct"]);
    $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 json_decode($data, true);
}

Randomly, the server code openssl_decrypt return false. Often, I saw that $ct = base64_decode($jsondata["ct"]); go in error for "base64 outside alphabet", but I tried to check in js before sending and it seems correct. The code is the following:

var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij ............" };
var sendString = "msg=" + crypt_text +"&key=" + k ; 
if( Base64.decode( Base64.encode(sendString) )=== sendString  ){
    // ok
} else {
    alert('base 64 error');
    return;
}
Community
  • 1
  • 1
Giorgio A.
  • 23
  • 8
  • I would think that you need to use a url-safe Base64 alphabet. Have you checked what you receive at PHP *before* you start handling it? – Artjom B. Feb 29 '16 at 19:09
  • When I have error in php openssl_decrypt, I found the following missmatch in console log for POST parameters: "dummydata whatever" have blank space when source have "+". Correct is msg with "+" character. In php arrive blank space (not "+"). I think is that missmatch but why? – Giorgio A. Mar 02 '16 at 09:17
  • I Make a correction: When I have error in php openssl_decrypt, I found the following missmatch in console log for POST parameters: before send, data have char "+" and that is modify in blank space from php. I think is that the problem but why? – Giorgio A. Mar 02 '16 at 13:30
  • It probably depends on how you send and receive the data. jQuery and PHP might make further processing on the data. – Artjom B. Mar 02 '16 at 13:32
  • From php.net: - urldecode — Decodes URL-encoded string Decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character. For that, PHP make e urldecode everytime receive data from client and urldecode change "+" char in space char. Then a simple str_replace() resolve. – Giorgio A. Mar 07 '16 at 14:27

0 Answers0