0

My question now has connection to this one Crypto-Js different output from mcrypt that's why I used the same question but added a few extra lines to explain it better.

Based on my previous question which is solved by SIr Jim(many thanks for the tips as well). It worked partially correct since it does show the same result but only when I use the word 'Blader' and If ever I use another word like 'CROW' then the output between the 2 scripts are different.

Here's the code which is given by Sir jim that works like a charm (I used Blader here)

$encrypted = "Blader\x0a\x0a\x0a\x0a\x0a\x0a\x0a\x0a\x0a";
$iv = base64_decode('AAAAAAAAAAAAAAAAAAAAAA==');
$key = base64_decode('ITU2NjNhI0tOc2FmZExOTQ==');
$plaintext = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC,  $iv );
echo base64_encode($plaintext);

Sample is When I use CROW as data to be ecnrypted

Output in cryptoJS

dxt3uyk27U3wRRrzaFGiwQ==

Output in mcrypt

x9/oeyLZkLkXM7B1Zo+ezg==

To solve this I removed the padding: CryptoJS.pad.Pkcs7 in cryptoJS but my question is what if I don't want to remove the padding in cryptoJS?

All answers will be greatly appreciated.

Community
  • 1
  • 1

1 Answers1

0

You need to look into how PKCS#7 padding works. It brings the plaintext up to a multiple of 16 bytes. If already a multiple of 16, it adds an extra 16 bytes.

For "CROW" in UTF-8 (four bytes) you would add 12 more bytes. Each byte would be now 12, that is 12 bytes of 12, instead of 10 bytes of 10 for Blader. For example, try this:

$encrypted = "CROW\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c";

To pad with PKCS#7 you can try something like this:

$encrypted = "CROW";

// Add PKCS#7 padding
$pad = 16 - (strlen($encrypted) % 16);
$encrypted = $encrypted . str_repeat(chr($pad), $pad);

(I would name the variable something other than $encrypted because it never actually holds encrypted data.)

Jim Flood
  • 8,144
  • 3
  • 36
  • 48
  • Wish I can thank you like more than a hundred times. Two of my questions are answered by you in less than an hour. Hope I can be like you one day sir. many thanks for the help sir. couldn't really have done without your help. – user3771496 Jun 24 '14 at 19:23
  • @user3771496 It's easy when you know where to look. Also, having actual data values and code in your question really helped. Cheers. – Jim Flood Jun 24 '14 at 19:26