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
35import base64
4- import hashlib
56from .eventwebhook_header import EventWebhookHeader
67
78class EventWebhook :
@@ -20,15 +21,15 @@ def __init__(self, public_key=None):
2021
2122 def convert_public_key_to_ecdsa (self , public_key ):
2223 """
23- Convert the public key string to a VerifyingKey object.
24+ Convert the public key string to an EllipticCurvePublicKey object.
2425
2526 :param public_key: verification key under Mail Settings
2627 :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
2930 """
3031 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" ) )
3233
3334 def verify_signature (self , payload , signature , timestamp , public_key = None ):
3435 """
@@ -41,15 +42,15 @@ def verify_signature(self, payload, signature, timestamp, public_key=None):
4142 :param timestamp: value obtained from the 'X-Twilio-Email-Event-Webhook-Timestamp' header
4243 :type timestamp: string
4344 :param public_key: elliptic curve public key
44- :type public_key: VerifyingKey
45+ :type public_key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey
4546 :return: true or false if signature is valid
4647 """
4748 timestamped_payload = (timestamp + payload ).encode ('utf-8' )
4849 decoded_signature = base64 .b64decode (signature )
4950
5051 key = public_key or self .public_key
5152 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 ()) )
5354 return True
54- except BadSignatureError :
55+ except InvalidSignature :
5556 return False
0 commit comments