这是一个关于如何使用 sodium_crypto_box() 的快速示例;在其中两个人交换了一条 $message,其中第一个人对其进行加密,以便只有第二个人才能解密它,并且确保第一个人确实发送了它(没有被篡改)。
<?php
$keypair1 = sodium_crypto_box_keypair();
$keypair1_public = sodium_crypto_box_publickey($keypair1);
$keypair1_secret = sodium_crypto_box_secretkey($keypair1);
$keypair2 = sodium_crypto_box_keypair();
$keypair2_public = sodium_crypto_box_publickey($keypair2);
$keypair2_secret = sodium_crypto_box_secretkey($keypair2);
$message = 'hello';
$nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES);
$encryption_key = sodium_crypto_box_keypair_from_secretkey_and_publickey($keypair1_secret, $keypair2_public);
$encrypted = sodium_crypto_box($message, $nonce, $encryption_key);
echo base64_encode($encrypted) . "\n";
$decryption_key = sodium_crypto_box_keypair_from_secretkey_and_publickey($keypair2_secret, $keypair1_public);
$decrypted = sodium_crypto_box_open($encrypted, $nonce, $decryption_key);
echo $decrypted . "\n";
?>