= 32 ) { $material = FEHU_AP_KEY; } else { $material = ( defined( 'AUTH_KEY' ) ? AUTH_KEY : '' ) . '|' . ( defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : '' ); } return hash_hmac( 'sha256', 'zonepilot-secrets-v1', $material, true ); } /** * Whether the salts look like the defaults (then encryption is weak). * * @return bool */ public static function weak_key() { if ( defined( 'FEHU_AP_KEY' ) && is_string( FEHU_AP_KEY ) && strlen( FEHU_AP_KEY ) >= 32 ) { return false; } if ( ! defined( 'AUTH_KEY' ) || strlen( (string) AUTH_KEY ) < 32 ) { return true; } return false !== strpos( (string) AUTH_KEY, 'put your unique phrase here' ); } /** * Encrypt a string. * * @param string $plain Plain text. * @return string Base64 payload with a version prefix. */ public static function encrypt( $plain ) { $plain = (string) $plain; if ( function_exists( 'sodium_crypto_secretbox' ) ) { $nonce = random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ); $box = sodium_crypto_secretbox( $plain, $nonce, self::key() ); return 's1:' . base64_encode( $nonce . $box ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode } $iv = random_bytes( 12 ); $tag = ''; $enc = openssl_encrypt( $plain, 'aes-256-gcm', self::key(), OPENSSL_RAW_DATA, $iv, $tag ); return 'o1:' . base64_encode( $iv . $tag . $enc ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode } /** * Decrypt a payload produced by encrypt(). * * @param string $payload Payload. * @return string Empty string when it cannot be decrypted (e.g. salts changed). */ public static function decrypt( $payload ) { $payload = (string) $payload; if ( strlen( $payload ) < 4 ) { return ''; } $ver = substr( $payload, 0, 3 ); $raw = base64_decode( substr( $payload, 3 ), true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode if ( false === $raw ) { return ''; } if ( 's1:' === $ver && function_exists( 'sodium_crypto_secretbox_open' ) ) { $nonce = substr( $raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ); $box = substr( $raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ); $plain = sodium_crypto_secretbox_open( $box, $nonce, self::key() ); return false === $plain ? '' : $plain; } if ( 'o1:' === $ver ) { $iv = substr( $raw, 0, 12 ); $tag = substr( $raw, 12, 16 ); $enc = substr( $raw, 28 ); $plain = openssl_decrypt( $enc, 'aes-256-gcm', self::key(), OPENSSL_RAW_DATA, $iv, $tag ); return false === $plain ? '' : $plain; } return ''; } /** * Random hex secret. * * @param int $bytes Number of random bytes. * @return string */ public static function random_hex( $bytes = 24 ) { return bin2hex( random_bytes( $bytes ) ); } }