Ssh – Why is the same private key file generating two different public key strings

private-keyrsasshssh-keygen

I have an ssh key pair that was generated to use as an access key for my GoCD CI/CD server. It was working but due to some configuration changes I made (moved the server out of container to a Linux host) I needed to reinstall the keys on the Linux host, so I did. I had already generated the pair and rather than change the public key on Bitbucket I figured it would be easier to continue using the same pair (also I have some CI/CD agents running in containers that are currently using this key pair).

So here's where my problem begins. I move my pre-generated private key (gocd) from my staging directory to the go user's homedir (/var/go/):

[ip-10-71-10-66 docker]# cp ./gocd ~go/.ssh/id_rsa
[root@ip-10-71-10-66 docker]# diff gocd ~go/.ssh/id_rsa
[root@ip-10-71-10-66 docker]#

So far so good, the id_rsa file and gocd file appear to be the same. However, when I compare the public keys…

[root@ip-10-71-10-66 docker]# ssh-keygen -y -e -f ~go/.ssh/id_rsa && ssh-keygen -y -e -f gocd

    ---- BEGIN SSH2 PUBLIC KEY ----
Comment: "2048-bit RSA, converted by root@ip-10-71-10-66 from OpenSSH"
TEXT REMOVED

GsH8pAPy3iQI54HvSZn9qNtA19pL+8r/DlFb6X4qeTyvte0iEIqAYmuSJglcf6OlTx0FxR
HK9y3iyG01zdcBdr2+O06j
---- END SSH2 PUBLIC KEY ----

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "2048-bit RSA, converted by root@ip-10-71-10-66 from OpenSSH"
TEXT REMOVED

bse2UtKDtTbN1EbUZ7XxLOeVG6j6CDokLagJ9LOxdLW0Zb4aMnm/sg1x5VcAY6rQKFEnSl
F3z68VhKCw0ZOqVBNg8SGz
---- END SSH2 PUBLIC KEY ----

Hopefully from this example you can see why I'm confused. Now the really strange thing is that the public key that comes from the id_rsa file (the first output of the last command) actually matches an earlier private key I had generated.

What is going on here? Is there some caching happening in ssh-agent that I'm not aware of? Is something else going on?

Best Answer

The answer to this question is frustratingly simple. Apparently, in the presence of an id_rsa and id_rsa.pub pair, the ssh-keygen command which evaluates the private key and outputs the associated public key will ignore the contents of the id_rsa file and assume that the associated id_rsa.pub file matches.

Removing the non-matching id_rsa.pub file from the ~go/.ssh/ directory allowed ssh-keygen to properly output the associated public key.