sodium_crypto_secretbox

認証付きの共有鍵による暗号化

説明

string sodium_crypto_secretbox(string $message, string $nonce, string $key)

対称(共有)鍵を使い、メッセージを暗号化します。

パラメータ

message

暗号化するプレーンテキスト

nonce

メッセージごとに一度だけ使われる数値。 長さは24バイトです。 これは、 (たとえば、random_bytesを使って) ランダムな値を生成するのに十分大きな長さです。

key

暗号化キー(256ビット)

戻り値

暗号化された文字列を返します。

エラー / 例外

  • nonce の長さが SODIUM_CRYPTO_SECRETBOX_NONCEBYTES (24 バイト) と異なっている場合、 SodiumException がスローされます。
  • key の長さが、 SODIUM_CRYPTO_SECRETBOX_KEYBYTES (32 バイト) と異なっている場合、 SodiumException がスローされます。
  • 失敗時には、SodiumException がスローされます。

例1 sodium_crypto_secretbox の例

<?php
// The $key must be kept confidential
$key sodium_crypto_secretbox_keygen();
// Do not reuse $nonce with the same key
$nonce random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$plaintext "message to be encrypted";
$ciphertext sodium_crypto_secretbox($plaintext$nonce$key);

var_dump(bin2hex($ciphertext));
// The same nonce and key are required to decrypt the $ciphertext
var_dump(sodium_crypto_secretbox_open($ciphertext$nonce$key));
?>

上の例の出力は、 たとえば以下のようになります。

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

参考

  • sodium_crypto_secretbox_open
  • sodium_crypto_secretbox_keygen
  • random_bytes