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
5- from .eventwebhook_header import EventWebhookHeader
66
77class EventWebhook :
88 """
@@ -20,15 +20,15 @@ def __init__(self, public_key=None):
2020
2121 def convert_public_key_to_ecdsa (self , public_key ):
2222 """
23- Convert the public key string to a VerifyingKey object.
23+ Convert the public key string to a EllipticCurvePublicKey object.
2424
2525 :param public_key: verification key under Mail Settings
2626 :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
2929 """
3030 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" ) )
3232
3333 def verify_signature (self , payload , signature , timestamp , public_key = None ):
3434 """
@@ -41,15 +41,15 @@ def verify_signature(self, payload, signature, timestamp, public_key=None):
4141 :param timestamp: value obtained from the 'X-Twilio-Email-Event-Webhook-Timestamp' header
4242 :type timestamp: string
4343 :param public_key: elliptic curve public key
44- :type public_key: VerifyingKey
44+ :type public_key: EllipticCurvePublicKey
4545 :return: true or false if signature is valid
4646 """
4747 timestamped_payload = (timestamp + payload ).encode ('utf-8' )
4848 decoded_signature = base64 .b64decode (signature )
4949
5050 key = public_key or self .public_key
5151 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 ()) )
5353 return True
54- except BadSignatureError :
54+ except InvalidSignature :
5555 return False
0 commit comments