Storing Secret Credentials
2 minute readHow to store secret credentials on your system and let your code access them.
If you’ve already set up a Telegram bot and added it to a channel, you only need 2 things to be able to write code that uses that bot:
- The BOT TOKEN - when you create a bot on Telegram you are given this
- A CHAT ID - this points to a specific chat/channel on Telegram
These bits of info are used to send messages via the Telegram API. Anybody who has them can use your bot, so you want them to be secret, meaning you won’t want to hard-code them in any scripts.
Storing bot credentials using GPG
GNU Privacy Guard is a set of popular command line tools for working with encrypted secrets. We’ll use this to manage our Telegram IDs/keys.
First, make sure all the dependencies are installed
# Some distros might use gnupg, some have gnupg2
# some have both
sudo apk add pass gnupg gnupg2 pinentry-tty
Set up your user ready for key storage
Run the following commands and choose your options:
- The default options are usually fine, but check out
man pass
to learn more - Use any email address you want, it doesn’t have to be real, it will be used as an ID to work with your keystore
Keep a note of whatever address you used
gpg2 --full-generate-key
pass init <YOUR_EMAIL>
Store your secrets
Use pass insert
and give it an argument which you’ll use like a label for your secrets so you can edit/delete/retrieve them. You can organise them by using slashes so you can create something like a path or namespace for related secrets.
You will be prompted to enter the secret you want to store, then again to confirm it.
# I want to store a couple of IDs related to a Telegram bot,
# so start both with the same `telegrambot/` string
pass insert telegrambot/bottoken
pass insert telegrambot/chatid
Retrieve your secrets
pass telegrambot/bottoken
# Output eg > t3l3GRAMbotIDiJustEnT3red
pass telegrambot/chatid
# Output eg > teleGR4MchatIDiJustEnT3red
# So eg to set environment variables
# !WARNING ANYONE WHO CAN READ YOUR VARIABLES
# WILL BE ABLE TO READ THE SECRET!
export TELEGRAM_BOT_ID=$(pass telegrambot/bottoken)
To let go of your cached password
After you enter your password GPG hangs on to it for a while, which can make testing difficult while you are getting things set up. If you enter the command below it will be cleaned up and you’ll be prompted to enter your password again.
gpg-connect-agent reloadagent /bye