Skip to content

Instantly share code, notes, and snippets.

@kepocnhh
Last active October 14, 2023 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kepocnhh/55d4c5efb8e2e8d49cd3b613c647c7e2 to your computer and use it in GitHub Desktop.
Save kepocnhh/55d4c5efb8e2e8d49cd3b613c647c7e2 to your computer and use it in GitHub Desktop.
OS X security sample to keychain.
KEYCHAIN='keychain_baz'
# https://www.unix.com/man-page/osx/1/security/
security delete-keychain "$KEYCHAIN"
security create-keychain -P "$KEYCHAIN"
if test $? -ne 0; then
echo 'Create keychain error!'; exit 1; fi
SERVICE_NAME='service_foo'
ACCOUNT_NAME='account_bar'
PASSWORD_VALUE="pass_$(date +%s)_bar"
security delete-generic-password -s "$SERVICE_NAME" -a "$ACCOUNT_NAME" "$KEYCHAIN" &> /dev/null
# Add a generic password item to the default keychain.
security add-generic-password -s "$SERVICE_NAME" -a "$ACCOUNT_NAME" -w "$PASSWORD_VALUE" -T '' "$KEYCHAIN"
if test $? -ne 0; then
echo 'Add password error!'; exit 1; fi
# Find a generic password item and display the password(only) for the item found.
PASSWORD_ACTUAL=$(security find-generic-password -s "$SERVICE_NAME" -a "$ACCOUNT_NAME" -w "$KEYCHAIN")
if test $? -ne 0; then
echo 'Find password error!'; exit 1; fi
if test "$PASSWORD_ACTUAL" != "$PASSWORD_VALUE"; then
echo 'Password error!'; exit 1; fi
echo 'Password as expected.'
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment