(PHP 7 >= 7.2.0,PHP 8)
sodium_crypto_secretstream_xchacha20poly1305_init_pull — 初始化用於解密的 secretstream 內容
$header
, #[\SensitiveParameter] string $key
): string初始化用於解密的 secretstream 內容。
header
secretstream 的標頭。這應該是 sodium_crypto_secretstream_xchacha20poly1305_init_push() 產生的其中一個值。
key
加密金鑰 (256 位元)。
Secretstream 狀態。
範例 #1 sodium_crypto_secretstream_xchacha20poly1305_init_pull() 範例
<?php
function decrypt_file(string $inputFilePath, string $outputFilePath, string $key): void
{
$inputFile = fopen($inputFilePath, 'rb');
$outputFile = fopen($outputFilePath, 'wb');
$header = fread($inputFile, 24);
$state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($header, $key);
$inputFileSize = fstat($inputFile)['size'];
// 解密檔案並將其內容寫入輸出檔案:
for ($i = 24; $i < $inputFileSize; $i += 8192) {
$ctxt_chunk = fread($inputFile, 8192);
// 我們沒有使用 $tag,但在實際協定中,您可以在加密時使用它,例如
// 觸發重新金鑰或指示檔案結尾。然後,在解密時,您可以斷言
// 此行為。
[$ptxt_chunk, $tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($state, $ctxt_chunk);
fwrite($outputFile, $ptxt_chunk);
}
sodium_memzero($state);
fclose($inputFile);
fclose($outputFile);
}
// sodium_crypto_secretstream_xchacha20poly1305_keygen()
$key = sodium_base642bin('MS0lzb7HC+thY6jY01pkTE/cwsQxnRq0/2L1eL4Hxn8=', SODIUM_BASE64_VARIANT_ORIGINAL);
$example = sodium_hex2bin('971e33b255f0990ef3931caf761c59136efa77b434832f28ec719e3ff73f5aec38b3bba1574ab5b70a8844d8da36a668e802cfea2c');
file_put_contents('hello.enc', $example);
decrypt_file('hello.enc', 'hello.txt.decrypted', $key);
var_dump(file_get_contents('hello.txt.decrypted'));
?>
上面的範例將會輸出類似以下的內容
string(12) "Hello world!"