1- from ellipticcurve .ecdsa import Ecdsa
2- from ellipticcurve .publicKey import PublicKey
3- from ellipticcurve .signature import Signature
4-
5- from .eventwebhook_header import EventWebhookHeader
1+ from ecdsa import VerifyingKey , BadSignatureError
2+ from ecdsa .util import sigdecode_der
3+ import base64
4+ import hashlib
65
76class EventWebhook :
87 """
@@ -20,14 +19,15 @@ def __init__(self, public_key=None):
2019
2120 def convert_public_key_to_ecdsa (self , public_key ):
2221 """
23- Convert the public key string to a ECPublicKey .
22+ Convert the public key string to a VerifyingKey object .
2423
2524 :param public_key: verification key under Mail Settings
2625 :type public_key string
27- :return: public key using the ECDSA algorithm
28- :rtype PublicKey
26+ :return: VerifyingKey object using the ECDSA algorithm
27+ :rtype VerifyingKey
2928 """
30- return PublicKey .fromPem ('\n -----BEGIN PUBLIC KEY-----\n ' + public_key + '\n -----END PUBLIC KEY-----\n ' )
29+ pem_key = "-----BEGIN PUBLIC KEY-----\n " + public_key + "\n -----END PUBLIC KEY-----"
30+ return VerifyingKey .from_pem (pem_key )
3131
3232 def verify_signature (self , payload , signature , timestamp , public_key = None ):
3333 """
@@ -40,11 +40,15 @@ def verify_signature(self, payload, signature, timestamp, public_key=None):
4040 :param timestamp: value obtained from the 'X-Twilio-Email-Event-Webhook-Timestamp' header
4141 :type timestamp: string
4242 :param public_key: elliptic curve public key
43- :type public_key: PublicKey
43+ :type public_key: VerifyingKey
4444 :return: true or false if signature is valid
4545 """
46- timestamped_payload = timestamp + payload
47- decoded_signature = Signature . fromBase64 (signature )
46+ timestamped_payload = ( timestamp + payload ). encode ( 'utf-8' )
47+ decoded_signature = base64 . b64decode (signature )
4848
4949 key = public_key or self .public_key
50- return Ecdsa .verify (timestamped_payload , decoded_signature , key )
50+ try :
51+ key .verify (decoded_signature , timestamped_payload , hashfunc = hashlib .sha256 , sigdecode = sigdecode_der )
52+ return True
53+ except BadSignatureError :
54+ return False
0 commit comments