PHP 8.1.28 Released!

sodium_crypto_secretbox

(PHP 7 >= 7.2.0, PHP 8)

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

説明

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

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

パラメータ

message

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

nonce

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

key

暗号化キー(256ビット)

戻り値

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

エラー / 例外

例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"

参考

add a note

User Contributed Notes 1 note

up
0
celso fontes
3 years ago
An example to how encrypt or decrypt using 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