Statistics
| Branch: | Tag: | Revision:

root / userdata / views.py @ 4264d385

History | View | Annotate | Download (2 kB)

1
from django import http
2
from django.template import RequestContext, loader
3
from django.utils import simplejson as json
4
from django.conf import settings
5

    
6
from synnefo.userdata import rest
7
from synnefo.userdata.models import PublicKeyPair
8

    
9
from synnefo.userdata import asn1
10
from Crypto.PublicKey import RSA
11
from Crypto.Util.number import inverse
12

    
13
import binascii
14
import base64
15

    
16
class PublicKeyPairResourceView(rest.UserResourceView):
17
    model = PublicKeyPair
18
    exclude_fields = ["user"]
19

    
20
class PublicKeyPairCollectionView(rest.UserCollectionView):
21
    model = PublicKeyPair
22
    exclude_fields = ["user"]
23

    
24
SSH_KEY_LENGTH = getattr(settings, 'UI_SSH_KEY_LENGTH', 1024)
25
def generate_key_pair(request):
26
    """
27
    Response to generate private/public RSA key pair
28
    """
29
    key = RSA.generate(SSH_KEY_LENGTH)
30

    
31
    # generate private content in PEM format
32
    seq = asn1.DerSequence()
33
    seq[:] = [ 0, key.n, key.e, key.d, key.p, key.q, key.d % (key.p-1), key.d % (key.q-1), inverse(key.q, key.p)]
34
    pem = asn1.b("-----BEGIN PRIVATE KEY-----\n")
35
    binaryKey = seq.encode()
36
    chunks = [ binascii.b2a_base64(binaryKey[i:i+48]) for i in range(0, len(binaryKey), 48) ]
37
    pem += asn1.b('').join(chunks)
38
    pem += asn1.b("-----END PRIVATE KEY-----\n")
39

    
40
    # generate public content
41
    seq = asn1.DerSequence()
42
    ssh_rsa = '00000007' + base64.b16encode('ssh_rsa')
43
    exponent = '%x' % (key.e, )
44
    if len(exponent) % 2:
45
        exponent = '0' + exponent
46
    ssh_rsa += '%08x' % (len(exponent) / 2, )
47
    ssh_rsa += exponent
48
    modulus = '%x' % (key.n, )
49
    if len(modulus) % 2:
50
        modulus = '0' + modulus
51
    if modulus[0] in '89abcdef':
52
        modulus = '00' + modulus
53
    ssh_rsa += '%08x' % (len(modulus) / 2, )
54
    ssh_rsa += modulus
55
    public = 'ssh-rsa %s' % (base64.b64encode(base64.b16decode(ssh_rsa.upper())),)
56

    
57
    print pem
58
    print
59
    print
60
    print public
61

    
62
    data = {'private': pem, 'public': public}
63
    return http.HttpResponse(json.dumps(data), mimetype="application/json")