encryption_key = $this->get_encryption_key(); } /** * Get or generate encryption key. * * @return string Encryption key (32 characters). */ private function get_encryption_key() { if ( defined( 'AUTH_KEY' ) && AUTH_KEY !== 'put your unique phrase here' ) { return substr( hash( 'sha256', AUTH_KEY . SECURE_AUTH_KEY ), 0, 32 ); } return substr( hash( 'sha256', 'fallback-key-' . get_option( 'siteurl' ) ), 0, 32 ); } /** * Check if data is encrypted. * * @param mixed $data Data to check. * @return bool True if data is encrypted, false otherwise. */ public function is_encrypted( $data ) { if ( is_array( $data ) ) { return false; } return is_string( $data ) && strpos( $data, $this->encryption_prefix ) === 0; } /** * Encrypt string or array. * * @param mixed $data Data to encrypt (string or array). * @return mixed Encrypted data. */ public function encrypt( $data ) { if ( is_array( $data ) ) { return array_map( array( $this, 'encrypt' ), $data ); } if ( ! is_string( $data ) || empty( $data ) ) { return $data; } // Already encrypted. if ( $this->is_encrypted( $data ) ) { return $data; } $iv = openssl_random_pseudo_bytes( openssl_cipher_iv_length( $this->cipher_method ) ); $encrypted = openssl_encrypt( $data, $this->cipher_method, $this->encryption_key, 0, $iv ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Used for encryption, not obfuscation. return $this->encryption_prefix . base64_encode( $encrypted . '::' . base64_encode( $iv ) ); } /** * Decrypt string or array. * * @param mixed $data Data to decrypt (string or array). * @return mixed Decrypted data. */ public function decrypt( $data ) { if ( is_array( $data ) ) { return array_map( array( $this, 'decrypt' ), $data ); } if ( ! is_string( $data ) ) { return $data; } // Not encrypted, return as-is (backward compatibility). if ( ! $this->is_encrypted( $data ) ) { return $data; } // Remove prefix. $data = substr( $data, strlen( $this->encryption_prefix ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode $decoded = base64_decode( $data ); if ( false === $decoded ) { return $data; } $parts = explode( '::', $decoded, 2 ); if ( count( $parts ) !== 2 ) { return $data; } list($encrypted_data, $iv) = $parts; // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode $iv = base64_decode( $iv ); $decrypted = openssl_decrypt( $encrypted_data, $this->cipher_method, $this->encryption_key, 0, $iv ); return false !== $decrypted ? $decrypted : $data; } }