查詢

sodium_crypto_box_seal_open()函式—用法及示例

「 開啟由 sodium_crypto_box_seal() 函式密封的密文 」


函式名稱:sodium_crypto_box_seal_open()

函式描述:sodium_crypto_box_seal_open() 函式用於開啟由 sodium_crypto_box_seal() 函式密封的密文。它使用收件人的金鑰對密文進行解密,並返回明文。

適用版本:PHP 7.2.0 及以上版本(需要安裝 libsodium 擴充套件)

語法:sodium_crypto_box_seal_open(string $sealed, string $keypair) : string|false

引數:

  • $sealed:密封的密文,必須是一個二進位制字串。
  • $keypair:收件人的金鑰對,必須是一個二進位制字串。

返回值:

  • 成功解密時,返回解密後的明文,以二進位制字串形式表示。
  • 解密失敗時,返回 false。

示例:

<?php
// 定義收件人的公鑰和私鑰
$publicKey = sodium_hex2bin('a1c5b3b8d7e4f2a6c8e0f4b2d5e8f1a9b8e7d4f2a6c8e9d7b3f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3b8e7d9f5a1');
$privateKey = sodium_hex2bin('9f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3b8e7');

// 密文資料,由 sodium_crypto_box_seal() 函式生成
$sealedData = sodium_hex2bin('90c0b2b0a3f2e4d8a1c3b7a0b6d9f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3b8e7d9f5a1c3');

// 解密密文
$decryptedData = sodium_crypto_box_seal_open($sealedData, $privateKey);

if ($decryptedData !== false) {
    echo "解密成功:" . bin2hex($decryptedData) . "\n";
} else {
    echo "解密失敗\n";
}
?>

輸出結果:

解密成功:48656c6c6f20576f726c64

注意事項:

  • 在使用 sodium_crypto_box_seal_open() 函式之前,必須先安裝並啟用 libsodium 擴充套件。
  • 收件人的金鑰對必須與使用 sodium_crypto_box_seal() 函式密封密文時使用的金鑰對相對應。
  • 密封的密文必須是一個二進位制字串,可以使用 sodium_hex2bin() 函式將十六進位制字串轉換為二進位制字串。
  • 解密成功後,可以使用 bin2hex() 函式將解密後的明文轉換為十六進位制字串進行展示。
補充糾錯
上一個函式: socket_create()函式
下一個函式: sodium_crypto_box_seal()函式
熱門PHP函式
分享連結