1
- from ecdsa import VerifyingKey , BadSignatureError
2
- from ecdsa .util import sigdecode_der
1
+ from cryptography .exceptions import InvalidSignature
2
+ from cryptography .hazmat .primitives import hashes
3
+ from cryptography .hazmat .primitives .asymmetric import ec
4
+ from cryptography .hazmat .primitives .serialization import load_pem_public_key
3
5
import base64
4
- import hashlib
5
6
from .eventwebhook_header import EventWebhookHeader
6
7
7
8
class EventWebhook :
@@ -20,15 +21,15 @@ def __init__(self, public_key=None):
20
21
21
22
def convert_public_key_to_ecdsa (self , public_key ):
22
23
"""
23
- Convert the public key string to a VerifyingKey object.
24
+ Convert the public key string to an EllipticCurvePublicKey object.
24
25
25
26
:param public_key: verification key under Mail Settings
26
27
:type public_key string
27
- :return: VerifyingKey object using the ECDSA algorithm
28
- :rtype VerifyingKey
28
+ :return: An EllipticCurvePublicKey object using the ECDSA algorithm
29
+ :rtype cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey
29
30
"""
30
31
pem_key = "-----BEGIN PUBLIC KEY-----\n " + public_key + "\n -----END PUBLIC KEY-----"
31
- return VerifyingKey . from_pem (pem_key )
32
+ return load_pem_public_key (pem_key . encode ( "utf-8" ) )
32
33
33
34
def verify_signature (self , payload , signature , timestamp , public_key = None ):
34
35
"""
@@ -41,15 +42,15 @@ def verify_signature(self, payload, signature, timestamp, public_key=None):
41
42
:param timestamp: value obtained from the 'X-Twilio-Email-Event-Webhook-Timestamp' header
42
43
:type timestamp: string
43
44
:param public_key: elliptic curve public key
44
- :type public_key: VerifyingKey
45
+ :type public_key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey
45
46
:return: true or false if signature is valid
46
47
"""
47
48
timestamped_payload = (timestamp + payload ).encode ('utf-8' )
48
49
decoded_signature = base64 .b64decode (signature )
49
50
50
51
key = public_key or self .public_key
51
52
try :
52
- key .verify (decoded_signature , timestamped_payload , hashfunc = hashlib . sha256 , sigdecode = sigdecode_der )
53
+ key .verify (decoded_signature , timestamped_payload , ec . ECDSA ( hashes . SHA256 ()) )
53
54
return True
54
- except BadSignatureError :
55
+ except InvalidSignature :
55
56
return False
0 commit comments