问题
There's a mcrypt snippet on several webs:
https://stackoverflow.com/a/11538728/408872
http://www.binrand.com/post/3810303-mcrypt-md5-how-to-create-an-online-encryption-decryption-web-page.html
http://www.techbees.org/best-way-to-use-php-to-encrypt-and-decrypt/
$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
echo 'Encrypted:' . "\n";
var_dump($encrypted);
echo "\n";
echo 'Decrypted:' . "\n";
var_dump($decrypted); // spaces are preserved
Anybody knows why extra spaces are introduced on $string?
回答1:
The sources you have provided all use nearly exactly the same code. I can only assume they stole the code from each other. So it's not several sites doing this, it was most likely a single site, and the others who didn't really understand what was going on simply inherited this.
There is no good reason to add additional spaces to a string prior to encrypting it, it does not enhance the strength of the cryptography in any way, it doesn't make it "better".
My guess would be that in these examples, it has been done to show that functions like trim
do not affect the contents of an encrypted stream. (I personally don't understand why this needs to be proved - it seems entirely logical to me)
If you're accepting a base64 encoded encrypted data (perhaps from a form submission), you will most likely trim the submitted data to remove any chaff the user left in there, I suspect someone somewhere was concerned that trimming the encrypted data would break the original plaintext.
Edit:
Note, if this string wasn't base64 encoded, it would be entirely possible to damage the ciphertext. Since the ciphertext would be represented in binary form, it is possible that it would have whitespace characters at the end, which could be trimmed off causing corruption.
Edit 2:
md5(key)
for the key, and md5(md5(key))
for the initialisation vector are both terrible terrible ways to implement this.
Firstly, AES 256 should have a 256 bit key. If you want to use a passphrase, then use hash('sha256', $passphrase, true)
. The final true
makes it return the result as binary, not hex encoded, and this is important so you actually get as much entropy as possible in your key.
Secondly, initialisation vectors should not be re-used, ever. md5(md5(key))
will always produce the same value, for the same key. This weakens your encryption considerably if an attacker manages to obtain several ciphertexts.
来源:https://stackoverflow.com/questions/13493335/php-mcrypt-why-to-add-spaces-on-string-input