Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (1.3 kB)

1 8bf3a249 Kostas Papadimitriou
import binascii
2 8bf3a249 Kostas Papadimitriou
3 8bf3a249 Kostas Papadimitriou
from synnefo.ui.userdata.asn1 import DerObject, DerSequence
4 8bf3a249 Kostas Papadimitriou
5 8bf3a249 Kostas Papadimitriou
def exportKey(keyobj, format='PEM'):
6 8bf3a249 Kostas Papadimitriou
    """Export the RSA key. A string is returned
7 8bf3a249 Kostas Papadimitriou
    with the encoded public or the private half
8 8bf3a249 Kostas Papadimitriou
    under the selected format.
9 8bf3a249 Kostas Papadimitriou

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