219

Possible Duplicate:
PHP 2-way encryption: I need to store passwords that can be retrieved

I plan to store foreign account information for my users on my website, aka rapidshare username and passwords, etc... I want to keep information secure, but I know that if I hash their information, I can't retrieve it for later use.

Base64 is decrypt-able so there's no point using that just plain off. My idea is to scramble the user and pass before and after it gets base64ed that way even after you decrypt it, you get some funny looking text if you try to decrypt. Is there a php function that accepts values that will make an unique scramble of a string and de-scramble it later when the value is reinputed?

Any suggestions?

3
  • 7
    Base64?! Ahahaha, no. Encrypt with AES and use a master password like PassPack does. phpaes.com
    – mcandre
    Aug 17, 2009 at 16:56
  • 1
    How will the webserver be able to get to the encrypted user credentials information? Yes, by knowing the decryption password. And if I were an attacker with access to your box, how would your scheme hinder me in getting this information? The only thing you get here is a "scrambling", thereby not having this laying around on your box in total plaintext. But it is security-through-obscurity at best.
    – stolsvik
    Nov 9, 2011 at 12:27
  • 2
    @stolsvik This is an extra layer against SQL injection attacks. In the case where your database is corrupted and not your server, you would still need the key to get sensitive info back.
    – haknick
    Feb 6, 2012 at 14:28

8 Answers 8

303

You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. This answer explains how to properly implement password hashing in PHP. Still, here is how you would encrypt/decrypt:

$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces

To Encrypt:

$iv = mcrypt_create_iv(
    mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
    MCRYPT_DEV_URANDOM
);

$encrypted = base64_encode(
    $iv .
    mcrypt_encrypt(
        MCRYPT_RIJNDAEL_128,
        hash('sha256', $key, true),
        $string,
        MCRYPT_MODE_CBC,
        $iv
    )
);

To Decrypt:

$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));

$decrypted = rtrim(
    mcrypt_decrypt(
        MCRYPT_RIJNDAEL_128,
        hash('sha256', $key, true),
        substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
        MCRYPT_MODE_CBC,
        $iv
    ),
    "\0"
);

Warning: The above example encrypts information, but it does not authenticate the ciphertext to prevent tampering. You should not rely on unauthenticated encryption for security, especially since the code as provided is vulnerable to padding oracle attacks.

See also:

Also, don't just use a "password" for an encryption key. Encryption keys are random strings.


Demo at 3v4l.org:

echo 'Encrypted:' . "\n";
var_dump($encrypted); // "m1DSXVlAKJnLm7k3WrVd51omGL/05JJrPluBonO9W+9ohkNuw8rWdJW6NeLNc688="

echo "\n";

echo 'Decrypted:' . "\n";
var_dump($decrypted); // " string to be encrypted "
32
  • 20
    Actually, not "some random", but "random and stored after that".)
    – BasTaller
    Jun 23, 2011 at 10:10
  • 2
    I was just wondering on the significance of the spaces around $string. Are they added artificially before encrypting to increase difficulty of cracking? Sorry if I missed the point on that ;)
    – wired00
    Dec 13, 2011 at 0:45
  • 5
    @wired00: No, not at all! If you decrypt an encrypted string you'll notice that some NULL bytes are added at the end of the string. Usually people just use [r]trim() to get rid of those NULL bytes, but in the process spaces are also removed. I added the spaces so that people could test and verify that the right way to trim a decrypted string is: $original = rtrim($decrypted, "\0"); - note the \0. =)
    – Alix Axel
    Dec 13, 2011 at 12:17
  • 13
    Holy hell. This is bad even as a suggestion for how to store passwords. It's not even reversible (so why are you using encryption in the first place)... And it doesn't use bcrypt (which you mention in the first line). As far as how to encrypt data, take a look at this SO Answer which includes the proper tools to set it up correctly... Example: you're missing padding (which CBC requires)...
    – ircmaxell
    Dec 11, 2012 at 17:11
  • 11
    Well, and after looking at the code deeper, you're not storing the password at all. You're using the password as a cipher key to store other data. So this doesn't even answer the question. If you're doing that, you need to use a key derivation function on the password first. Something like PBKDF2...
    – ircmaxell
    Dec 11, 2012 at 17:24
37

Security Warning: This class is not secure. It's using Rijndael256-ECB, which is not semantically secure. Just because "it works" doesn't mean "it's secure". Also, it strips tailing spaces afterwards due to not using proper padding.

Found this class recently, it works like a dream!

class Encryption {
    var $skey = "yourSecretKey"; // you can change it

    public  function safe_b64encode($string) {
        $data = base64_encode($string);
        $data = str_replace(array('+','/','='),array('-','_',''),$data);
        return $data;
    }

    public function safe_b64decode($string) {
        $data = str_replace(array('-','_'),array('+','/'),$string);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        return base64_decode($data);
    }

    public  function encode($value){ 
        if(!$value){return false;}
        $text = $value;
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
        return trim($this->safe_b64encode($crypttext)); 
    }

