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
6
5
7
6
class EventWebhook :
8
7
"""
@@ -20,14 +19,15 @@ def __init__(self, public_key=None):
20
19
21
20
def convert_public_key_to_ecdsa (self , public_key ):
22
21
"""
23
- Convert the public key string to a ECPublicKey .
22
+ Convert the public key string to a VerifyingKey object .
24
23
25
24
:param public_key: verification key under Mail Settings
26
25
: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
29
28
"""
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 )
31
31
32
32
def verify_signature (self , payload , signature , timestamp , public_key = None ):
33
33
"""
@@ -40,11 +40,15 @@ def verify_signature(self, payload, signature, timestamp, public_key=None):
40
40
:param timestamp: value obtained from the 'X-Twilio-Email-Event-Webhook-Timestamp' header
41
41
:type timestamp: string
42
42
:param public_key: elliptic curve public key
43
- :type public_key: PublicKey
43
+ :type public_key: VerifyingKey
44
44
:return: true or false if signature is valid
45
45
"""
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 )
48
48
49
49
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