Voy a actualizar esto con más detalles y un decodificador cuando me libere en unas pocas horas.
def bitlength_and_integer_in_bytes(n):
bytes_length = n.bit_length()//8+1
return bytes_length.to_bytes(4, "big")+n.to_bytes(bytes_length, "big")
def gen_id_rsa_pub(n,e):
return b"ssh-rsa "+base64.b64encode(b"\x00\x00\x00\x07ssh-rsa"+bitlength_and_integer_in_bytes(e)+bitlength_and_integer_in_bytes(n))+b" RSA key description"
open("id_rsa.pub", "bw").write(gen_id_rsa_pub(n,e))
##import base64
##from pyasn1.codec.der import decoder
##s = "\n".join(open(".ssh/id_rsa").readlines()[1:-1])
##d = decoder.decode(base64.b64decode(s))
import base64
from pyasn1.codec.der import encoder
from pyasn1.type.univ import *
#below from http://stackoverflow.com/a/9758173/443348
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
#got example values from https://en.wikipedia.org/wiki/RSA_(algorithm)#A_working_example
p = 61
q = 53
n = p*q #3233
totient_n = (p-1)*(q-1) # 3120
e = 17 # Should be coprime to 3120
d = modinv(e, totient_n) #2753
s = Sequence()
def setvalues(sequence, values):
for index, value in enumerate(values):
sequence.setComponentByPosition(index, value)
q = n/p
setvalues(s, map(Integer, (0, n, e, d, p, q, d%(p-1), d%(q-1), modinv(q,p))))
id_rsa = b"-----BEGIN RSA PRIVATE KEY-----\n"+base64.b64encode(encoder.encode(s))+b"\n-----END RSA PRIVATE KEY-----\n"
open("id_rsa", "bw").write(id_rsa)
Por qué no http://docs.python.org/3.4/library/base64.html y/o (https://pypi.python.org/pypi/rsa http://stuvel.eu/ rsa)? – user2284570
@ J.Random alguna respuesta? – user2284570