This is a low-level function for encrypting/decrypting data using 'Authenticated Encryption with Additional Data' (AEAD). This encryption scheme assures data confidentiality (privacy) i.e. the encrypted data is impossible to understand without the knowledge of the secret key.

The authenticity of the message is also assured i.e. the message is unforgeable.

Additional data can optionally be included in the encryption process. This data is not encrypted, nor is it included with the output. Instead this data is a part of the message authentication. See below for more details.

encrypt_raw(x, key, additional_data = NULL)

decrypt_raw(src, key, additional_data = NULL)

Arguments

x

Data to encrypt. Character string or raw vector.

key

The encryption key. This may be a character string, a 32-byte raw vector or a 64-character hex string (which encodes 32 bytes). When a shorter character string is given, a 32-byte key is derived using the Argon2 key derivation function.

additional_data

Additional data to include in the authentication. Raw vector or character string. Default: NULL. This additional data is not included with the encrypted data, but represents an essential component of the message authentication. The same additional_data must be presented during both encryption and decryption for the message to be authenticated. See vignette on 'Additional Data'.

src

Raw vector of data to decrypt

Value

encrypt_raw() returns a raw vector containing the nonce, mac and the encrypted data

decrypt_raw() returns the decrypted data as a raw vector

Details

Implements authenticated encryption as documented here https://monocypher.org/manual/aead

Technical Notes

The encryption functions in this package implement RFC 8439 ChaCha20-Poly1305 authenticated encryption with additional data. This algorithm combines the ChaCha20 stream cipher with the Poly1305 message authentication code.

Examples

# Encrypt/Decrypt a string or raw vector
# Data to encrypt
dat <- "Follow the white rabbit" |> charToRaw()

# Create an encryption key
key <- argon2("my secret key") # Keep this key secret!
key
#> [1] "4efc5724863e58fe84aeea94fce1be1a9b312417082003caf359579d131bd08d"

# Encrypt the data
enc <- encrypt_raw(dat, key)
enc
#>  [1] 58 84 f7 0c 52 20 8f 83 51 9b 0f c3 b3 c1 54 0e e3 8e 64 48 e6 f0 c5 f0 c8
#> [26] 8a d2 06 c0 25 8a 8d 95 cd 6e f4 d7 d4 92 f3 61 13 f3 2e 05 4f 9a cc d1 88
#> [51] ed 3f f2 04 a4 4a bc 02 f6 34 96 bc c2

# Using the same key, decrypt the data 
decrypt_raw(enc, key) |> rawToChar()
#> [1] "Follow the white rabbit"