-
-
Save tfirdaus/d4dab6dae47e7c04d37f293af88b9578 to your computer and use it in GitHub Desktop.
Encrypt & Decrypt with PHP
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 | |
/** | |
* Decrypts a value. | |
* | |
* If a user-based key is set, that key is used. Otherwise the default key is used. | |
* | |
* @since 1.0.0 | |
* | |
* @param string $raw_value Value to decrypt. | |
* @param string $key Key to use for encryption. | |
* @param string $salt Salt to use for encryption. | |
* @return string|bool Decrypted value, or false on failure. | |
*/ | |
function decrypt( $raw_value, $key, $salt ) { | |
if ( ! extension_loaded( 'openssl' ) ) { | |
return $raw_value; | |
} | |
$raw_value = base64_decode( $raw_value, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode | |
$method = 'aes-256-ctr'; | |
$ivlen = openssl_cipher_iv_length( $method ); | |
$iv = substr( $raw_value, 0, $ivlen ); | |
$raw_value = substr( $raw_value, $ivlen ); | |
$value = openssl_decrypt( $raw_value, $method, $key, 0, $iv ); | |
if ( ! $value || substr( $value, - strlen( $salt ) ) !== $salt ) { | |
return false; | |
} | |
return substr( $value, 0, - strlen( $this->salt ) ); | |
} |
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 | |
/** | |
* Encrypts a value. | |
* | |
* If a user-based key is set, that key is used. Otherwise the default key is used. | |
* | |
* @since 1.0.0 | |
* | |
* @param string $value Value to encrypt. | |
* @param string $key Key to use for encryption. | |
* @param string $salt Salt to use for encryption. | |
* @return string|bool Encrypted value, or false on failure. | |
*/ | |
function encrypt( $value, $key, $salt ) { | |
if ( ! extension_loaded( 'openssl' ) ) { | |
return $value; | |
} | |
$method = 'aes-256-ctr'; | |
$ivlen = openssl_cipher_iv_length( $method ); | |
$iv = openssl_random_pseudo_bytes( $ivlen ); | |
$raw_value = openssl_encrypt( $value . $salt, $method, $key, 0, $iv ); | |
if ( ! $raw_value ) { | |
return false; | |
} | |
return base64_encode( $iv . $raw_value ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment