Securely store Passwords into the macOS Keychain

Why put cleartext passwords in scripts, when we can use the macOS Keychain to securely store this information for us.

How to have a easy way to include this into your scripts, so we can have a placeholder for the password rather then leaking this password within the script.

How to

We are going to add an PASSWORD into the macOS Keychain with the security command. For this command we are using -T to add an entry to the login keychain and add the security binary to “Always allow access by these applications:” list in the Access Control preferences.

security add-generic-password [-s service] [-a account] [-w password] -T [appPath]

-s service      Specify service name (required)
-a account      Specify account name (required)
-w password     Specify password to be added. Put at end of command to be prompted (recommended)
-T appPath      Specify an application which may access this item (multiple -T options are allowed)


security add-generic-password -s `SERVICE-NAME` -a `ACCOUNT-NAME` -w `PASSWORD` -T /usr/bin/security

Now we securely store the PASSWORD into the macOS Keychain, and allowing the security binary to access this entry. We can use the security command to fetch the PASSWORD.

security find-generic-password [-s service] -w 
-s service      Match service string
-w              Display the password(only) for the item found

We only need to provide the service name and ask for the password


security find-generic-password -s `SERVICE-NAME` -w

Now we can include this placeholder into the scripts, and fetch the PASSWORD in a secure way.

# Variables
password=$(security find-generic-password -s ${serviceName} -w)

See the man page security in terminal for more options. man security