Last active
February 22, 2025 19:29
-
-
Save fanurs/f30a568e894072e36d6d150c193756e7 to your computer and use it in GitHub Desktop.
To generate ssh key pair whose public key BASE64 encoding matches a certain substring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This script offers a fun way to generate an SSH key whose public key's BASE64 | |
# encoding would end in a certain substring you specify. The script simply | |
# keeps trying until to find one. Because the probability distribution is | |
# geometric, so in practice, it is not "that bad" if you just want to match to | |
# last two characters. | |
# Ensure script is run from ~/.ssh | |
if [[ "$(pwd)" != "$HOME/.ssh" ]]; then | |
echo "Error: This script must be run from ~/.ssh" | |
exit 1 | |
fi | |
# Check if username and machine name are both provided | |
if [ "$#" -ne 2 ]; then | |
echo "Usage: $0 <user-name> <machine-name>" | |
exit 1 | |
fi | |
USERNAME="$1" # Can be anything, no need to match the actual username | |
HOSTNAME="$2" # Can be anything, no need to match the actual hostname | |
TARGET="IU" # Ending substring that you try to match in the public key | |
TARGET_NCHARS=${#TARGET} | |
echo "Generating ed25519 keys until the public key ends in '$TARGET'..." | |
MAX_TRIALS=20000 # Upper limit to prevent infinite loop; adjust accordingly | |
COUNT=0 | |
while [ $COUNT -lt $MAX_TRIALS ]; do | |
# Progress bar | |
if (( COUNT % 10 == 0 )); then | |
printf "\rAttempts: %d" "$COUNT" | |
fi | |
# Remove any current keys of the same names | |
rm -f ${USERNAME}-${HOSTNAME}-ed25519* | |
# Create SSH key candidate quietly | |
ssh-keygen -q -t ed25519 -C "${USERNAME}@${HOSTNAME}" -f "${USERNAME}-${HOSTNAME}-ed25519" -N "" | |
# Extract last two characters of the base64 public key | |
BASE64_KEY=$(awk '{print $2}' "${USERNAME}-${HOSTNAME}-ed25519.pub") | |
LAST_TWO=$(echo -n "$BASE64_KEY" | tail -c 2) | |
if [[ "$LAST_TWO" == "$TARGET" ]]; then | |
echo "" | |
echo "Success! Found a matching key after $COUNT attempts." | |
exit 0 | |
fi | |
((COUNT++)) | |
done | |
echo "" | |
echo "Failed to generate a key with '$TARGET' in $MAX_TRIALS attempts." | |
echo "Just try again. Thanks." | |
exit 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment