Eğer bir bilgiyi şifrelemek (encryption) ve deşifrelemek (decryption) istiyorsanız (eğer bilgi bulunduğu makinadan ayrılıyorsa ve sadece bilginin gittiği makina deşifreleme işlemi yapacaksa), aşağıdaki örneği kullanabilirsiniz. Şifrelenen verinin sonucu her zaman farklı olacak. Örneğimiz PHP 7.2+ makinada Sodium kullanıyor. Not: Kod içindeki yorumları okuyun.


Class


Uygulamanızdaki composer.json dosyasına "ext-sodium": "*" ekini eklemeniz gerekebilir. Ayrıca ilgili fonksiyonun tam olarak ne yaptığını öğrenmek isterseniz burayı okuyabilirsiniz.


/**
* 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);
}
}