17 const DEFAULT_NONCE =
'bc5d92ffc6c54ff8d865a1e6f3361f48d0a84a2b145be34e';
43 if ( ! $secret_key ) {
44 $secret_key = wp_salt();
47 if ( strlen( $secret_key ) < SODIUM_CRYPTO_SECRETBOX_KEYBYTES ) {
48 $secret_key = hash_hmac(
'sha256', $secret_key, self::DEFAULT_NONCE );
51 if ( strlen( $secret_key ) > SODIUM_CRYPTO_SECRETBOX_KEYBYTES ) {
52 $secret_key = mb_substr( $secret_key, 0, SODIUM_CRYPTO_SECRETBOX_KEYBYTES,
'8bit' );
55 $this->_secret_key = $secret_key;
68 if ( is_null( self::$_instance ) ) {
69 self::$_instance =
new self( $secret_key );
72 return self::$_instance;
88 public function encrypt( $data, $use_random_nonce =
true, $custom_nonce = null ) {
90 if ( ! $use_random_nonce ) {
91 $nonce = $custom_nonce ? $custom_nonce : sodium_hex2bin( self::DEFAULT_NONCE );
99 if ( strlen( $nonce ) < SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ) {
100 $nonce = hash_hmac(
'sha256', $nonce, self::DEFAULT_NONCE );
103 if ( strlen( $nonce ) > SODIUM_CRYPTO_SECRETBOX_KEYBYTES ) {
104 $nonce = mb_substr( $nonce, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES,
'8bit' );
108 $encrypted = sodium_crypto_secretbox( $data, $nonce, $this->_secret_key );
109 $encrypted = sodium_bin2base64( $nonce . $encrypted, SODIUM_BASE64_VARIANT_ORIGINAL );
110 if ( extension_loaded(
'sodium' ) || extension_loaded(
'libsodium' ) ) {
111 sodium_memzero( $nonce );
133 $encrypted = sodium_base642bin( $data, SODIUM_BASE64_VARIANT_ORIGINAL );
138 $nonce = mb_substr( $encrypted, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES,
'8bit' );
139 $encrypted = mb_substr( $encrypted, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null,
'8bit' );
142 $decrypted = sodium_crypto_secretbox_open( $encrypted, $nonce, $this->_secret_key );
147 return $decrypted !==
false ? $decrypted : null;
161 public function hash( $data ) {
162 return hash_hmac(
'sha256', $data, self::DEFAULT_NONCE );
175 return random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES );
hash( $data)
Generates a quick one-way hash of data.
__construct( $secret_key='')
Class constructor.
This class provides basic data encryption functionality.
static get_instance( $secret_key='')
Returns class instance.
get_random_nonce()
Returns a random 24-byte nonce.
encrypt( $data, $use_random_nonce=true, $custom_nonce=null)
Encrypts data.
decrypt( $data)
Decrypts data.