2024 年 PHP Conference Japan

sodium_crypto_stream_xchacha20_xor_ic

(PHP 8 >= 8.2.0)

sodium_crypto_stream_xchacha20_xor_ic使用 nonce 和密鑰加密訊息(無驗證)

說明

sodium_crypto_stream_xchacha20_xor_ic(
    #[\SensitiveParameter] 字串 $message,
    字串 $nonce,
    整數 $counter,
    #[\SensitiveParameter] 字串 $key
): 字串

此函數與 sodium_crypto_stream_xchacha20_xor() 類似,但增加了將區塊計數器的初始值設定為非零值的功能。這允許直接存取任何區塊,而無需計算先前的區塊。

注意

此加密未經身份驗證,並且無法防止選擇密文攻擊。請確保將密文與訊息鑑別碼 (MAC) 結合使用,例如使用 sodium_crypto_aead_xchacha20poly1305_ietf_encrypt() 函數或 sodium_crypto_auth()

參數

message

要加密的訊息。

nonce

24 位元組的 nonce。

counter

區塊計數器的初始值。

key

金鑰,可能由 sodium_crypto_stream_xchacha20_keygen() 產生。

傳回值

加密後的訊息,如果失敗則傳回 false

範例

範例 #1 sodium_crypto_stream_xchacha20_xor_ic() 範例

<?php
$n2
= random_bytes(SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES);
$left = str_repeat("\x01", 64);
$right = str_repeat("\xfe", 64);

// 一次全部加密:
$stream7_unified = sodium_crypto_stream_xchacha20_xor($left . $right, $n2, $key);

// 分段加密,使用初始計數器:
$stream7_left = sodium_crypto_stream_xchacha20_xor_ic($left, $n2, 0, $key);
$stream7_right = sodium_crypto_stream_xchacha20_xor_ic($right, $n2, 1, $key);
$stream7_concat = $stream7_left . $stream7_right;

var_dump(strlen($stream7_concat));
var_dump($stream7_unified === $stream7_concat);
?>

上述範例將輸出類似以下的內容:

int(128)
bool(true)

參見

新增筆記

使用者貢獻的筆記

此頁面沒有使用者貢獻的筆記。
To Top