Secure Password storage for bash scripts on MacOS

Many times the reason to create a bash script is to automate and document a work flow. Most of my work flows need some kind of password or complex secret files.

I am sure it happed to you too — you checked in your code in a public git and just to find out that you made your secrets public to every one 🙈.

Some tools like docker provide their own secure registry but what about storing everything in a place you can simple search an access?

Simple Passwords

security add-generic-password -a $USER -s name-of-the-note \
-w "PASSWORD"

when ever you need the password in your script you can access the passwort with:

mysql --user=user_name \
--
password \
$(security find-generic-password -a $USER -s name-of-a-note -w)

and a modal dialog will ask to allow access:

Complex multiline password files

user1:a609316768619f154ef58db4d847b75e
user2:f522d1d715970073a6413474ca0e0f63

There is no problem to store this files but when you try to access it, you will get this output:

$ security find-generic-password -a $USER -C note \
-s name-of-the-note -w
75736572313a61363039333136373638363139663135346566353864623464383437623735650a75736572323a6635323264316437313539373030373361363431333437346361306530663633

It looks like garbage but it is only the hexadecimal representation of the original content. The easiest way to solve this is to use the tool `xxd`:

$ security find-generic-password -a $USER -C note \
-s name-of-the-note -w | xxd -r -p -
user1:a609316768619f154ef58db4d847b75e
user2:f522d1d715970073a6413474ca0e0f63

If you try to add the same key “name-of-the-note” a second time you will receive an error:

security: SecKeychainItemCreateFromContent (<default>): The specified item already exists in the keychain.

use the option to delete the key to solve this problem:

security delete-generic-password -a $USER \
-s name-of-the-note -w

if you need to add a file “passwords.txt” use this:

security add-generic-password -a $USER -s name-of-the-note -C note \
-w "$(cat passwords.txt)"

Never try to add the content of a file by manual creating a note and using copy & paste. The result is a RTF content with font info and other garbage.

Conclusion

If you look for the manual or other solutions have a look at this links:

Fast-track professional successful in the design, development and deployment of technology strategies and policy. Experienced leading Internet and IS operations

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store