leigh/aead-chacha20-poly1305

RFC 7539 ChaCha20/Poly1305 AEAD 构造

0.2.1 2016-02-05 15:59 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:09:44 UTC


README

这个库包含了对 RFC 7539 ChaCha20/Poly1305 AEAD 构造的纯 PHP 实现。

用法

记住,一个 nonce 不得为特定的密钥重复使用

该库包含了一次性函数,用于处理少量数据,以及处理信息流的方法,而不会消耗大量内存。

一次性函数

// Encrypt and produce a ciphertext and tag.
list($ciphertext, $tag) = \ChaCha20Poly1305\encrypt($key, $nonce, $aad, $plaintext);

// Decrypt and produce a plaintext, throw an exception if the tag is invalid.
$plaintext = \ChaCha20Poly1305\decrypt($key, $nonce, $aad, $plaintext, $tag);

// Verify without decryption, return true/false depending the tag being valid.
$valid = \ChaCha20Poly1305\verify($key, $nonce, $aad, $plaintext, $tag);

Context 对象维护所有移动部件的当前状态,以便它们可以用于流处理。每个流需要一个单独的上下文。

流方法

$cipher = new \ChaCha20Poly1305\Cipher;
$encCtx = $cipher->init($key, $nonce);

$cipher->aad($encCtx, $additionalData);
$cipher->aad($encCtx, $moreData);

$ciphertext = $cipher->encrypt($encCtx, $plaintext);
$ciphertext .= $cipher->encrypt($encCtx, $morePlaintext);

$tag = $cipher->finish($encCtx);

// Or

$cipher = new \ChaCha20Poly1305\Cipher;
$decCtx = $cipher->init($key, $nonce);

$cipher->aad($decCtx, $additionalData);
$cipher->aad($decCtx, $moreData);

// Could also $cipher->verify() to skip decryption overhead.
$plaintext = $cipher->decrypt($decCtx, $ciphertext);
$plaintext .= $cipher->decrypt($decCtx, $moreCiphertext);

try {
    $cipher->finish($decCtx, $tag);
}
catch (\ChaCha20Poly1305\AuthenticationException $e) {
    // Tag was not valid
}