Here is how you can block commits using git pre-commit hook.
In your git repo, go to .git/hooks and create a pre-commit script. It looks for a certain pattern in your files. In this example, my script will examine newly staged files, and grep the file content for PEM boundary. If found, the commit will be blocked with an error.
#!/usr/bin/env bash
# Check files to be committed, reject if the file contains what appears to be private key
for f in $(git diff --name-only --cached | grep .key$); do
if grep -qE '\-+BEGIN.*KEY\-+' $f ; then
echo "HOOK: Key $f is not encrypted. To unstage, run git restore --staged $f"
exit 1
fi
done
Remember to run chmod 755 pre-commit and make it executable. Otherwise the hook will be ignored.
This script will only block PEM-encoded keys. Other formats are not supported at the moment. This script will also block encrypted PEM keys.
Git hooks work on the client side. If you want to distribute the hooks to all team members, store your hooks in the git repo – say .githooks and commit it to your repo. Each client still need to run the following once to tell git where to look for hooks:
git config core.hooksPath .githooks
I wish client setting can be git-cloned.
![]()