key = sodium_crypto_generichash( 'abs-courier|' . $key_material, '', SODIUM_CRYPTO_SECRETBOX_KEYBYTES ); } /** * Store keyed to this WordPress install. * * @return self */ public static function for_site() { return new self( wp_salt( 'auth' ) ); } /** * Encrypts a value. * * @param string $plain Plain text. * @return string Versioned, base64-encoded nonce + ciphertext. */ public function encrypt( $plain ) { $nonce = random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ); return self::PREFIX . sodium_bin2base64( $nonce . sodium_crypto_secretbox( (string) $plain, $nonce, $this->key ), SODIUM_BASE64_VARIANT_ORIGINAL ); } /** * Decrypts a value produced by encrypt(). * * @param mixed $stored Stored value. * @return string|null Plain text, or null when the value is missing, malformed or was encrypted with another key. */ public function decrypt( $stored ) { if ( ! is_string( $stored ) || 0 !== strpos( $stored, self::PREFIX ) ) { return null; } try { $raw = sodium_base642bin( substr( $stored, strlen( self::PREFIX ) ), SODIUM_BASE64_VARIANT_ORIGINAL ); } catch ( \Throwable $e ) { return null; } if ( strlen( $raw ) <= SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ) { return null; } $plain = sodium_crypto_secretbox_open( substr( $raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ), substr( $raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ), $this->key ); return false === $plain ? null : $plain; } }