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