aboutsummaryrefslogtreecommitdiffstats
path: root/src/py/imc/auth.py
blob: 03c15dc72a3bdc4d723096a8016284f3e5a31648 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import time
import json
import binascii
import contextlib

import tornado.stack_context
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA512
from Crypto.Signature import PKCS1_v1_5

current_iden = None

class Auth:
    def __init__(self):
        global current_iden

        self._cache_hashmap = {}
        current_iden = None

    @staticmethod
    def get_current_iden():
        global current_iden

        return current_iden

    @staticmethod
    def change_current_iden(iden):
        @contextlib.contextmanager
        def context():
            global current_iden

            old_iden = current_iden
            current_iden = iden
            
            try:
                yield

            finally:
                current_iden = old_iden

        return tornado.stack_context.StackContext(context)

    def set_signkey(self,key):
        self._signer = PKCS1_v1_5.new(RSA.importKey(key))

    def set_verifykey(self,key):
        self._verifier = PKCS1_v1_5.new(RSA.importKey(key))

    def sign_iden(self,iden):
        data = json.dumps(iden)
        sign = binascii.hexlify(self._sign(bytes(data,'utf-8'))).decode('utf-8')

        return json.dumps([data,sign])

    def get_iden(self,idendesc):
        pair = json.loads(idendesc)
        data = pair[0]
        sign = pair[1]

        if self._verify(bytes(data,'utf-8'),binascii.unhexlify(sign)):
            return json.loads(data)

        else:
            return None

    def _sign(self,data):
        return self._signer.sign(SHA512.new(data))

    def _verify(self,data,sig):
        h = SHA512.new(data)
        if h in self._cache_hashmap:
            return True

        if self._verifier.verify(h,sig) == True:
            self._cache_hashmap[h] = True

            return True
        else:
            return False