Laravel Live Japan

sodium_crypto_aead_chacha20poly1305_encrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_encryptChaCha20-Poly1305 を使って暗号化し、認証を行う

説明

sodium_crypto_aead_chacha20poly1305_encrypt(
    #[\SensitiveParameter] string $message,
    string $additional_data,
    string $nonce,
    #[\SensitiveParameter] string $key
): string

ChaCha20-Poly1305 を使って暗号化し、認証を行います。

パラメータ

message

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

additional_data

追加の認証データ。 これは、 暗号化されたテキストに追加された認証タグを検証するのに用いられますが、 このデータは暗号化されていませんし、 暗号化されたテキストにも保存されません。

nonce

メッセージごとに一度だけ使われる数値。 長さは8バイトです。

key

暗号化キー(256ビット)

戻り値

成功時には、暗号化されたテキストと、 認証タグを返します。 失敗した場合に false を返します.

add a note

User Contributed Notes 1 note

up
1
alain at fuz dot org
2 years ago
A flip/flop unit test to give you a sample:

<?php

use PHPUnit\Framework\TestCase;

class SodiumTest extends TestCase
{
    public function testSodium()
    {
        // or 32 cryptographically secure bytes
        // store the key securely with other secrets in your app 
       $key = sodium_crypto_aead_xchacha20poly1305_ietf_keygen();

        // 8-bytes nonce should be stored along with the ciphertext (will be needed for decryption)
        // It is not sensitive, you may just prepend it before the ciphertext.
        $nonce = random_bytes(SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES);

        $flip = 'Hello, world!';
        $ciphertext = sodium_crypto_aead_chacha20poly1305_encrypt($flip, $nonce, $nonce, $key);
        $flop = sodium_crypto_aead_chacha20poly1305_decrypt($ciphertext, $nonce, $nonce, $key);

        $this->assertEquals($flip, $flop);
    }
}

?>

Side note: the nonce is used twice in this test, but you can use a username, an identifier or whatever you like in `$additional_data`
To Top