Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / userdata / util.py @ 5facd191

History | View | Annotate | Download (1.3 kB)

1
import binascii
2

    
3
from synnefo.ui.userdata.asn1 import DerObject, DerSequence
4

    
5
def exportKey(keyobj, format='PEM'):
6
    """Export the RSA key. A string is returned
7
    with the encoded public or the private half
8
    under the selected format.
9

10
    format: 'DER' (PKCS#1) or 'PEM' (RFC1421)
11
    """
12
    der = DerSequence()
13
    if keyobj.has_private():
14
        keyType = "RSA PRIVATE"
15
        der[:] = [ 0, keyobj.n, keyobj.e, keyobj.d, keyobj.p, keyobj.q,
16
        keyobj.d % (keyobj.p-1), keyobj.d % (keyobj.q-1),
17
        keyobj.u ]
18
    else:
19
        keyType = "PUBLIC"
20
        der.append('\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00')
21
        bitmap = DerObject('BIT STRING')
22
        derPK = DerSequence()
23
        derPK[:] = [ keyobj.n, keyobj.e ]
24
        bitmap.payload = '\x00' + derPK.encode()
25
        der.append(bitmap.encode())
26
    if format=='DER':
27
        return der.encode()
28
    if format=='PEM':
29
        pem = "-----BEGIN %s KEY-----\n" % keyType
30
        binaryKey = der.encode()
31
        # Each BASE64 line can take up to 64 characters (=48 bytes of data)
32
        chunks = [ binascii.b2a_base64(binaryKey[i:i+48]) for i in range(0, len(binaryKey), 48) ]
33
        pem += ''.join(chunks)
34
        pem += "-----END %s KEY-----" % keyType
35
        return pem
36
    return ValueError("")