Ankit
Ankit

Reputation: 1428

How to save public key from a certificate in .pem format

I am using the below openssl command for storing my public key into a .pem file.

openssl> x509 -in E:/mycert.pem -pubkey  -out E:/mypubkey.pem

But when i try to use this command, it is storing the whole certificate info in the mypubkey.pem file.

I have seen that i can save my public key using

openssl> x509 -pubkey -noout -in cert.pem > pubkey.pem

But it is throwing an error. I can't use ">" operator.

Upvotes: 119

Views: 437543

Answers (3)

John Hanley
John Hanley

Reputation: 81462

I am not sure why the other answers have such high upvotes. They do not solve the two problems presented in the question. A key point to the problem is the openssl command interpreter is being used and not the shell prompt.

Problem #1 - the certificate is written with the public key.

I am using the below openssl command for storing my public key into a .pem file.

openssl> x509 -in E:/mycert.pem -pubkey -out E:/mypubkey.pem But when i try to use this command, it is storing the whole certificate info in the mypubkey.pem file.

The solution is to add the command argument -noout.

Problem #2 - ">" operator is not supported:

openssl> x509 -pubkey -noout -in cert.pem > pubkey.pem

But it is throwing an error. I can't use ">" operator.

The solution is to add the -out <filename> command parameter.

Solution:

openssl> x509 -pubkey -in cert.pem -noout -out pubkey.pem

Upvotes: 6

Alex Punnen
Alex Punnen

Reputation: 6254

if it is a RSA key

openssl rsa  -pubout -in my_rsa_key.pem

if you need it in a format for openssh , please see Use RSA private key to generate public key?

Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.

Upvotes: 16

gtrig
gtrig

Reputation: 12978

There are a couple ways to do this.

First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:

E:\> openssl x509 -pubkey -noout -in cert.pem  > pubkey.pem

If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.

openssl> x509 -pubkey -noout -in cert.pem

Output will look something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----

Upvotes: 269

Related Questions