Beryl::Crypto::V1::AuthenticatedEncryption
Encryption that also proves a message is whole and came from someone who
holds the key (authenticated encryption with associated data, RFC 5116).
ChaCha20Poly1305, XChaCha20Poly1305 and AESGCM are the ciphers; this
class is what they share.
cipher = Beryl::Crypto::V1::XChaCha20Poly1305.new(key)
nonce = Random::Secure.random_bytes(cipher.nonce_bytesize)
sealed = cipher.encrypt("a private note", nonce: nonce, associated_data: "note 42")
cipher.decrypt(sealed, nonce: nonce, associated_data: "note 42") # => the note's bytes
cipher.decrypt(sealed, nonce: nonce, associated_data: "note 43") # => nil
An encrypted message is the ciphertext followed by the authentication tag. associated_data is authenticated and left readable; both sides must supply the same bytes. A nonce must never repeat under one key.
Decryption checks the tag before it returns a single byte of plaintext:
a message that fails the check returns nil (or false), and the
caller's into: buffer is overwritten with zeros, whatever its length
and whichever code ran (a cipher may decrypt while it checks). The check
takes the same time whatever the key, the message and the tag hold.
wipe zeroes every buffer derived from the key; after it, every
encryption, decryption and tag check raises KeyWiped.
Constants
The size of a full tag, in bytes, for every cipher in this shard.
Instance methods
Returns whether ciphertext_and_tag carries the right tag for nonce and associated_data, without decrypting it. The comparison runs in constant time.
Returns the plaintext of ciphertext_and_tag, or nil when the
message, the nonce or the associated data is not what was encrypted.
Decrypts ciphertext_and_tag into plaintext, which must be
tag_bytesize bytes shorter, and returns true; or returns false and
overwrites all of plaintext with zeros when the message fails
authentication.
Returns plaintext encrypted under nonce: the ciphertext, then the tag.
Encrypts plaintext under nonce into ciphertext_and_tag, which
must be tag_bytesize bytes longer than the plaintext.
Zeroes the key and everything derived from it (round keys, hash keys)
through SecretWiping. The cipher cannot be used afterward: every
encryption, decryption and tag check raises KeyWiped.