Last active
June 20, 2025 21:45
-
-
Save gmazzap/2d0ad8f1d0be80bab07fca7da9c95579 to your computer and use it in GitHub Desktop.
A class to encrypt/decrypt strings using Sodium and encryption key derived from WP secret keys constants
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace Gmazzap; | |
class Cypher | |
{ | |
/** | |
* @return Cypher | |
*/ | |
public static function new(): Cypher | |
{ | |
return new self(); | |
} | |
/** | |
*/ | |
final protected function __construct() | |
{ | |
} | |
/** | |
* @param string $plain | |
* @return string | |
*/ | |
public function encrypt(string $plain): string | |
{ | |
$nonce = \random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); | |
$cypher = \sodium_crypto_secretbox($plain, $nonce, $this->generateKey()); | |
return \sodium_bin2hex($cypher) . '|' . \sodium_bin2hex($nonce); | |
} | |
/** | |
* @param string $cypher | |
* @return string | |
*/ | |
public function decrypt(string $cypher): string | |
{ | |
[$secret, $nonce] = $this->splitCypher($cypher); | |
$plain = \sodium_crypto_secretbox_open($secret, $nonce, $this->generateKey()); | |
if ($plain === false) { | |
throw new \Error('Could not decrypt string.'); | |
} | |
return $plain; | |
} | |
/** | |
* @return string | |
*/ | |
private function generateKey(): string | |
{ | |
static $key; | |
if (\is_string($key)) { | |
return $key; | |
} | |
$key = \sodium_crypto_pwhash( | |
\SODIUM_CRYPTO_SECRETBOX_KEYBYTES, | |
\SECURE_AUTH_KEY, | |
\substr(\hex2bin(\sha1(\SECURE_AUTH_SALT)), 0, \SODIUM_CRYPTO_PWHASH_SALTBYTES), | |
\SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, | |
\SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE | |
); | |
return $key; | |
} | |
/** | |
* @param string $cypher | |
* @return array{string, string} | |
*/ | |
private function splitCypher(string $cypher): array | |
{ | |
$parts = \explode('|', $cypher); | |
if ((\count($parts) !== 2) || ($parts[0] === '') || ($parts[1] === '')) { | |
throw new \Error('Invalid encrypted string.'); | |
} | |
[$secretHex, $nonceHex] = $parts; | |
return [\sodium_hex2bin($secretHex), \sodium_hex2bin($nonceHex)]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment