If you want to encrypt and decrypt a string (only if the data is leaving the current machine and only if the receiver machine is allowed to decrypt the data), you can use example below. The encrypted data will always be dynamic so the result will always be different for given string. It uses Sodium on a PHP 7.2+ machine. Note: Read comments in the code.


Class


You might need to add "ext-sodium": "*" to your composer.json file. Also read what exactly the relevant function does here.


/**
* Use if the data is leaving the current machine.
* Use only if the receiver machine is allowed to decrypt the data. A -> B
*
* Use bin2hex() on encrypted data before sending.
* Use hex2bin() on encrypted data before decrypting.
*/
class Sender
{
/**
* This is what sender computer does.
*
* @param string $plainData This is what sender computer will send
* @param string $otherComputersPublicKey This belongs to the other computer where the message will be sent to
*
* @return string
*/
public function encrypt(string $plainData, string $otherComputersPublicKey): string
{
return sodium_crypto_box_seal($plainData, $otherComputersPublicKey);
}

/**
* This is what receiver computer does.
*
* @param string $encryptedData This comes from the sender computer
* @param string $keyPair This belongs to receiver computer where the message will be handled
*
* @return string
*/
public function decrypt(string $encryptedData, string $keyPair): string
{
return sodium_crypto_box_seal_open($encryptedData, $keyPair);
}
}

Test


class SenderTest extends TestCase
{
private $otherComputersKeyPair;
private $otherComputersPublicKey;

protected function setUp()
{
$this->otherComputersKeyPair = sodium_crypto_box_keypair();
$this->otherComputersPublicKey = sodium_crypto_box_publickey($this->otherComputersKeyPair);
}

public function testEncrypt(): void
{
$dataToBeSent = (new Sender())->encrypt('inanzzz', $this->otherComputersPublicKey);

$this->assertIsString($dataToBeSent);
}

public function testDecrypt(): void
{
// Sender
$dataReceived = (new Sender())->encrypt('inanzzz', $this->otherComputersPublicKey);

// Receiver
$result = (new Sender())->decrypt($dataReceived, $this->otherComputersKeyPair);

$this->assertSame('inanzzz', $result);
}
}