Search code examples
linuxsslopensslssl-certificatepki

How to extract public key and private key from .key file?


I have a file server.key generated by openssl genrsa -out server.key 2048, which contains both public and private key.

I searched and fount that I can get public key by openssl rsa -in server.key -pubout -out key.pub

How can I get private key from server.key?


Solution

  • the .key file corresponds to the private key itself. If you open your .key file in a text editor you would see that they have -----BEGIN RSA PRIVATE KEY----- as the prefix and -----END RSA PRIVATE KEY----- as the suffix. See below for example:

    -----BEGIN RSA PRIVATE KEY-----
    MIIEogIBAAKCAQEAr/8dgslQvZLyDnPnBVJbihYjhPw6hUuCH1tKop5RitQuob4r
    i4ixAhNyrjB3dmO39o8cG56/kb1MHszt256476LGW20Q3s902Nckc4yYqaA02XuE
    ...
    ...
    rG8D6oIoim5XwtS68fHJpfvciuuE/TQcnS4Ek04jkReP1EXv2hp4CTAZ4l5Tm4HJ
    oDmCiSOsQE/YjiyQp5eGFadqosOZZFU7k+8ipKIstr71kEQRiLE=
    -----END RSA PRIVATE KEY-----
    

    The command that you shared generates a public key pair from the existing private key.

    openssl rsa -in server.key -pubout -out key.pub

    HTH