PHP8 sodium_crypto_secretstream_xchacha20poly1305_init_push

2024-03-18 14:05 更新

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_init_push — 初始化用于加密的 secretstream 上下文

說明

sodium_crypto_secretstream_xchacha20poly1305_init_push(string $key): array

初始化用于加密的 secretstream 上下文。

參數(shù) 

key

加密密鑰。見sodium_crypto_secretstream_xchacha20poly1305_keygen())。

返回值 

具有兩個(gè)字符串值的數(shù)組:

  • 進(jìn)一步推送所需的 secretstream 狀態(tài)
  • secretstream 標(biāo)頭,需要提供給收件人,以便他們可以提取數(shù)據(jù)

示例 

示例 #1 sodium_crypto_secretstream_xchacha20poly1305_init_push() example

<?php
function encrypt_file(string $inputFilePath, string $outputFilePath, string $key): void
{
    [$state, $header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($key);

    $inputFile = fopen($inputFilePath, 'rb');
    $outputFile = fopen($outputFilePath, 'wb');
    // Write the header:
    fwrite($outputFile, $header);
    $inputFileSize = fstat($inputFile)['size'];

    // Encrypt the file and write its contents to the output file:
    for ($i = 0; $i < $inputFileSize; $i += 8175) {
        $ptxt_chunk = fread($inputFile, 8175);
        $ctxt_chunk = sodium_crypto_secretstream_xchacha20poly1305_push($state, $ptxt_chunk);
        fwrite($outputFile, $ctxt_chunk);
    }

    sodium_memzero($state);
    fclose($inputFile);
    fclose($outputFile);
}

// sodium_crypto_secretstream_xchacha20poly1305_keygen()
$key = sodium_base642bin('MS0lzb7HC+thY6jY01pkTE/cwsQxnRq0/2L1eL4Hxn8=', SODIUM_BASE64_VARIANT_ORIGINAL);

file_put_contents('hello.txt', 'Hello world!');
encrypt_file('hello.txt', 'hello.txt.encrypted', $key);
var_dump(sodium_bin2hex(file_get_contents('hello.txt.encrypted')));
?>

以上示例的輸出類似于:

string(106) "971e33b255f0990ef3931caf761c59136efa77b434832f28ec719e3ff73f5aec38b3bba1574ab5b70a8844d8da36a668e802cfea2c"


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號