R tip: Keep passwords and tokens secure with the keyring package

InfoWorld | Nov 15, 2018

Learn how to store credentials in an encrypted, secure keyring within R

Similar
Hi. I’m Sharon Machlis at IDG Communications, here with Do More With R: Keep your passwords and tokens secure with keyring.
As a former security reporter, it makes me a little queasy to store a password or token in plain text. And that’s basically what happens when you store a password or token string in an R environment variable.
The good news is that if you use R environment variables, they don’t show up in your environment tab. And, if you share your code with someone or post the code on GitHub, you won’t reveal your credentials by mistake.
Here’s an example. I stored a (fake) Google client ID and secret in my R environment. If I use them with the googleAuthR package, they don’t show up in my Environment tab when I set my options.
The bad news is that they’re stored in a plain text file, dot Renviron. We can see that if I open the file with usethis::edit_renviron().
See, there they are.
A better idea is using the keyring package.
Install it from CRAN with the usual install dot packages, then load it.
You can store a value in the keyring from R with the key underscore set function. See what happens when I run that to set MY FAKE CLIENT ID:
I can set the value once interactively, and I never have to type the value in clear text.
Same for MY FAKE SECRET
Now the best way to use those values is as an argument within a function, so the actual values never show up in your environment tab or history. I can access the values with keyring’s key underscore get function.
You can see the value has been set if I run options (which I’d never do in a real session).
Keep in mind this still isn’t super secure. It’s a big improvement that your credentials are stored in an encrypted keyring. But anyone who can access your machine and knows about the keyring package can still get to your credentials. Keyring underscore list will show all the available entries in the keyring.
To add a layer of security, you can create a keyring that’s password-protected within R. Do that with keyring underscore create.
You’ll be asked for a password
You can unlock the keyring at the start of your session with keyring underscore unlock
Now you can set a value for a new token, specifying the new keyring.
And you can a value the same way as before, but specifying the keyring
You can lock the keyring at the end of your script with keyring underscore lock
Now if you – or anyone else – run key_get, you (or they) will be asked for the keyring password.
And, you’ve got some more security for your passwords and tokens in R.
That’s it for this episode, thanks for watching! For more R tips, head to the Do More With R page at https go dot infoworld dot com slash more with R, all lowercase except for the R. You can also find the Do More With R playlist on YouTube. Hope to see you next episode!