How to hide / asterisk part of the code in R?

I entered the password inside my code in Rstudio and I just want to make it obscure somehow, so when I show my code to someone, they don't see the password. Any suggestions on how to do this? Many thanks


source to share

4 answers

you have to create a new R script (call it login_credentials.R) and store your password there

username <- "username_here"
password <- "password_here"


Once you save this, you can load this script with source ()

This is where the username and password variables will be loaded.

> username
[1] "username_here"
> password
[1] "password_here"    





You can hide your password in the original file.

You can run something like

# as.raw(c(0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64))


to get a numeric password write-off. Then you can include in your script

pwd <- as.raw(c(0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64))
login("username", rawToChar(pwd))


This will at least make it less human-readable and won't be a variable in the environment browser with a text value (at least I guess I'm not sure how RStudio displays the raw data).



A somewhat safer solution is to store your password hash. This can be achieved with the function digest


> digest :: digest ("password")
[1] "380796939c86c55d6aa8ea8c941f7652" 

This implements an MD5 hash which is a one-way cryptographic function and the original password cannot be extracted from this hash i.e. there is no inverse function.

Then you will need to change the part of your code where you enter the password by hashing the entered password:

# Username and password part of code
username <- "username_here"
password_hash <- "380796939c86c55d6aa8ea8c941f7652"


# Password testing part of code
if (digest::digest(user_password_input) == password_hash){


where user_password_input

is a variable containing the entered password. The hashed password is secure because even if someone has your hashed password, they cannot use it to pass password verification. If they enter a hash of your password, it will be re-changed and different from the variable password_hash


Using hashes is a good practice as your actual passwords are never stored in code and the hashes themselves are not used.



You can create a file .Renviron

in your home directory or in the project directory where you store such information in an environment variable for use in your R scripts.

If it is content ~/.Renviron

or /path/to/my/project/.Renviron




Then you can get secretsecret

through Sys.getenv("YO")

. I wrote how to do this for API Authentication here .

Note. ... It is very important to make sure your file .Renviron

ends with a line break! Also, you need to restart R or Rstudio before this takes effect. Read R startup for more general information.



All Articles