How do I get the RSA bit length with the pubkey and openssl?

ssh-keygen -lf /etc/ssh/rsa_key.pub 
2048 d1:cb:15:df:5d:44:...

2048 is the keylength


With openssl, if your private key is in the file id_rsa, then

openssl rsa -text -noout -in id_rsa

will print the private key contents, and the first line of output contains the modulus size in bits. If the key is protected by a passphrase you will have to enter that passphrase, of course.

If you only have the public key, then OpenSSL won't help directly. @Enigma shows the proper command line (with ssh-keygen -lf id_rsa.pub). You can still do that with OpenSSL the following way:

Open the public key file with a text editor. You will find something like this:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDo2xko99piegEDgZCrobfFTvXUTFDbWT
ch4IGk5mk0CelB5RKiCvDeK4yhDLcj8QNumaReuwNKGjAQwdENsIT1UjOdVvZOX2d41/p6J
gOCD1ujjwuHWBzzQvDA5rXdQgsdsrJIfNuYr/+kIIANkGPPIheb2Ar2ccIWh9giwNHDjkXT
JXTVQ5Whc0mGBU/EGdlCD6poG4EzCc0N9zk/DNSMIIZUInySaHhn2f7kmfoh5LRw7RF3c2O
5tCWIptu8u8ydIxz9q5zHxxKS+c7q4nkl9V/tVjZx8sneNZB+O79X1teq7LawiYJyLulUMi
OEoiL1YH1SE1U93bUcOWvpAQ5 [email protected]

Select the first characters of the middle blob (after ssh-rsa); this is Base64 and OpenSSL can decode that:

echo "AAAAB3NzaC1yc2EAAAADAQABAAABAQDDo2xko99piegEDgZC" | openssl base64 -d | hd

OpenSSL is picky, it will require that you input no more than 76 characters per line, and the number of characters must be a multiple of 4. The line above will print out this:

00000000  00 00 00 07 73 73 68 2d  72 73 61 00 00 00 03 01  |....ssh-rsa.....|
00000010  00 01 00 00 01 01 00 c3  a3 6c 64 a3 df 69 89 e8  |.........ld..i..|
00000020  04 0e 06 42                                       |...B|

This reads as such:

00 00 00 07             The length in bytes of the next field
73 73 68 2d 72 73 61    The key type (ASCII encoding of "ssh-rsa")
00 00 00 03             The length in bytes of the public exponent
01 00 01                The public exponent (usually 65537, as here)
00 00 01 01             The length in bytes of the modulus (here, 257)
00 c3 a3...             The modulus

So the key has type RSA, and its modulus has length 257 bytes, except that the first byte has value "00", so the real length is 256 bytes (that first byte was added so that the value is considered positive, because the internal encoding rules call for signed integers, the first bit defining the sign). 256 bytes is 2048 bits.

Tags:

Ssh

Openssl