This repository was archived by the owner on Apr 13, 2024. It is now read-only.
forked from ahknight/httpsig
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsign_algorithms.py
More file actions
61 lines (44 loc) · 1.74 KB
/
sign_algorithms.py
File metadata and controls
61 lines (44 loc) · 1.74 KB
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
import base64
import six
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_PSS
from httpsig.utils import HttpSigException, HASHES
from abc import ABCMeta, abstractmethod
DEFAULT_HASH_ALGORITHM = "sha512"
class SignAlgorithm(object):
__metaclass__ = ABCMeta
@abstractmethod
def sign(self, private, data):
raise NotImplementedError()
@abstractmethod
def verify(self, public, data, signature):
raise NotImplementedError()
class PSS(SignAlgorithm):
def __init__(self, hash_algorithm=DEFAULT_HASH_ALGORITHM, salt_length=None, mgfunc=None):
if hash_algorithm not in HASHES:
raise HttpSigException("Unsupported hash algorithm")
if hash_algorithm != DEFAULT_HASH_ALGORITHM:
raise HttpSigException(
"Hash algorithm: {} is deprecated. Please use: {}".format(hash_algorithm, DEFAULT_HASH_ALGORITHM))
self.hash_algorithm = HASHES[hash_algorithm]
self.salt_length = salt_length
self.mgfunc = mgfunc
def _create_pss(self, key):
try:
rsa_key = RSA.importKey(key)
pss = PKCS1_PSS.new(rsa_key, saltLen=self.salt_length, mgfunc=self.mgfunc)
except ValueError:
raise HttpSigException("Invalid key.")
return pss
def sign(self, private_key, data):
pss = self._create_pss(private_key)
if isinstance(data, six.string_types):
data = data.encode("ascii")
h = self.hash_algorithm.new()
h.update(data)
return pss.sign(h)
def verify(self, public_key, data, signature):
pss = self._create_pss(public_key)
h = self.hash_algorithm.new()
h.update(data)
return pss.verify(h, base64.b64decode(signature))