I have few questions about this code:
<?php
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = "This is a very secret key";
$text = file_get_contents('path/to/your/file');
echo strlen($text) . "\n";
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
file_put_contents('path/to/your/file', $crypttext);
?>
It encrypts the file just fine, however it adds additional nulls at the end, so if I encrypt:
a test string is this one
and here is a new line
once decrypted becomes:
a test string is this one
and here is a new line 000000000000000
What’s going on?
Second, is MCRYPT_RIJNDAEL_256 compatible with AES-128?
Finally, how would I let another party decrypt a file I’ve encrypted? They would need to know which encryption was used and I am not sure what to tell them.
MCRYPT_RIJNDAEL_128is AES-128,MCRYPT_RIJNDAEL_256is AES-256 – just another name:The
\x00characters you encounter at the end of the decrypted string are the padding required for some block ciphers (with ECB being such a block cipher).McyrptusesNULL-padding internally if the input data needs to be padded to the required block length. There are other padding modes available (which have to be user-coded when usingMcyrpt), namely PKCS7, ANSI X.923 or ISO 10126.NULL-padding is problematic when encrypting binary data that may end with one or more\x00characters because you can’t detect where the data ends and the padding starts – the other padding modes mentioned solve this kind of problem. If you’re encrypting character data (strings) you can easily trim off the trailing\x00by using$data = trim($data, "\x00");.To decrypt the data you sent to a consumer, the consumer would need to know the IV (initialization vector) (
$iv), the algorithm used (MCRYPT_RIJNDAEL_256/AES-256), the encryption mode (ECB), the secret encryption key ($key) and the padding mode used (NULL-padding). The IV can be transmitted with the encrypted data as it does not need to be kept secret: