Skip to content

Instantly share code, notes, and snippets.

@Smart123s
Last active June 30, 2024 12:29
Show Gist options
  • Save Smart123s/0fb9f1ff1111d6352ebd91d29b911cab to your computer and use it in GitHub Desktop.
Save Smart123s/0fb9f1ff1111d6352ebd91d29b911cab to your computer and use it in GitHub Desktop.
Transform a PGP private key to an OpenSSH private key
#!/usr/bin/python3
"""
Transform a PGP private key to an OpenSSH private key
Requirements:
pgpy>=0.6.0
Usage:
Install dependencies with `pip install pgpy`
Find GPG Key ID with `gpg --list-secret-keys --with-keygrip`
Export key with `gpg --armor --export-secret-keys <key-id>`
python3 pgp2ssh.py <path-to-private-key> > output.pem
Note:
The output key of this script is NOT encrypted
You should encrypt it with `ssh-keygen -p -f <path-to-ssh-key>`
References / script inspired by:
https://0xacab.org/monkeysphere/monkeypy/-/blob/master/monkeysphere/openpgp2ssh.py
"""
import sys
from getpass import getpass
from cryptography.hazmat.primitives import serialization
from pgpy import PGPKey
def key2ssh_private(key: PGPKey):
material = key._key.keymaterial.__privkey__()
return material.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.OpenSSH,
encryption_algorithm=serialization.NoEncryption(),
).decode("utf-8")
if __name__ == "__main__":
with open(sys.argv[-1], encoding="utf-8") as f:
key, _ = PGPKey.from_blob(f.read())
key_passphrase = None
if not key.is_unlocked:
print("Key is password protected.", file=sys.stderr)
key_passphrase = getpass(stream=sys.stderr)
with key.unlock(key_passphrase):
print(key2ssh_private(key))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment