Created
July 28, 2017 11:19
-
-
Save lucymtc/54835badb5f1ac70e3e5f3d3d8fa9cf5 to your computer and use it in GitHub Desktop.
Encrypt/decrypt passwords
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Encrypt password using OpenSSL | |
* | |
* @param string $password The password to encrypt. | |
*/ | |
public function encrypt_password( $password ) { | |
$encryption_key = base64_decode( SECURE_AUTH_KEY ); | |
$iv = openssl_random_pseudo_bytes( openssl_cipher_iv_length( 'aes-256-cbc' ) ); | |
$encrypted = openssl_encrypt( $password, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv ); | |
// Append the $iv variable to use for decrypting later. | |
return base64_encode( $encrypted . '::' . $iv ); | |
} | |
/** | |
* Decrypt password using OpenSSL | |
* | |
* @param string $password The password to decrypt. | |
*/ | |
public function decrypt_password( $password ) { | |
$encryption_key = base64_decode( SECURE_AUTH_KEY ); | |
// Grab the $iv from earlier, to decrypt. | |
list( $encrypted_data, $iv ) = explode( '::', base64_decode( $password ), 2 ); | |
return openssl_decrypt( $encrypted_data, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment