CakeFest 2024: The Official CakePHP Conference

sodium_crypto_secretbox_open

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretbox_open認証付きの共有鍵による復号

説明

sodium_crypto_secretbox_open(string $ciphertext, string $nonce, string $key): string|false

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

パラメータ

ciphertext

sodium_crypto_secretbox() が生成したフォーマットでなければいけません。 (暗号化されたテキスト、タグを連結したもの)

nonce

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

key

暗号化キー(256ビット)

戻り値

成功時には、復号した文字列を返します。 失敗した場合に false を返します.

エラー / 例外

例1 sodium_crypto_secretbox_open() の例

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

// The same nonce and key are required to decrypt the $ciphertext
$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if (
$plaintext !== false) {
echo
$plaintext . PHP_EOL;
}
?>

上の例の出力は以下となります。

message to be encrypted

参考

add a note

User Contributed Notes 1 note

up
3
khalyomede at gmail dot com
5 years ago
This method will return a string, or false if the data failed to be decrypted.

$key = 'secret';
$data = 'binarydata';
$nonce = random_bytes(SODIUM_CRYPT_SECRETBOX_NONCEBYTES);

$decrypted = sodium_crypto_secretbox_open($data, $nonce, $key);

if ($decrypted === false) {
throw new Exception('failed to decrypt data');
}
To Top