Skip to contents

[Maturing]

lock_file() and unlock_file can encrypt/decrypt any kind of file using an RSA key pair. If your project doesn't have an RSA key pair, you can use rsa_keygen() to create one.

These functions use encrypt_envelope() / decrypt_envelope() to perform file encryption/decryption. See those functions to learn more about the encrypting/decrypting process.

Usage

lock_file(
  file,
  public_key = "./inst/ssh/id_rsa.pub",
  suffix = ".lockr",
  remove_file = TRUE
)

unlock_file(
  file,
  private_key = "./inst/ssh/id_rsa",
  suffix = ".lockr",
  remove_file = TRUE,
  password = NULL
)

Arguments

file

A string with the file path to be encrypted/decrypted. For security reasons, encrypted files must end with the suffix parameter.

public_key

(optional) an openssl RSA public key or a string specifying the public key path. See rsa_keygen() to learn how to create an RSA key pair (default: "./inst/ssh/id_rsa.pub").

suffix

(optional) a string specifying the suffix to be added (when encrypting)/removed (when decrypting) to/of the file. It must start with . (default: ".lockr").

remove_file

(optional) a logical value indicating if the original file must be removed after the encryption/decryption process (default: TRUE).

private_key

(optional) an openssl RSA private key or a string specifying the private key path. See rsa_keygen() to learn how to create an RSA key pair (default: "./inst/ssh/id_rsa").

password

(optional) only for protected keys. A string specifying the password to read the private key. Avoid typing passwords on the console, use askpass() instead (default: NULL).

Value

An invisible string containing the locked/unlocked file path.

See also

Other lock/unlock functions: lock_dir()

Examples

## Locking files

temp_dir <- tempfile("dir")
dir.create(temp_dir)
temp_file <- tempfile(tmpdir = temp_dir)
rsa_keygen(temp_dir)
#> Keys successfully created at '/tmp/RtmpoFK8iT/dir1d2e769eaf45'.

con <- file(temp_file, "w+")
cat("Test", file = temp_file, sep = "\n")
list.files(temp_dir)
#> [1] "file1d2e549e8d73" "id_rsa"           "id_rsa.pub"      
suppressWarnings(readLines(con))
#> [1] "Test"
close(con)

lock_file(temp_file, public_key = file.path(temp_dir, "id_rsa.pub"))
#> Locked file written at
#> '/tmp/RtmpoFK8iT/dir1d2e769eaf45/file1d2e549e8d73.lockr'.

temp_file_locked <- paste0(temp_file, ".lockr")
con <- file(temp_file_locked, "rb")
list.files(temp_dir)
#> [1] "file1d2e549e8d73.lockr" "id_rsa"                 "id_rsa.pub"            
suppressWarnings(readLines(con))
#> [1] "\037\x8b\b"
close(con)

## Unlocking files

unlock_file(temp_file_locked, private_key = file.path(temp_dir, "id_rsa"))
#> Unlocked file written at '/tmp/RtmpoFK8iT/dir1d2e769eaf45/file1d2e549e8d73'.

list.files(temp_dir)
#> [1] "file1d2e549e8d73" "id_rsa"           "id_rsa.pub"      
con <- file(temp_file, "r+")
readLines(con)
#> [1] "Test"
close(con)