FWIW, this BASH script will take a PEM- or DER-format X.509 certificate or OpenSSL public key file (also PEM format) as the first argument and disgorge an OpenSSH RSA public key. This expands upon @mkalkov's answer above. Requirements are cat
, grep
, tr
, dd
, xxd
, sed
, xargs
, file
, uuidgen
, base64
, openssl
(1.0+), and of course bash
. All except openssl
(contains base64
) are pretty much guaranteed to be part of the base install on any modern Linux system, except maybe xxd
(which Fedora shows in the vim-common
package). If anyone wants to clean it up and make it nicer, caveat lector.
#!/bin/bash
#
# Extract a valid SSH format public key from an X509 public certificate.
#
# Variables:
pubFile=$1
fileType="no"
pkEightTypeFile="$pubFile"
tmpFile="/tmp/`uuidgen`-pkEightTypeFile.pk8"
# See if a file was passed:
[ ! -f "$pubFile" ] && echo "Error, bad or no input file $pubFile." && exit 1
# If it is a PEM format X.509 public cert, set $fileType appropriately:
pemCertType="X$(file $pubFile | grep 'PEM certificate')"
[ "$pemCertType" != "X" ] && fileType="PEM"
# If it is an OpenSSL PEM-format PKCS#8-style public key, set $fileType appropriately:
pkEightType="X$(grep -e '-BEGIN PUBLIC KEY-' $pubFile)"
[ "$pkEightType" != "X" ] && fileType="PKCS"
# If this is a file we can't recognise, try to decode a (binary) DER-format X.509 cert:
if [ "$fileType" = "no" ]; then
openssl x509 -in $pubFile -inform DER -noout
derResult=$(echo $?)
[ "$derResult" = "0" ] && fileType="DER"
fi
# Exit if not detected as a file we can use:
[ "$fileType" = "no" ] && echo "Error, input file not of type X.509 public certificate or OpenSSL PKCS#8-style public key (not encrypted)." && exit 1
# Convert the X.509 public cert to an OpenSSL PEM-format PKCS#8-style public key:
if [ "$fileType" = "PEM" -o "$fileType" = "DER" ]; then
openssl x509 -in $pubFile -inform $fileType -noout -pubkey > $tmpFile
pkEightTypeFile="$tmpFile"
fi
# Build the string:
# Front matter:
frontString="$(echo -en 'ssh-rsa ')"
# Encoded modulus and exponent, with appropriate pointers:
encodedModulus="$(cat $pkEightTypeFile | grep -v -e "----" | tr -d '\n' | base64 -d | dd bs=1 skip=32 count=257 status=none | xxd -p -c257 | sed s/^/00000007\ 7373682d727361\ 00000003\ 010001\ 00000101\ / | xxd -p -r | base64 -w0 )"
# Add a comment string based on the filename, just to be nice:
commentString=" $(echo $pubFile | xargs basename | sed -e 's/\.crt\|\.cer\|\.pem\|\.pk8\|\.der//')"
# Give the user a string:
echo $frontString $encodedModulus $commentString
# cleanup:
rm -f $tmpFile