Search code examples
phpcryptsensitive-data

best way to store sensitive data php encryption


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


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. :)