Encrypting .env Files with GPG for Safe Commits
Summary: A guide to encrypting .env files with GPG to prevent secret exposure when you need to commit them to Git. Covers everything from .gitignore handling to gpg encrypt/decrypt commands and setting a default recipient, so you can start operating a secure repository.

Overview
There are cases where you need to commit application configuration files or environment variable definition files to Git.
Sometimes a development environment password gets committed carelessly, or a production environment password ends up included in a commit.
This post summarizes how to encrypt and hide the contents of a file that contains secret information when committing it.
There are several common approaches, but here we’ll cover only the approach of using GPG directly.
Commonly recommended methods for encrypting file contents
- gpg
- age
- git-crypt (Git filter-based encryption)
- sops (+age)
Why GPG?
Many people already use GPG for signing GitHub commits/tags.
The advantage is that you can extend the same key to file encryption as well.
For installation/key generation, refer to Signing Commits with GPG in Git.
If your only goal is file encryption, age may feel simpler.
Encrypting/Decrypting Files
Prerequisite: You must have a GPG key already issued before proceeding with the steps below.
Things to check first (important)
- If a file has already been included in a past commit, adding it to
.gitignorestill leaves the secret value viewable in past commits. - To remove it completely, you must revoke/reissue the secret value and rewrite the git commits.
git filter-repoor BFG Repo-Cleaner- force push (if needed)
Exclude the original file from Git
1# Add .env to .gitignore
2echo ".env" >> .gitignore
3
4# If it's already being tracked, remove it from the index
5# (keep the local file, only remove it from Git tracking)
6git rm --cached .env
Encrypting the file
Notes
gpg --encryptdoesn’t update an existing file in place — it creates a new output file each time.- If the file already exists, it will ask whether to overwrite it. Use the
--yesoption to auto-confirm.
Example .env file:
Create an encrypted .env file from a .env file that contains secrets.
1# Encrypt with the specified recipient's key to create .env.enc
2gpg --encrypt -r [email protected] --output .env.enc .env
3
4# If you need to automate overwriting as well
5# gpg --yes --encrypt -r [email protected] --output .env.enc .env
Decrypting the file
Create a .env file containing secrets from the .env.enc file.
1gpg --decrypt .env.enc > .env
Miscellaneous
Setting a default recipient
- Useful when specifying
-revery time is cumbersome. default-recipient: used by default when the-roption is not givenencrypt-to: always included regardless of the-roption- Configuration file:
~/.gnupg/gpg.conf
1# Default key
2default-key {pub uuid}
3
4# Default recipient
5default-recipient {pub uuid}
6
7# Recipient to always include (only if needed)
8#encrypt-to {pub uuid}