函数名:sodium_crypto_box()
适用版本:PHP 7.2.0 及以上版本
用法:sodium_crypto_box() 函数用于使用公钥加密和私钥解密数据,基于 X25519 密钥交换和 XSalsa20-Poly1305 加密算法。
语法:
string sodium_crypto_box(string $message, string $nonce, string $publicKey, string $secretKey)
参数:
返回值:
示例:
// 生成公钥和私钥
$keyPair = sodium_crypto_box_keypair();
$publicKey = sodium_crypto_box_publickey($keyPair);
$secretKey = sodium_crypto_box_secretkey($keyPair);
// 要加密的消息
$message = "Hello, world!";
$nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES); // 生成随机的 nonce
// 使用公钥加密消息
$ciphertext = sodium_crypto_box($message, $nonce, $publicKey, $secretKey);
// 使用私钥解密消息
$decryptedMessage = sodium_crypto_box_open($ciphertext, $nonce, $publicKey, $secretKey);
// 输出结果
echo "加密后的消息: " . base64_encode($ciphertext) . "\n";
echo "解密后的消息: " . $decryptedMessage . "\n";
注意事项: