Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. <a href="https://stackoverflow.com/a/6337021/2224584">This answer explains how to properly implement password hashing in PHP</a>.</strong> Still, here is how you would encrypt/decrypt:</p> <pre><code>$key = 'password to (en/de)crypt'; $string = ' string to be encrypted '; // note the spaces </code></pre> <p><strong>To Encrypt:</strong></p> <pre><code>$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 ) ); </code></pre> <p><strong>To Decrypt:</strong></p> <pre><code>$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" ); </code></pre> <hr> <p><strong>Warning</strong>: The above example encrypts information, but it does not authenticate the ciphertext to prevent tampering. <a href="https://paragonie.com/blog/2015/05/using-encryption-and-authentication-correctly" rel="noreferrer">You should <em>not</em> rely on unauthenticated encryption for security</a>, especially since the code as provided is vulnerable to padding oracle attacks.</p> <p>See also:</p> <ul> <li><a href="https://stackoverflow.com/a/30189841/2224584">https://stackoverflow.com/a/30189841/2224584</a></li> <li><a href="https://stackoverflow.com/a/30166085/2224584">https://stackoverflow.com/a/30166085/2224584</a></li> <li><a href="https://stackoverflow.com/a/30159120/2224584">https://stackoverflow.com/a/30159120/2224584</a></li> </ul> <p>Also, don't just use a "password" for an encryption key. <strong>Encryption keys are random strings.</strong></p> <hr> <p><a href="http://3v4l.org/CJfSn" rel="noreferrer">Demo at 3v4l.org</a>:</p> <pre><code>echo 'Encrypted:' . "\n"; var_dump($encrypted); // "m1DSXVlAKJnLm7k3WrVd51omGL/05JJrPluBonO9W+9ohkNuw8rWdJW6NeLNc688=" echo "\n"; echo 'Decrypted:' . "\n"; var_dump($decrypted); // " string to be encrypted " </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload