44from backend .config import STARTING_BALANCE
55from cryptography .hazmat .backends import default_backend
66from cryptography .hazmat .primitives .asymmetric import ec
7- from cryptography .hazmat .primitives import hashes
7+ from cryptography .hazmat .primitives .asymmetric .utils import (
8+ encode_dss_signature ,
9+ decode_dss_signature
10+ )
11+ from cryptography .hazmat .primitives import hashes , serialization
812from cryptography .exceptions import InvalidSignature
913
1014class Wallet :
@@ -21,24 +25,41 @@ def __init__(self):
2125 default_backend ()
2226 )
2327 self .public_key = self .private_key .public_key ()
28+ self .serialize_public_key ()
2429
2530 def sign (self , data ):
2631 """
2732 Generate a signature based on the data using the local private key.
2833 """
29- return self .private_key .sign (
34+ return decode_dss_signature ( self .private_key .sign (
3035 json .dumps (data ).encode ('utf-8' ),
3136 ec .ECDSA (hashes .SHA256 ())
32- )
37+ ))
38+
39+ def serialize_public_key (self ):
40+ """
41+ Reset the public key to its serialized version.
42+ """
43+ self .public_key = self .public_key .public_bytes (
44+ encoding = serialization .Encoding .PEM ,
45+ format = serialization .PublicFormat .SubjectPublicKeyInfo
46+ ).decode ('utf-8' )
3347
3448 @staticmethod
3549 def verify (public_key , data , signature ):
3650 """
3751 Verify a signature based on the original public key and data.
3852 """
53+ deserialized_public_key = serialization .load_pem_public_key (
54+ public_key .encode ('utf-8' ),
55+ default_backend ()
56+ )
57+
58+ (r , s ) = signature
59+
3960 try :
40- public_key .verify (
41- signature ,
61+ deserialized_public_key .verify (
62+ encode_dss_signature ( r , s ) ,
4263 json .dumps (data ).encode ('utf-8' ),
4364 ec .ECDSA (hashes .SHA256 ())
4465 )
0 commit comments