Encrypt and decrypt data and other things

Encrypt and decrypt raw data, objects, strings and files. The core functions here are encrypt_data and decrypt_data which take raw data and decrypt it, writing either to file or returning a raw vector. The other functions encrypt and decrypt arbitrary R objects (encrypt_object, decrypt_object), strings (encrypt_string, decrypt_string) and files (encrypt_file, decrypt_file).

encrypt_data(data, key, dest = NULL)

encrypt_object(object, key, dest = NULL, rds_version = NULL)

encrypt_string(string, key, dest = NULL)

encrypt_file(path, key, dest = NULL)

decrypt_data(data, key, dest = NULL)

decrypt_object(data, key)

decrypt_string(data, key)

decrypt_file(path, key, dest = NULL)


(for encrypt_data, decrypt_data, decrypt_object, decrypt_string) a raw vector with the data to be encrypted or decrypted. For the decryption functions this must be data derived by encrypting something or you will get an error.


A cyphr_key or cyphr_key object describing the encryption approach to use.


The destination filename for the encrypted or decrypted data, or NULL to return a raw vector. This is not used by decrypt_object or decrypt_string which always return an object or string.


(for encrypt_object) an arbitrary R object to encrypt. It will be serialised to raw first (see serialize).


RDS serialisation version to use (see serialize. The default in R version 3.3 and below is version 2 - in the R 3.4 series version 3 was introduced and is becoming the default. Version 3 format serialisation is not understood by older versions so if you need to exchange data with older R versions, you will need to use rds_version = 2. The default argument here (NULL) will ensure the same serialisation is used as R would use by default.


(for encrypt_string) a scalar character vector to encrypt. It will be converted to raw first with charToRaw.


(for encrypt_file) the name of a file to encrypt. It will first be read into R as binary (see readBin).

  • encrypt_data
  • encrypt_object
  • encrypt_string
  • encrypt_file
  • decrypt_data
  • decrypt_object
  • decrypt_string
  • decrypt_file
key <- key_sodium(sodium::keygen())
# Some super secret data we want to encrypt:
x <- runif(10)
# Convert the data into a raw vector:
data <- serialize(x, NULL)
# Encrypt the data; without the key above we will never be able to
# decrypt this.
data_enc <- encrypt_data(data, key)
# Our random numbers:
unserialize(decrypt_data(data_enc, key))
# Same as the never-encrypted version:

# This can be achieved more easily using `encrypt_object`:
data_enc <- encrypt_object(x, key)
identical(decrypt_object(data_enc, key), x)

# Encrypt strings easily:
str_enc <- encrypt_string("secret message", key)
decrypt_string(str_enc, key)
# }
Documentation reproduced from package cyphr, version 1.0.2, License: MIT + file LICENSE

Community examples

Looks like there are no examples yet.