util.py 966 Bytes
Newer Older
cloud committed
1
def keygen(length=1024):
2 3
    import os
    import base64
cloud committed
4
    from datetime import date
Dudás Ádám committed
5 6
    from Crypto.PublicKey import RSA

cloud committed
7
    key = RSA.generate(length, os.urandom)
Dudás Ádám committed
8 9 10 11
    try:
        pub = key.exportKey('OpenSSH')
        if not pub.startswith("ssh-"):
            raise ValueError(pub)
cloud committed
12
    except:
Dudás Ádám committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
        ssh_rsa = '00000007' + base64.b16encode('ssh-rsa')
        exponent = '%x' % (key.e, )
        if len(exponent) % 2:
            exponent = '0' + exponent

        ssh_rsa += '%08x' % (len(exponent) / 2, )
        ssh_rsa += exponent

        modulus = '%x' % (key.n, )
        if len(modulus) % 2:
            modulus = '0' + modulus

        if modulus[0] in '89abcdef':
            modulus = '00' + modulus

        ssh_rsa += '%08x' % (len(modulus) / 2, )
        ssh_rsa += modulus

        pub = 'ssh-rsa %s' % (
            base64.b64encode(base64.b16decode(ssh_rsa.upper())), )
cloud committed
33
    return key.exportKey(), "%s %s" % (pub, "cloud-%s" % date.today())