Created
December 13, 2018 14:13
-
-
Save lucymtc/0ba9a3f00578e986813891a38555f50a to your computer and use it in GitHub Desktop.
Encrypt/Decrypt using WordPress constant SECURE_AUTH_KEY
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 | |
// $this->_default_secure_auth_key defined in case SECURE_AUTH_KEY is not defined. | |
/** | |
* Encrypt code using OpenSSL | |
* | |
* @param string $code The code to encrypt. | |
*/ | |
public function encrypt_code( $code ) { | |
if ( empty( $code ) ) { | |
return ''; | |
} | |
$key = defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : $this->_default_secure_auth_key; | |
$encryption_key = base64_decode( $key ); | |
$iv = substr( openssl_random_pseudo_bytes( openssl_cipher_iv_length( 'aes-256-cbc' ) ), 0, 16 ); | |
$encrypted = openssl_encrypt( $code, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv ); | |
// Append the $iv variable to use for decrypting later. | |
return base64_encode( $encrypted . '::' . $iv ); | |
} | |
/** | |
* Decrypt code using OpenSSL | |
* | |
* @param string $code The code to decrypt. | |
*/ | |
public function decrypt_code( $code ) { | |
$key = defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : $this->_default_secure_auth_key; | |
$encryption_key = base64_decode( $key ); | |
// Grab the $iv from earlier, to decrypt. | |
list( $encrypted_data, $iv ) = explode( '::', base64_decode( $code ), 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