Skip to content

Instantly share code, notes, and snippets.

@punitsoni
Last active October 3, 2024 15:22
Show Gist options
  • Save punitsoni/e3c30d2c21eb61838d3f7296df0f7f76 to your computer and use it in GitHub Desktop.
Save punitsoni/e3c30d2c21eb61838d3f7296df0f7f76 to your computer and use it in GitHub Desktop.
gpg-encrypt-api-keys

How to use gpg to securely store your api keys

When you are using a third-party api in your application code. it usually requires you to supply some secret client information when making requests. if your code is opensource or accessible by a lot of people, putting these keys directly in code in plaintext can be a security issue.

One approach that i have seen in the wild is to use os environment variables to store the secrets and your app code can query the environment when starting up. this still requires someone to set up the environment in your server when deploying. this can also be inconvenient in a development workflow.

Why not hide in plain sight?

we can put the secret keys right there besides the code in a file called secret.json. not quite, but close enough. let's encrypt the file secret.json with good-old symmetric key cipher. basically, the secrets will be right in front of you, but you can't read them unless you have a valid password.

gpg

Lets say we have a file called secret.json in the repo. Our application reads and parses this file to get access to the secret juicy api keys.

$ cat secret.json
{
  "super_secret_api_key": "23ab44cdef"
}

Encrypt

# encrypt the file secret.json using aes256 cipher.
gpg -c --cipher-algo AES256 --no-symkey-cache secret.json

This command will ask for a passphrase, after selecting passphrase it will encrypt the file. It will create a file called secret.json.gpg, which is AES256 encrypted. You can now check-in this file in your code repo. Make sure not to upload the plaintext secret.json file in your repo.

Decrypt

When making a new workspace, you will download code with secret.json.gpg file in your repo. To run your app, you will need the plaintext secret.json file. Use following command to generate that file. You will have to provide the same passphrase that you used while encrypting the file.

gpg secret.json.gpg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment