Question

Hello so obviously this is not a question with code, I am very familiar with salt and md5 encryption in php. But I need a safe way to store sensitive information in mysql. using md5 its very simple but again not the safest way. any suggestion or examples please ? it needs to be stored in db, and of course have the possibility to be retrieved and read. the simplest way is what im looking for

Was it helpful?

Solution

public static function encrypt($string, $salt = NULL){

     $mcrypt_iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
     $mcrypt_iv = mcrypt_create_iv($mcrypt_iv_size, MCRYPT_RAND);

     $mcrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $salt, $string, MCRYPT_MODE_ECB, $mcrypt_iv);

     $encoded = base64_encode($mcrypted);

     return $encoded;
}

public static function decrypt($hash, $salt = NULL){

    $mcrypt_iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
    $mcrypt_iv = mcrypt_create_iv($mcrypt_iv_size, MCRYPT_RAND);

    $basedecoded = base64_decode($hash);

    $mcrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $salt, $basedecoded, MCRYPT_MODE_ECB, $mcrypt_iv);

    return $mcrypted;
}

The following code is an working example, and uses AES-128 Mode ECB. If you aren't any friendly with the encryption terms used, it isn't any major deal either. Just use the code. :)

OTHER TIPS

If you are storing something in the DB encrypted, then you don't want to decrypt it. If you want to read it back, why bother encrypting it in the first place?

For encryption, the best way to ensure forward compatibility with future code and also to make it more secure is to use crypt().

php.net/crypt

There are various options you can pass to crypt(), if you're storing passwords I would probably use sha512 with a sufficiently high enough number for "rounds". Check out: http://php.net/crypt#example-4701 for examples.

Essentially, you get the hashed value from the DB and you can use it as your salt for plain text to verify whether the plain text is the same password as what's stored in the DB - it's one way encryption, no decryption (yet, anyway ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top