Skip to content

Instantly share code, notes, and snippets.

@yitsushi
Created October 19, 2015 19:36
Show Gist options
  • Save yitsushi/2d824cec027c00f021c0 to your computer and use it in GitHub Desktop.
Save yitsushi/2d824cec027c00f021c0 to your computer and use it in GitHub Desktop.
A simple script that calculates the key length from the public key
#!/usr/bin/env bash
keyFile=$1
keyHash=`sed -e 's/^[^ ]* //' ~/.ssh/acquia_rsa.pub | sed -e 's/ .*//'`
comment=`awk '{print $3}' $keyFile`
getHexValue() {
content=$1
from=$2
length=$3
echo $keyHash | base64 -D | hexdump -n $length -s $from | sed -e 's/^[^ ]* //g' -e 's/ //g' | head -n 1
}
hexToDec() {
printf '%d' "0x$1"
}
# Get the length of the next block
nextBlockSize=$(printf '%d' "0x`getHexValue $keyHash 0 4`")
# Get the key type
keyType=`echo $keyHash | base64 -D | head -c $((4 + $nextBlockSize))`
# public exponent length
lengthOfPublicExponent=$(hexToDec `getHexValue $keyHash $(( 4 + $nextBlockSize )) 4`)
# public exponent
publicExponent=$(hexToDec `getHexValue $keyHash $(( 4 + 4 + $nextBlockSize )) $lengthOfPublicExponent`)
# modulus length in bytes
lengthOfModulus=$(hexToDec `getHexValue $keyHash $(( $lengthOfPublicExponent + 4 + 4 + $nextBlockSize )) 4`)
# sub 1 from the length of modulus (because there is an extra bit defines the sign)
# then mult with 8 to get in bits (1 byte = 8 bits)
echo "${keyFile}: ${keyType} with "$(( ($lengthOfModulus - 1) * 8 ))" bits (${comment})"
## sample output:
# /Users/yitsushi/.ssh/acquia_rsa.pub: ssh-rsa with 4096 bits (__myemail__)
@yitsushi
Copy link
Author

Useful if you want to automate your key acceptance and want to check if the key reaches the minimum key length.
For example: we want RSA with at least 4096bits

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