如何从.pem 格式的证书中保存公钥

我使用下面的 openssl 命令将公钥存储到一个. pem 文件中。

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

但是当我尝试使用这个命令时,它会将整个证书信息存储在 mypubkey.pem 文件中。

我已经看到,我可以保存我的公钥使用

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

但它抛出了一个错误。我不能使用“ >”操作符。

339068 次浏览

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-----

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.

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