Skip to content
shellhacks.dev
SSH and Networking

Extract a public key from a private key

Rebuild a public key from a private key file with ssh-keygen -y. The output holds the type and the key but no comment, so it differs from the .pub file.

1 min read
Summarize in AI

The private key is on disk but the .pub file is missing, and you need the public half to install on a server.

Shell
ssh-keygen -q -t ed25519 -f ./k -N '' -C [email protected]
rm k.pub
ssh-keygen -y -f ./k > k.rebuilt
cut -d' ' -f1,3 k.rebuilt
Text
ssh-ed25519 [email protected]

The public key is derived from the private one, so -y reads the private key file and prints the public key line to standard output. See the ssh-keygen manual for the option. In the OpenSSH key format used since 6.5 the comment is stored inside the private key, so it comes back too, as the output shows.

A private key in the older PEM format has no stored comment, so the rebuilt line has only two fields and you add the label by hand if you use it to tell keys apart in authorized_keys. If the key has a passphrase, -y asks for it.

Share

More snippets

SSH and Networking

Create an Ed25519 key

Create an Ed25519 key pair with ssh-keygen -t ed25519. Name the file with -f, label it with -C, and set a passphrase instead of the empty one used here.

1 min read
SSH and Networking

Show a key's fingerprint

Show the fingerprint of a key with ssh-keygen -lf. The default hash is SHA256, and -E md5 prints the older format that some web consoles still list.

1 min read
SSH and Networking

Change a key's passphrase

Change or remove the passphrase of an existing key with ssh-keygen -p. Pass -P and -N only in a throwaway demo, since they put secrets in the process list.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.