0

This is the code in javascript which for some straing reason I could not recode it in PHP

function encrypt(b, a) {
    var c = CryptoJS.MD5(CryptoJS.enc.Utf8.parse(a));
    return CryptoJS.AES.encrypt(b, c, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    }).toString()
}

UPDATED: I tried this, But the output is not the same: PHP

$key = md5('SR0.08963341827756699');

$key_size =  strlen($key);
$plaintext = "22222222";

$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
                             $plaintext, MCRYPT_MODE_ECB, $iv);
echo base64_encode($ciphertext);

JavaScript

Input : encrypt('22222222', 'SR0.08963341827756699')

Output: RnN1WTGkZ9RKPQz3eBtivQ==

PHP

Input : string=22222222, key=SR0.08963341827756699

Output: ZA2pbDiSx3chj9/ubbUfOA==

MoJo
  • 44
  • 7
  • You must have tried something. Can you show your PHP code as well as the inputs, outputs and expected outputs? Stack Overflow is not a code translation service. – Artjom B. Sep 17 '16 at 09:32
  • I updated it, thanks – MoJo Sep 17 '16 at 10:20
  • You've requested PKCS#7 padding in CryptoJS, but mcrypt uses zero padding by default. You'd need the same padding in PHP... – Artjom B. Sep 17 '16 at 10:30
  • **Never use [ECB mode](http://crypto.stackexchange.com/q/14487/13022)**. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like [CBC](http://crypto.stackexchange.com/q/22260/13022) or [CTR](http://crypto.stackexchange.com/a/2378/13022). It is better to authenticate your ciphertexts so that attacks like a [padding oracle attack](http://crypto.stackexchange.com/q/18185/13022) are not possible. This can be done with authenticated modes like GCM or EAX, or with an [encrypt-then-MAC](http://crypto.stackexchange.com/q/202/13022) scheme. – Artjom B. Sep 17 '16 at 10:31
  • I'm kind new to PHP, But I know its not secure to use ECB and all that, I'm just trying to figure out if its possible in PHP and so far, I couldn't know where the problem is. – MoJo Sep 17 '16 at 11:05
  • I've closed this question as a duplicate of another which gives you the necessary code. The padding is the only difference. Pad the plaintext before encryption and unpad the recovered plaintext after decryption. – Artjom B. Sep 17 '16 at 11:10

0 Answers0