0

I want to encrypt some data within my php file when I add the stuff to my mysql database.

This is how I do it.

I create a static key like:

$key = md5("uJHyFVSG");

Then I have two functions called encrypt() and decrypt() and they do this:

function encrypt($string, $key){
    $string = rtrim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string, MCRYPT_MODE_ECB)));
    return $string;
}

function decrypt($string, $key){
    $string = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($string), MCRYPT_MODE_ECB));
    return $string;
}

I am not sure if this is best practice but like how do I generate a key other than md5?

2 Answers2

5

Then I have two functions called encrypt() and decrypt()

Don't use the code in your question!

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.

Community
  • 1
  • 1
Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206
1

There's a clue in the name: Rijndael 256 uses a 256 bit cypher. You are using a 64 bit key (actually your only using 48 bits but spread across 64). Also you might want to think about somewhere other than your source code to store the key in.

There are lots of random number generators on your system you could choose from. But you didn't say what OS this runs on nor what PHP modules are installed. But since you are using mcrypt already the you can use mcrypt_create_iv(256); (hint: base64 encode the value if you need to store it as ASCII.

symcbean
  • 47,736
  • 6
  • 59
  • 94