Show More
@@ -1,58 +1,57 b'' | |||
|
1 | 1 | import base64 |
|
2 | from ecdsa import SigningKey, VerifyingKey | |
|
2 | from ecdsa import SigningKey, VerifyingKey, BadSignatureError | |
|
3 | 3 | from django.db import models |
|
4 | 4 | |
|
5 | 5 | TYPE_ECDSA = 'ecdsa' |
|
6 | 6 | |
|
7 | 7 | APP_LABEL_BOARDS = 'boards' |
|
8 | 8 | |
|
9 | 9 | |
|
10 | 10 | class KeyPairManager(models.Manager): |
|
11 | 11 | def generate_key(self, key_type=TYPE_ECDSA, primary=False): |
|
12 | 12 | if primary and self.filter(primary=True).exists(): |
|
13 | 13 | raise Exception('There can be only one primary key') |
|
14 | 14 | |
|
15 | 15 | if key_type == TYPE_ECDSA: |
|
16 | 16 | private = SigningKey.generate() |
|
17 | 17 | public = private.get_verifying_key() |
|
18 | 18 | |
|
19 | 19 | private_key_str = private.to_pem().decode() |
|
20 | 20 | public_key_str = public.to_pem().decode() |
|
21 | 21 | |
|
22 | 22 | return self.create(public_key=public_key_str, |
|
23 | 23 | private_key=private_key_str, |
|
24 | 24 | key_type=TYPE_ECDSA, primary=primary) |
|
25 | 25 | else: |
|
26 | 26 | raise Exception('Key type not supported') |
|
27 | 27 | |
|
28 | 28 | def verify(self, public_key_str, string, signature, key_type=TYPE_ECDSA): |
|
29 | 29 | if key_type == TYPE_ECDSA: |
|
30 | 30 | public = VerifyingKey.from_pem(public_key_str) |
|
31 | 31 | signature_byte = base64.b64decode(signature) |
|
32 | 32 | try: |
|
33 | return public.verify(signature_byte, | |
|
34 | string.encode()) | |
|
33 | return public.verify(signature_byte, string.encode()) | |
|
35 | 34 | except BadSignatureError: |
|
36 | 35 | return False |
|
37 | 36 | else: |
|
38 | 37 | raise Exception('Key type not supported') |
|
39 | 38 | |
|
40 | 39 | |
|
41 | 40 | class KeyPair(models.Model): |
|
42 | 41 | class Meta: |
|
43 | 42 | app_label = APP_LABEL_BOARDS |
|
44 | 43 | |
|
45 | 44 | objects = KeyPairManager() |
|
46 | 45 | |
|
47 | 46 | public_key = models.TextField() |
|
48 | 47 | private_key = models.TextField() |
|
49 | 48 | key_type = models.TextField() |
|
50 | 49 | primary = models.BooleanField(default=False) |
|
51 | 50 | |
|
52 | 51 | def __str__(self): |
|
53 | 52 | return '%s: %s' % (self.key_type, self.public_key) |
|
54 | 53 | |
|
55 | 54 | def sign(self, string): |
|
56 | 55 | private = SigningKey.from_pem(self.private_key) |
|
57 | 56 | signature_byte = private.sign(string.encode()) |
|
58 | 57 | return base64.b64encode(signature_byte) |
General Comments 0
You need to be logged in to leave comments.
Login now