PHP Conference Japan 2024

sodium_crypto_secretbox

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretbox已驗證的共享金鑰加密

描述

sodium_crypto_secretbox(#[\SensitiveParameter] 字串 $message, 字串 $nonce, #[\SensitiveParameter] 字串 $key): 字串

使用對稱(共享)金鑰加密訊息。

參數

message

要加密的明文訊息。

nonce

一個訊息中只能使用一次的數字,長度為 24 位元組。這個長度足以用於隨機生成 (例如:random_bytes())。

金鑰 (key)

加密金鑰 (256 位元)。

回傳值

回傳加密後的字串。

錯誤/例外

範例

範例 #1 sodium_crypto_secretbox() 範例

<?php
// $key 必須保密
$key = sodium_crypto_secretbox_keygen();
// 不要重複使用相同的 key 和 $nonce
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$plaintext = "要加密的訊息";
$ciphertext = sodium_crypto_secretbox($plaintext, $nonce, $key);

var_dump(bin2hex($ciphertext));
// 解密 $ciphertext 需要相同的 nonce 和 key
var_dump(sodium_crypto_secretbox_open($ciphertext, $nonce, $key));
?>

上述範例的輸出會類似於

string(78) "3a1fa3e9f7b72ef8be51d40abf8e296c6899c185d07b18b4c93e7f26aa776d24c50852cd6b1076"
string(23) "message to be encrypted"

參見

新增筆記

使用者貢獻的筆記 1 則筆記

celso fontes
4 年前
使用 sodium 加密或解密的範例

<?php

$key
= random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);

$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox("Hello World !", $nonce, $key);

$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if (
$plaintext === false) {
throw new
Exception("Bad ciphertext");
}

echo
$plaintext;
To Top