如果你想对一个字符串进行加密和解密(只有当数据离开当前机器时,并且只有当接收机器被允许解密该数据时),你可以使用下面的例子。加密的数据将永远是动态的,所以对于给定的字符串,其结果将永远是不同的。它在PHP7.2以上的机器上使用Sodium。**注意:**阅读代码中的注释。
类别
你可能需要在你的composer.json 文件中添加"ext-sodium": "*" 。也请阅读这里的相关函数的具体作用。
/**
* 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);
}
}
测试
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);
}
}