Extract Public Key From Private Key using ssh-keygen

Extract Public Key From Private Key using ssh-keygen

When you create a private key, it actually contains both the private and public components. If you happen to lose the public key but still have the private key, you can easily regenerate the public part using the ssh-keygen tool.

Here is an example of a private key in OpenSSH format saved in the id_rsa file:

-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAIEAxR4tYL+c/uyuyP84jqTOhQIwD0MFLX3PtLkegsPT1cEf6YLatGNN
zMx19r3/qMQ1tuOuEt1m5Azyvlb0PqH5ho5nXnmjD8S8J+2pcTG1Agv476XgsOWLSe5s1G
qKBekfxgivI3iyCUjHeD9N1L8MQHZosZmx8hl2oM2fctauUsEAAAII8e99LfHvfS0AAAAH
c3NoLXJzYQAAAIEAxR4tYL+c/uyuyP84jqTOhQIwD0MFLX3PtLkegsPT1cEf6YLatGNNzM
x19r3/qMQ1tuOuEt1m5Azyvlb0PqH5ho5nXnmjD8S8J+2pcTG1Agv476XgsOWLSe5s1GqK
BekfxgivI3iyCUjHeD9N1L8MQHZosZmx8hl2oM2fctauUsEAAAADAQABAAAAgDB/KDLxcb
LWkHorMMMHkTfwPdrDZna2yW9xTCxn+apRhYRyCVTwSafldfBq9oeTHpQMmDtT9YiOFvr1
cconF7iv9sQl0SvzD2ArNK38j3vrYHihpL5gj5Xf9KBd8n2+ltb4N8tTSNM3v6R6W2M7DS
tEyRDESFm1iuJjVGOPZByxAAAAQQDSsl5lEbNYVjTvQF+u9nXWWzP2zicBRqrtDiwlxdsd
gnfDa/9oemRW7oiSBYmxdmNmXmFO+tkN+PGZN+V7s9phAAAAQQD7ygfotwZYHy339i0EWk
yf67PSfVDsn9oWMvbA1n1s9HR1MPDzCThb1jvrnCoX28My575yBQY3j+bm0i3RM/ErAAAA
QQDIahXn6CKBlNwR8qDQvJEM2OczItnCdlpzJTiAcHlKHaPFLPplVOHvwThbkjR9ZRm3Re
0p8aszkBpFcqleA13DAAAAEXJvb3RANGE5MWE2YmZkNjQ2AQ==
-----END OPENSSH PRIVATE KEY-----

To obtain the public key from this file, run the following command:

ssh-keygen -y -f id_rsa > id_rsa.pub

Explanation of options:

  • -y - prints the public key corresponding to the given private key.
  • -f id_rsa - specifies the private key file to read from.
  • > id_rsa.pub - writes the extracted public key into a new file.

The result will look like this:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDFHi1gv5z+7K7I/ziOpM6FAjAPQwUtfc+0uR6Cw9PVwR/pgtq0Y03MzHX2vf+oxDW2464S3WbkDPK+VvQ+ofmGjmdeeaMPxLwn7alxMbUCC/jvpeCw5YtJ7mzUaooF6R/GCK8jeLIJSMd4P03UvwxAdmixmbHyGXagzZ9y1q5SwQ== root@4a91a6bfd646

Leave a Comment

Cancel reply

Your email address will not be published.