Home > Mobile >  Retrieve public SSH key from private key file using Python
Retrieve public SSH key from private key file using Python

Time:11-09

I have a private key file id_rsa (starts with -----BEGIN RSA PRIVATE KEY-----). With the tool ssh-keygen I am able to generate an SSH public key using the following command: ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

The generated file will have the following content:

ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU GPl nafzlHDTYW7hdI4yZ5ew18JH4JW9j...

I am trying to achieve the same within my Python code. The code will be executed on AWS Lambda so I want to avoid invoking os.system() to run shell commands since I don't have control over the underlying environment.

Given that I have a variable private_key, how can I extract the ssh public key from it?

CodePudding user response:

OpenSSH now has its own format for private keys (BEGIN OPENSSH PRIVATE KEY). Previously, the PKCS#1 or PKCS#8 format was used for private RSA keys. The posted private key has the PKCS#1 format (PEM encoded).

The Cryptography library supports a wide range of key formats, including PKCS#1 and the OpenSSH format. The following code allows importing a PKCS#1 formatted private key and exporting the public key in OpenSSH format:

from cryptography.hazmat.primitives import serialization

privatePkcs1Pem = b'''-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQE....QkFn5HuC2aOZjktdA==
-----END RSA PRIVATE KEY-----'''

private_key = serialization.load_pem_private_key(privatePkcs1Pem, password=None)
public_key = private_key.public_key()
public_openssh = public_key.public_bytes(encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH )

print(public_openssh.decode('utf-8')) # ssh-rsa AAAAB3NzaC1...
  • Related