sodium_crypto_aead_chacha20poly1305_encrypt
(PHP 7 >= 7.2.0, PHP 8)
sodium_crypto_aead_chacha20poly1305_encrypt — Encrypt then authenticate with ChaCha20-Poly1305
说明
sodium_crypto_aead_chacha20poly1305_encrypt(
#[\SensitiveParameter] string
string
string
#[\SensitiveParameter] string
): string
#[\SensitiveParameter] string
$message
,string
$additional_data
,string
$nonce
,#[\SensitiveParameter] string
$key
): string
Encrypt then authenticate with ChaCha20-Poly1305.
参数
message
-
The plaintext message to encrypt.
additional_data
-
Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.
nonce
-
A number that must be only used once, per message. 8 bytes long.
key
-
Encryption key (256-bit).
返回值
Returns the ciphertext and tag on success, 或者在失败时返回 false
.
+添加备注
用户贡献的备注 1 note
alain at fuz dot org ¶
1 year 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`
备份地址:http://www.lvesu.com/blog/php/function.sodium-crypto-aead-chacha20poly1305-encrypt.php