R/encrypted_rds.R

Defines functions read_encrypted_rds save_encrypted_rds

Documented in read_encrypted_rds save_encrypted_rds

#' Read and write RDS files with encrypted contents
#'
#' Uses \link{openssl} to encrypt/decrypt the contents of an RDS file. A user
#' supplied passphrase is hashed into a 32-bit key using
#' \code{\link[openssl]{sha256}}, which is then passed to
#' \code{\link[openssl]{aes_cbc_encrypt}} for encryption or
#' \code{\link[openssl]{aes_cbc_decrypt}} for decryption.
#'
#' @name encrypted_rds
#'
#' @param x An R object to serialize, encrypt, and save
#' @param file File path to read from or save to
#' @param passphrase Passphrase used to generate 32-bit key for
#'   encryption/decryption. By default uses \code{\link[getPass]{getPass}} to
#'   allow for masked input.
#'
#' @return
#' For `read_encrypted_rds`, an R object. For `save_encrypted_rds`, returns
#' `NULL` invisibly.
#'
#' @examples
#' \dontrun{
#'   dat <- data.frame(x = letters[1:4], y = 1:4, stringsAsFactors = FALSE)
#'
#'   # serialize, encrypt, and write to RDS (will be prompted for passphrase)
#'   file_write <- file.path(tempdir(), "dat.rds")
#'   save_encrypted_rds(dat, file_write)
#'
#'   # read RDS, decrypt, and unserialize (will be prompted for passphrase)
#'   dat <- read_encrypted_rds(file_write)
#' }


#' @rdname encrypted_rds
#' @importFrom openssl sha256 aes_cbc_decrypt
#' @importFrom getPass getPass
#' @export save_encrypted_rds
save_encrypted_rds <- function(x, file, passphrase = getPass::getPass()) {
  passphrase_raw <- charToRaw(passphrase)
  key <- openssl::sha256(passphrase_raw)

  x_serialized <- serialize(x, connection = NULL)
  x_encrypted <- openssl::aes_cbc_encrypt(x_serialized, key = key)

  saveRDS(x_encrypted, file)
}


#' @rdname encrypted_rds
#' @importFrom openssl sha256 aes_cbc_decrypt
#' @importFrom getPass getPass
#' @export read_encrypted_rds
read_encrypted_rds <- function(file, passphrase = getPass::getPass()) {
  x_encrypted <- readRDS(file)
  key <- openssl::sha256(charToRaw(passphrase))
  unserialize(openssl::aes_cbc_decrypt(x_encrypted, key = key))
}
epicentre-msf/llutils documentation built on Nov. 9, 2020, 8:24 p.m.