I am trying to see if the message gets corrupted in the middle I should be able to get an error but all I am seeing is a white page.
<?php
$keypair = hex2bin('66b70b4e93416f8a7a82a40a856fe9884fd7a6e5018837c5421f507307026b40b2c8fbaf820ee38198af1dcf23143ec7ae21da1c785f58d1053940b9f317180e');
$encrypted_text = hex2bin('de261df126463f57b6c38bf42b69252b2f9382267b51e137e20e27ace37c5853279b00c95536cc9a44945146376c5d94355ae0bab5c1eb0ceb9669002ee5dd13e7aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
$decrypted_text = sodium_crypto_box_seal_open($encrypted_text, $keypair);
echo $decrypted_text;
?>
As you can see there are aaaaaaaaaaaaaa in the end in $encrypted_text I should get an error but there is no error.
sodium_crypto_box_seal_open()
returns FALSE
if the message cannot be decrypted.
You should compare its output against FALSE
, not check if it is empty, as it is perfectly fine to encrypt an empty message. Empty messages are authenticated and will be rejected if the key is not correct.
Also, if secrets are involved, you should use sodium_bin2hex()
and sodium_hex2bin()
, that are designed to avoid side channels
Libsodium functions are low-level. Either use any wrapper package to ease use, or create one by yourself:
interface Decryptor
{
public function decrypt(string $input): string;
}
final class LibsodiumDecryptor implements Decryptor
{
private $keyPair;
public function __construct(string $keyPair)
{
$this->keyPair = hex2bin($keyPair);
}
public function decrypt(string $input): string
{
$decrypted = sodium_crypto_box_seal_open(hex2bin($input), $this->keyPair);
if (empty($decrypted)) {
throw new \RuntimeException('Encryption failed');
}
return $decrypted;
}
}
$crypto = new LibsodiumDecryptor('66b70b4e93416f8a7a82a40a856…');
echo $crypto->decrypt('de261df126463f57b6aaaaaaaaaaa…');