函式名:sodium_crypto_box_seal()
適用版本:PHP 7.2.0及以上版本
函式描述:sodium_crypto_box_seal()函式用於對稱加密一個訊息,使其只能被私鑰所有者解密。該函式使用公鑰加密,私鑰解密的方式進行加密。它適用於不需要進行金鑰交換的場景。
用法:
string sodium_crypto_box_seal ( string $message , string $public_key )
引數:
- $message:要加密的訊息,型別為字串。
- $public_key:公鑰,型別為字串。
返回值:
- 返回一個加密後的字串,該字串只能由私鑰持有者解密。
示例:
// 生成金鑰對
$keyPair = sodium_crypto_box_keypair();
// 獲取公鑰和私鑰
$publicKey = sodium_crypto_box_publickey($keyPair);
$privateKey = sodium_crypto_box_secretkey($keyPair);
// 要加密的訊息
$message = "Hello, world!";
// 使用公鑰加密訊息
$encryptedMessage = sodium_crypto_box_seal($message, $publicKey);
// 使用私鑰解密訊息
$decryptedMessage = sodium_crypto_box_seal_open($encryptedMessage, $keyPair);
echo "原始訊息:".$message."\n";
echo "加密後的訊息:".$encryptedMessage."\n";
echo "解密後的訊息:".$decryptedMessage."\n";
注意事項:
- 使用sodium_crypto_box_seal()函式加密的訊息只能使用sodium_crypto_box_seal_open()函式解密。
- 在使用該函式之前,確保已經安裝了libsodium擴充套件,並且PHP版本大於等於7.2.0。
- 金鑰對的生成可以使用sodium_crypto_box_keypair()函式來實現。