namespace WPForms\Helpers;
* Class for encryption functionality.
* @link https://www.php.net/manual/en/intro.sodium.php
* Get a secret key for encrypt/decrypt.
public static function get_secret_key() {
$secret_key = get_option( 'wpforms_crypto_secret_key' );
// If we already have the secret, send it back.
if ( false !== $secret_key ) {
return base64_decode( $secret_key ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
// We don't have a secret, so let's generate one.
$secret_key = sodium_crypto_secretbox_keygen();
add_option( 'wpforms_crypto_secret_key', base64_encode( $secret_key ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
* @param string $message Message to encrypt.
* @param string $key Encryption key.
public static function encrypt( $message, $key = '' ) {
// Create a nonce for this operation. It will be stored and recovered in the message itself.
SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
$key = self::get_secret_key();
// Encrypt message and combine with nonce.
$cipher = base64_encode( // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
sodium_memzero( $message );
} catch ( \Exception $e ) {
* @param string $encrypted Encrypted message.
* @param string $key Encryption key.
public static function decrypt( $encrypted, $key = '' ) {
// Unpack base64 message.
$decoded = base64_decode( (string) $encrypted ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
if ( false === $decoded ) {
if ( mb_strlen( $decoded, '8bit' ) < ( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES ) ) {
// Pull nonce and ciphertext out of unpacked message.
$nonce = mb_substr( $decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit' );
$ciphertext = mb_substr( $decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit' );
$key = self::get_secret_key();
$message = sodium_crypto_secretbox_open(
// Check for decrpytion failures.
if ( false === $message ) {
sodium_memzero( $ciphertext );
} catch ( \Exception $e ) {