Skip to content

Instantly share code, notes, and snippets.

@bhyde
Created November 20, 2009 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhyde/239244 to your computer and use it in GitHub Desktop.
Save bhyde/239244 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# With luck this illustrates 2 things r. keyczar
# 1. How to convert an RSA private key into a RSA public key.
# 2. How to convert RSA keys of either kind into their PEM
# equivaletn.
import sys
try:
import simplejson as json
except ImportError:
import json
#from Crypto.PublicKey import RSA
import keyczar
from keyczar import keys
from keyczar import keyinfo
from keyczar import util
from pyasn1.codec.der import encoder
from pyasn1.type import univ
import base64
RSA_OID = univ.ObjectIdentifier('1.2.840.113549.1.1.1')
def makeRSAPublicFromPrivate(privateRSAKey):
publicPortion = json.loads(str(privateRSAKey))['publicKey']
publicRSAKey = keys.RsaPublicKey.Read(json.dumps(publicPortion))
return publicRSAKey
def wrap_up_pem(kind, b64) :
x = ["-----BEGIN " + kind + "-----"]
for i in range(0,len(b64),64) :
x.append("\n" + b64[i:i+64])
x.append( '=' * (len(b64) % 4))
x.append("\n-----END " + kind + "-----\n")
return "".join(x)
def PublicRsaKey2PEM(params):
oid = util.ASN1Sequence(RSA_OID, univ.Null())
key = univ.Sequence()
key.setComponentByPosition(0, univ.Integer(params['n']))
key.setComponentByPosition(1, univ.Integer(params['e']))
binkey = util.BytesToBin(encoder.encode(key))
pubkey = univ.BitString("'%s'B" % binkey)
seq = util.ASN1Sequence(oid, pubkey)
return wrap_up_pem('PUBLIC KEY',
base64.standard_b64encode(encoder.encode(seq)))
def PrivateRsaKey2PEM(params):
rsa_params = ['n', 'e', 'd', 'p', 'q', 'dp', 'dq', 'invq']
key = univ.Sequence()
key.setComponentByPosition(0, univ.Integer(0)) # version
for i in range(len(rsa_params)):
key.setComponentByPosition(i+1, univ.Integer(params[rsa_params[i]]))
return wrap_up_pem('RSA PRIVATE KEY',
base64.standard_b64encode(encoder.encode(key)))
def main():
def p (x): sys.stdout.write(x)
def h2 (x): p("\n\n====" + x + "===\n")
newKey = keys.GenKey(keyinfo.RSA_PRIV,512)
h2("Private JSON")
p(str(newKey))
h2("Public JSON")
publicKey = makeRSAPublicFromPrivate(newKey)
p(str(publicKey))
h2("Private Key - PEM")
def g(x) : return util.BytesToLong(x)
def f(x) : return g(newKey.params[x])
params = {'n' : g(newKey.public_key.params['modulus']),
'e' : g(newKey.public_key.params['publicExponent']),
'd' : f('privateExponent'),
'p' : f('primeP'),
'q' : f('primeQ'),
'dp' : f('primeExponentP'),
'dq' : f('primeExponentQ'),
'invq' : f('crtCoefficient')}
p(PrivateRsaKey2PEM(params))
h2("Public Key - PEM")
params = {'n' : g(newKey.public_key.params['modulus']),
'e' : g(newKey.public_key.params['publicExponent']),}
p(PublicRsaKey2PEM(params))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment