Skip to content

Instantly share code, notes, and snippets.

@ctesta01
Last active July 31, 2023 15:29
Show Gist options
  • Save ctesta01/1e45af0612007119be23831fb26881bc to your computer and use it in GitHub Desktop.
Save ctesta01/1e45af0612007119be23831fb26881bc to your computer and use it in GitHub Desktop.
Functions to create encrypted files with a password using openssl and prompting for password
#' Create Encrypted Files
create_encrypted_height_weight_medications <- function() {
# load files to be encrypted
dfs <-
list(
file1 = "sensitive_data/file1.xlsx",
file2 = "sensitive_data/file2.xlsx",
file3 = "sensitive_data/file3.xlsx"
) %>% purrr::map(readxl::read_excel)
# serialize data
dfs_serialized <- dfs %>% serialize(NULL)
# query key from user
key <- sha256(charToRaw(rstudioapi::askForPassword("Enter encryption passphrase:")))
# encrypt data
encrypted_dfs <- aes_cbc_encrypt(dfs_serialized, key = key)
# save in encrypted data store
saveRDS(
encrypted_dfs,
file.path(
'sensitive_data/encrypted_r_readable/'
), 'encrypted_dfs.rds')
)
}
#' Read Encrypted Data
read_height_weight_medications <- function() {
# if the encryption key is already defined in the environment, use that;
# otherwise query the user for the encryption passphrase.
if (! exists('encryption_key')) {
encryption_key <-
openssl::sha256(charToRaw(rstudioapi::askForPassword("Enter encryption passphrase:")))
assign('encryption_key', encryption_key, envir = globalenv())
}
# load the encrypted data
encrypted_dfs <- readRDS(
'sensitive_data/encrypted_r_readable/encrypted_dfs.rds'
)
# decrypt and de-serialize the data into a list of dataframes
dfs <- unserialize(openssl::aes_cbc_decrypt(encrypted_dfs, key = encryption_key))
return(dfs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment