Skip to content

Instantly share code, notes, and snippets.

@stevenewey
Created April 6, 2016 18:09
Show Gist options
  • Save stevenewey/b56b6d13a78ce2810867ed89ca6d08ee to your computer and use it in GitHub Desktop.
Save stevenewey/b56b6d13a78ce2810867ed89ca6d08ee to your computer and use it in GitHub Desktop.
Serialize Python 3 cryptography RSA public key to OpenSSH format
import binascii
import struct
from cryptography import utils
from cryptography.hazmat.primitives.asymmetric import rsa
def ssh_public_key(keypair: rsa.RSAPrivateKeyWithSerialization) -> str:
eb = utils.int_to_bytes(keypair.public_key().public_numbers().e)
nb = utils.int_to_bytes(keypair.public_key().public_numbers().n)
if eb[0] & 0x80: eb = bytes([0x00]) + eb
if nb[0] & 0x80: nb = bytes([0x00]) + nb
keyparts = [b'ssh-rsa', eb, nb]
keystring = b''.join([struct.pack(">I", len(kp)) + kp for kp in keyparts])
return str(b'ssh-rsa ' + binascii.b2a_base64(keystring)[:-1], encoding='utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment