This post will introduce using the keyring package to hide a password.
The keyring package is a library designed to let you access your operating system’s credential store. In essence, it lets you store and retrieve passwords in your operating system, which allows you to avoid having a password in plaintext in an R script.
Storing a password
Storing a password with keyring is really straightforward. First, we just need to load the keyring package. Then we call a function called key_set_with_value. In this function, we’ll input three different parameters – service, username and password.
# load keyring package library(keyring) # Store email username with password key_set_with_value(service = "user_email", username = "[email protected]", password = "test password")
The username and password stored are just that – a username and password. The service specifies what that username / password combination is in relation to. In this way, we can set the service parameter to be whatever value we like. Above we’re just setting this parameter to be “user_email”. By this we’re specifying that the username and password for “user_email” are the username and password that we denote – “[email protected]” and “test password”, respectively.
Once this is done, you can access your stored password like this:
key_get("user_email", "[email protected]") # "test password"
Here we just need to input the service name and username. An important point to note is that setting a username / password combination with keyring means that you can retrieve that password in future R sessions even after your current R session has ended. This is because it is stored in your operating system’s credential store i.e. you only have to set your password with keyring once.
keyring can be used to store any type of password or token you’d like, whether it’s an email password, API token, etc. The main advice to live by here is to avoid printing or showing any passwords in a script. keyring does return a password in text, but as long as you don’t print or return that value in any way, it won’t be directly shown in your code. keyring also has a counterpart package available in Python (see here for more details).
That’s it for this post! If you liked this article, please follow my blog on Twitter, or check out one of the articles below! Happy coding!
The post How to hide a password in R with the keyring package appeared first on Open Source Automation.