Search code examples
bashshellencryptionshzshrc

Loading secret content in .profile when initializing bash/zsh


I want to include an environment variable with a secret Api key during shell initialization. But I do not want that environment variable to be exposed in a plain text file.

So, I was wondering if there is a built-in mechanism or script to do this.

I was thinking on a encrypted git repository using git-crypt. And when initializing (on .profile) decrypt it, source it and then encrypt it back to make unreadable to other users.


Solution

  • A couple of sh functions and using gpg made it:

    SECRETS_FILE=~/.secrets.sh
    GPG_ID=yourgpgid@mydomain.com
    profile_decrypt (){
      gpg -d ${SECRETS_FILE}.asc > ${SECRETS_FILE} # Decrypt file
      rm ${SECRETS_FILE}.asc
    }
    
    profile_encrypt () {
      gpg -ea -r ${GPG_ID} ${SECRETS_FILE} # Encrypt file using ascii output
      rm ${SECRETS_FILE}
    }
    profile_decrypt
    source $SECRETS_FILE
    profile_encrypt
    

    Where ~/.secrets.sh contains:

    export API_KEY=<SECRET API KEY>
    

    Including this functions on .profile decrypts, exports variables and encrypts them back everytime the terminal is loaded.