Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gargolito/46b4031a4a2659009add0a96b2dddde6 to your computer and use it in GitHub Desktop.
Save gargolito/46b4031a4a2659009add0a96b2dddde6 to your computer and use it in GitHub Desktop.
Programmaticaly store and retrieve secrets/password in MacOS

MacOS stores credentials and SSL/TLS certificates in the login keychain which you can manage via Keychain Access. You can access the keychain data programatically with the builtin cli security command, and also with a pip instalable python module named keyring that also provides a cli command.

When retrieving a password with any of these tools, you will be prompted to allow access to the secret and prompted your login password. There's an option Allow and Always allow. Use the one with which you're comfortable. The default is Allow, if you hit enter, you will be prompted to enter your password every time you need it.

MacOS security (Keychain Access cli)

MacOS already stores most of your passwords in the Keychain. You can see and store passwords in Keychain Access gui, but the cli let's you leverage the Keychain to store and retrieve existing passwords. Wgen using the cli, you may need to unlock your keychain, so run:

security unlock-keychain ${HOME}/Library/Keychains/login.keychain-db

  1. security find-generic-password -ws name_of_secret

name_of_secret in Keychain Access this is the string in the Name column and the Name field when you open/double click on the name.

MacOS

  1. pip install keyring
  2. keyring get name_of_secret *account

Python

import keyring
passwd = keyring.get_password("name_of_secret", "*account")

* in Keychain Access you Account can be retrieved by opening the secret you want to use.

Lastpass

You can also retrieve secrets from Lastpass via cli

  1. brew install lastpass-cli
  2. login to lastpass: lpass login user@name.com
  3. retrieve an existing password: lpass show --password name_of_secret
  4. more can be done, please look at the man page or docs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment