A gentle solution for preventing hard coded passwords in R scripts. Uses data encryption with keys. The
hidePwd package use the data encryption functionality of the
PKI package and has easy functions for encrypting and decrpyting values of variables in R over different R-sessions.
The main purpose of this package is to substitute hard code passwords in scripts of the entire repository with variables containing the encrypted value of the password. The creater of the password can share the password and key to every trusted user. Every user that has the encrypted password and the key, can decipher the password and access the code in an R-session. In the end, both the creator and the trusted user do not expose the value of the password in the entire repository with R-scripts, only the name of the variable.
For several functions it is required to insert user credentials like the username and a password. For several reasons it is not desirable that the password is visable in the R-script. For security reasons the password should be hidden and not be exposed in the script or the same directory of the script.
An encrypted password is the solution. By generating a key and encrypt a password with the generated key, the original pattern of the password is not exposed in the script for the application.
- Password not exposed in R-scripts;
- Access to a database restricted to people with the key;
- Hide other values of variables that you do not want to have exposed;
- Simplified use of data encryption and decryption in R.
Script for generating a key and an encrypted password
library(hidePwd) # create a key db_key <- createPwdKey() # encrypt a password password_encrypted <- pwdEncrypt("HbgqeM#*CQ#!9", db_key) # (optional) check the encrypted password password_encrypted # save the encrypted password pwdSaveRDS(password_encrypted, "db_password_encrypted.rds") # filename for encrypted password requires the ".rds" extension # save the key that is needed to decrypt the password saveKeyRSA(key = db_key, "db_key.rsa") # filename for the key requires the ".rsa" extension
Script for using the encrypted password in an R script
# import the encrypted password encrypted_password <- pwdLoadRDS("db_password_encrypted.rds") # import key to decrypt password # key_db <- readKeyRDS("db_password_key.rds") # import rsa key to decrypt password key_db <- readKeyRSA("db_key.rsa") # (optional) show encrypted password encrypted_password # decrypt encrypted password with the imported key db_password <- pwdDecrypt(encrypted_password, key_db) # use the variable with the password in a function con = dbConnect(MySQL(), user='user', password=db_password, # use the variable with the decrypted password instead of the hard coded password dbname='sales', host='host')