Skip to content

Instantly share code, notes, and snippets.

@williamcroberts
Created February 22, 2023 18:38
Show Gist options
  • Save williamcroberts/5ce44b951af00c593c9d499df7498230 to your computer and use it in GitHub Desktop.
Save williamcroberts/5ce44b951af00c593c9d499df7498230 to your computer and use it in GitHub Desktop.
Python script for converting a private key from p, n and e values to a PEM private key format
#!/usr/bin/env python3
import sys
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from tpm2_pytss.internal.crypto import _MyRSAPrivateNumbers as MyRSAPrivateNumbers
nums = {
"p" : None,
"n" : None,
"e" : 65537
}
if len(sys.argv) < 3 or len(sys.argv) > 4:
sys.exit("Expected 2 or 3 key value arguments like p=abcdef123 q=1234fde e=65537. Note e is optional and defaults to 65537")
for arg in sys.argv[1:]:
k,v = arg.split('=')
if k not in nums:
sys.exit(f'Unknown key "{k}"')
try:
base = 16 if k != "e" else 10
nums[k] = int(v, base)
except ValueError as e:
sys.exit(f'Expected key "{k}" as base: {base}')
pubnums = rsa.RSAPublicNumbers(e=nums["e"], n=nums["n"])
m = MyRSAPrivateNumbers(p=nums["p"], n=nums["n"], e=nums["e"], pubnums=pubnums)
pk = m.private_key()
pem = pk.private_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption())
sys.stdout.write(pem.decode())
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment