Last active
July 31, 2023 15:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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