-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpss.py
71 lines (62 loc) · 2.13 KB
/
pss.py
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
import logging
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import utils
from ..exception import BadSignature
from ..exception import Unsupported
from . import Signer
logger = logging.getLogger(__name__)
class PSSSigner(Signer):
def __init__(self, algorithm="SHA256"):
if algorithm == "SHA256":
self.hash_algorithm = hashes.SHA256
elif algorithm == "SHA384":
self.hash_algorithm = hashes.SHA384
elif algorithm == "SHA512":
self.hash_algorithm = hashes.SHA512
else:
raise Unsupported("algorithm: {}".format(algorithm))
def sign(self, msg, key):
"""
Create a signature over a message
:param msg: The message
:param key: The key
:return: A signature
"""
hasher = hashes.Hash(self.hash_algorithm(), backend=default_backend())
hasher.update(msg)
digest = hasher.finalize()
sig = key.sign(
digest,
padding.PSS(
mgf=padding.MGF1(self.hash_algorithm()),
salt_length=padding.PSS.MAX_LENGTH,
),
utils.Prehashed(self.hash_algorithm()),
)
return sig
def verify(self, msg, signature, key):
"""
Verify a message signature
:param msg: The message
:param sig: A signature
:param key: A ec.EllipticCurvePublicKey to use for the verification.
:raises: BadSignature if the signature can't be verified.
:return: True
"""
try:
key.verify(
signature,
msg,
padding.PSS(
mgf=padding.MGF1(self.hash_algorithm()),
salt_length=padding.PSS.MAX_LENGTH,
),
self.hash_algorithm(),
)
except InvalidSignature as err:
raise BadSignature(err)
else:
return True