Skip to content

Instantly share code, notes, and snippets.

@luckman212
Last active October 17, 2024 12:49
Show Gist options
  • Save luckman212/ec52e9291f27bc39c2eecee07e7a9aa7 to your computer and use it in GitHub Desktop.
Save luckman212/ec52e9291f27bc39c2eecee07e7a9aa7 to your computer and use it in GitHub Desktop.
grab Apple DEVELOPMENT_TEAM ID from Keychain
#!/usr/bin/env bash
CODESIGN_CN_STRING='Developer ID Application'
#CODESIGN_CN_STRING='Apple Development'
#requires openssl@3 from Homebrew
_openssl=$(brew --prefix openssl 2>/dev/null)/bin/openssl
[[ -x $_openssl ]] || { echo "missing openssl, try \`brew install openssl\`"; exit 1; }
#find development cert
csids=$(security find-identity -v -p codesigning | grep -E '[A-F0-9]{40}')
[[ -n $csids ]] || { echo 1>&2 "could not find codesigning identity"; exit 1; }
read -r sha1 cn _ < <(sed -En "s/^.*([A-F0-9]{40}).*$CODESIGN_CN_STRING.*\((.*)\).*$/\1 \2/p" <<<"$csids")
[[ -n $cn && -n $sha1 ]] || { echo 1>&2 "could not find valid development cert"; exit 1; }
#make temp dir
outdir=$(mktemp -d /private/tmp/teamid.XXXXXX)
[[ -n $outdir ]] || { echo "error creating temp dir"; exit 1; }
#export cert
if ! security find-certificate -a -c "$cn" -Z -p >"${outdir}/${cn}.pem"; then
echo "error exporting cert from Keychain"
exit 1
fi
#check for hash match
certhash=$(awk -v h="$sha1" '$0 ~ "^SHA-1 hash: " h {print $NF; exit}' "${outdir}/${cn}.pem")
[[ $certhash == "$sha1" ]] || { echo "hash mismatch! ($certhash vs $sha1)"; exit 1; }
#output DEVELOPMENT_TEAM
$_openssl x509 -in "${outdir}/${cn}.pem" -subject -noout |
sed -En 's/.*OU ?= ?([^,]+),.*$/\1/p'
#cleanup
rm -r "${outdir:?}"
@kkharji
Copy link

kkharji commented Mar 1, 2022

Hey @luckman212 I'm trying to reuse this script to build hammerspoon, while it creates dir okay it doesn't output anything, do I need to add echo sha1?

Also, why openssl is important here, and isn't the openssl installed locally sufficient ?

Thanks

@luckman212
Copy link
Author

@tami5 I can't remember why but no, I think the built-in openssl does not have the right options to deal with the keys in this format. I can re-test again later but for now I suggest sticking with the Homebrew version since I know that it works.

Try adding set -x at the top of the script (at line 2) and then re-running it, paste the output here or on a pastebin & I will try to help you

@kkharji
Copy link

kkharji commented Mar 1, 2022

Thanks @luckman212 ❤️ . I'm trying to build it with nix, so having openssl is the easiest part.

edit: Yes, indeed, builtin openssl broke the script.

@kkharji
Copy link

kkharji commented Mar 1, 2022

using my development cert would be impossible with nix. I need to find an alternative way

@luckman212
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment