Then I have two functions called encrypt() and decrypt()
In fact, revisit where you found it and tell them their code is insecure and they shouldn't encourage people to use it.
I create a static key like:
$key = md5("uJHyFVSG");
Better idea: Use a library.
// Generate this once, then save it.
$key = Crypto::createNewRandomKey();
/*
var_dump(Crypto::binToHex($key));
// then later:
$key = Crypto::hexToBin("the generated hex characters go here");
*/
// To encrypt:
$encrypted = Crypto::encrypt(
"This is what you're trying to protect",
$key
);
// To decrypt:
$plaintext = Crypto::decrypt(
$encrypted,
$key
);
The library linked above (made by Taylor Hornby) provides something called Authenticated Encryption, which along with AEAD schemes (Authenticated Encryption with Associated Data) are the only way anyone should be encrypting arbitrary data in 2016.
You don't have to even particularly care about that detail or any others, but in case you're curious about your code snippet:
- It uses ECB mode
- It's using Rijndael-256, not AES
- Libmcrypt pads messages with
\0
until it reaches a multiple of the block size, so if you're encrypting anything that could possibly end in one or more \0
bytes, prepare to lose data when you decrypt your message.
- Also,
rtrim()
will gobble up other bytes (\x20
most notably)
By the way, all of this has been answered in general here, here, here, and here. There's a wealth of information about encryption best practices at the tips of your fingertips on Stack Exchange already, if you would only search for it.