函式名稱:sodium_crypto_box_secretkey()
函式描述:生成一個新的金鑰對的私鑰,用於Sodium擴充套件庫中的加密和解密操作。
適用版本:PHP 7.2.0及以上版本。
用法:
生成新的金鑰對的私鑰:
$secretKey = sodium_crypto_box_secretkey();
這將生成一個新的私鑰,並將其賦值給變數$secretKey。私鑰是一個二進位制字串,可用於進行加密和解密操作。
儲存私鑰到檔案:
file_put_contents('private.key', $secretKey);
將私鑰儲存到檔案中,以便在後續的加密和解密操作中使用。
示例:
<?php
// 生成新的金鑰對的私鑰
$secretKey = sodium_crypto_box_secretkey();
// 儲存私鑰到檔案
file_put_contents('private.key', $secretKey);
// 載入私鑰
$secretKey = file_get_contents('private.key');
// 使用私鑰進行加密和解密操作
$message = 'Hello, world!';
$nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES);
$publicKey = sodium_crypto_box_publickey_from_secretkey($secretKey);
$ciphertext = sodium_crypto_box($message, $nonce, $publicKey, $secretKey);
// 輸出加密後的密文
echo 'Ciphertext: ' . base64_encode($ciphertext) . PHP_EOL;
// 使用私鑰進行解密操作
$decrypted = sodium_crypto_box_open($ciphertext, $nonce, $publicKey, $secretKey);
// 輸出解密後的明文
echo 'Decrypted: ' . $decrypted . PHP_EOL;
?>
上述示例中,首先使用sodium_crypto_box_secretkey()生成一個新的私鑰,並將其儲存到檔案中。然後,載入私鑰並使用它進行加密操作。最後,使用相同的私鑰進行解密操作,輸出解密後的明文。請注意,示例中還使用了其他Sodium擴充套件庫中的函式,如sodium_crypto_box_publickey_from_secretkey()、sodium_crypto_box()和sodium_crypto_box_open()。