    public function decode($value){
        if(!$value){return false;}
        $crypttext = $this->safe_b64decode($value); 
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
        return trim($decrypttext);
    }
}

And to call it:

$str = "My secret String";

$converter = new Encryption;
$encoded = $converter->encode($str );
$decoded = $converter->decode($encoded);    

echo "$encoded<p>$decoded";
8
  • 1
    Thanks!! I use this class to store sensitive data in sessions, and I modified a little bit, I added a constructor: function __construct() { $this->skey = md5(session_name()); }. I think in this way it's a little bit more secure :)
    – BCsongor
    May 13, 2012 at 8:11
  • 6
    THIS ANSWER DOES NOT GENERATE SECURE CIPHER TEXT, PLEASE DO NOT USE. It only works in the sense that it encrypts/decrypts. Jun 30, 2012 at 11:36
  • 7
    // you can change it should be // you MUST change it Oct 11, 2012 at 13:53
  • 15
    No, no no. This is not good. First, it uses ECB mode, which is NOT good. Then, it uses an insecure method for generating IVs. It won't work in a secure way at all. Instead, take a look at something like this answer provides or just use a library. THIS IS NOT SECURE
    – ircmaxell
    Dec 11, 2012 at 17:27
  • 1
    Error Warning: mcrypt_encrypt(): Key of size 4 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported in for PHP 5.6.x
    – Editor
    Sep 21, 2016 at 10:12
19

Security warning: This code is not secure.

working example

define('SALT', 'whateveryouwant'); 

function encrypt($text) 
{ 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
} 

function decrypt($text) 
{ 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
} 

$encryptedmessage = encrypt("your message"); 
echo decrypt($encryptedmessage); 
2
  • 9
    Bad sample; two times random for IV, not using IV at all because of ECB, using ECB encoding in the first place, not using AES compatible code, not padding the message correctly. Yes, it works in the same sense that the random number generator on xkcd works. Jun 30, 2012 at 11:35
  • 12
    THIS ANSWER DOES NOT GENERATE SECURE CIPHER TEXT, PLEASE DO NOT USE. It only works in the sense that it encrypts/decrypts. Jun 30, 2012 at 11:36
13

One thing you should be very aware of when dealing with encryption:

Trying to be clever and inventing your own thing usually will leave you with something insecure.

You'd probably be best off using one of the cryptography extensions that come with PHP.

2
  • These are not always intuitive to use, or even to know which one to use. Perhaps some code examples would prove valuable here.
    – Simon E.
    Aug 23, 2017 at 8:11
  • 1
    Also, Mcrypt is not recommended anymore. See also paragonie.com/blog/2015/05/…
    – Simon E.
    Aug 23, 2017 at 8:13
4

Securiy Warning: This code is insecure. In addition to being vulnerable to chosen-ciphertext attacks, its reliance on unserialize() makes it vulnerable to PHP Object Injection.

To handle a string / array I use these two functions:

function encryptStringArray ($stringArray, $key = "Your secret salt thingie") {
 $s = strtr(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), serialize($stringArray), MCRYPT_MODE_CBC, md5(md5($key)))), '+/=', '-_,');
 return $s;
}

function decryptStringArray ($stringArray, $key = "Your secret salt thingie") {
 $s = unserialize(rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode(strtr($stringArray, '-_,', '+/=')), MCRYPT_MODE_CBC, md5(md5($key))), "\0"));
 return $s;
}

It's flexible as in you can store/send via URL a string or array because the string/array is serialzed before encryption.

1
  • 2
    Why use md5($key) for a key and md5(md5($key)) for an IV? Jul 29, 2015 at 16:42
3

This will only give you marginal protection. If the attacker can run arbitrary code in your application they can get at the passwords in exactly the same way your application can. You could still get some protection from some SQL injection attacks and misplaced db backups if you store a secret key in a file and use that to encrypt on the way to the db and decrypt on the way out. But you should use bindparams to completely avoid the issue of SQL injection.

If decide to encrypt, you should use some high level crypto library for this, or you will get it wrong. You'll have to get the key-setup, message padding and integrity checks correct, or all your encryption effort is of little use. GPGME is a good choice for one example. Mcrypt is too low level and you will probably get it wrong.

2

Check out mycrypt(): http://us.php.net/manual/en/book.mcrypt.php

And if you're using postgres there's pgcrypto for database level encryption. (makes it easier to search and sort)

1
1

The best idea to encrypt/decrypt your data in the database even if you have access to the code is to use 2 different passes a private password (user-pass) for each user and a private code for all users (system-pass).

Scenario

  1. user-pass is stored with md5 in the database and is being used to validate each user to login to the system. This user-pass is different for each user.
  2. Each user entry in the database has in md5 a system-pass for the encryption/decryption of the data. This system-pass is the same for each user.
  3. Any time a user is being removed from the system all data that are encrypted under the old system-pass have to be encrypted again under a new system-pass to avoid security issues.

Not the answer you're looking for? Browse other questions tagged or ask your own question.