When working with asymmetric keys, it's common to accumulate multiple private and public key pairs. Accidentally mismatching them can cause frustrating authentication failures. To avoid this, you should confirm that a given private key corresponds to the expected public key. This tutorial explains how to check if private key matches public key using ssh-keygen.
Suppose we have the following private key (id_rsa
) and public key (id_rsa.pub
):
-----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-----
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDFHi1gv5z+7K7I/ziOpM6FAjAPQwUtfc+0uR6Cw9PVwR/pgtq0Y03MzHX2vf+oxDW2464S3WbkDPK+VvQ+ofmGjmdeeaMPxLwn7alxMbUCC/jvpeCw5YtJ7mzUaooF6R/GCK8jeLIJSMd4P03UvwxAdmixmbHyGXagzZ9y1q5SwQ== root@4a91a6bfd646
Use the following command to confirm that the private key is paired with the public key:
diff <(ssh-keygen -y -f id_rsa | cut -d' ' -f 2) <(cut -d' ' -f 2 id_rsa.pub)
- If there is no output, the keys match.
- If differences are shown, the private and public keys are not a pair.
Explanation:
ssh-keygen -y -f id_rsa | cut -d' ' -f 2
- converts the private key into its corresponding public key format and prints only the Base64-encoded key portion (ignoring the type and comment).cut -d' ' -f 2 id_rsa.pub
- extracts the Base64 part of the saved public key.diff
- checks for differences between the two extracted values.
Leave a Comment
Cancel reply