11import logging
2- from base64 import urlsafe_b64decode , urlsafe_b64encode
2+ from base64 import b64decode , b64encode
33from cryptography .hazmat .primitives import hashes
44from cryptography .hazmat .primitives .asymmetric import ec
55from cryptography .hazmat .primitives import serialization
66from rid_lib .ext .utils import sha256_hash
7+ from cryptography .hazmat .primitives .asymmetric .utils import (
8+ decode_dss_signature ,
9+ encode_dss_signature
10+ )
711
812logger = logging .getLogger (__name__ )
913
1014
15+ def der_to_raw_signature (der_signature : bytes , curve = ec .SECP256R1 ()) -> bytes :
16+ """Convert a DER-encoded signature to raw r||s format."""
17+
18+ # Decode the DER signature to get r and s
19+ r , s = decode_dss_signature (der_signature )
20+
21+ # Determine byte length based on curve bit size
22+ byte_length = (curve .key_size + 7 ) // 8
23+
24+ # Convert r and s to big-endian byte arrays of fixed length
25+ r_bytes = r .to_bytes (byte_length , byteorder = 'big' )
26+ s_bytes = s .to_bytes (byte_length , byteorder = 'big' )
27+
28+ # Concatenate r and s
29+ return r_bytes + s_bytes
30+
31+
32+ def raw_to_der_signature (raw_signature : bytes , curve = ec .SECP256R1 ()) -> bytes :
33+ """Convert a raw r||s signature to DER format."""
34+
35+ # Determine byte length based on curve bit size
36+ byte_length = (curve .key_size + 7 ) // 8
37+
38+ # Split the raw signature into r and s components
39+ if len (raw_signature ) != 2 * byte_length :
40+ raise ValueError (f"Raw signature must be { 2 * byte_length } bytes for { curve .name } " )
41+
42+ r_bytes = raw_signature [:byte_length ]
43+ s_bytes = raw_signature [byte_length :]
44+
45+ # Convert bytes to integers
46+ r = int .from_bytes (r_bytes , byteorder = 'big' )
47+ s = int .from_bytes (s_bytes , byteorder = 'big' )
48+
49+ # Encode as DER
50+ return encode_dss_signature (r , s )
51+
52+
1153class PrivateKey :
1254 priv_key : ec .EllipticCurvePrivateKey
1355
1456 def __init__ (self , priv_key ):
1557 self .priv_key = priv_key
16-
58+
1759 @classmethod
1860 def generate (cls ):
19- return cls (priv_key = ec .generate_private_key (ec .SECP192R1 ()))
61+ return cls (priv_key = ec .generate_private_key (ec .SECP256R1 ()))
2062
2163 def public_key (self ) -> "PublicKey" :
2264 return PublicKey (self .priv_key .public_key ())
@@ -40,12 +82,14 @@ def to_pem(self, password: str) -> str:
4082 def sign (self , message : bytes ) -> str :
4183 hashed_message = sha256_hash (message .decode ())
4284
43- signature = urlsafe_b64encode (
44- self .priv_key .sign (
45- data = message ,
46- signature_algorithm = ec .ECDSA (hashes .SHA256 ())
47- )
48- ).decode ()
85+ der_signature_bytes = self .priv_key .sign (
86+ data = message ,
87+ signature_algorithm = ec .ECDSA (hashes .SHA256 ())
88+ )
89+
90+ raw_signature_bytes = der_to_raw_signature (der_signature_bytes )
91+
92+ signature = b64encode (raw_signature_bytes ).decode ()
4993
5094 logger .debug (f"Signing message with [{ self .public_key ().to_der ()} ]" )
5195 logger .debug (f"hash: { hashed_message } " )
@@ -78,29 +122,39 @@ def to_pem(self) -> str:
78122 def from_der (cls , pub_key_der : str ):
79123 return cls (
80124 pub_key = serialization .load_der_public_key (
81- data = urlsafe_b64decode (pub_key_der )
125+ data = b64decode (pub_key_der )
82126 )
83127 )
84128
85129 def to_der (self ) -> str :
86- return urlsafe_b64encode (
130+ return b64encode (
87131 self .pub_key .public_bytes (
88132 encoding = serialization .Encoding .DER ,
89133 format = serialization .PublicFormat .SubjectPublicKeyInfo
90134 )
91135 ).decode ()
92136
137+
93138 def verify (self , signature : str , message : bytes ) -> bool :
94- hashed_message = sha256_hash (message .decode ())
139+ # hashed_message = sha256_hash(message.decode())
140+
141+ # print(message.hex())
142+ # print()
143+ # print(hashed_message)
144+ # print()
145+ # print(message.decode())
95146
96- logger .debug (f"Verifying message with [{ self .to_der ()} ]" )
97- logger .debug (f"hash: { hashed_message } " )
98- logger .debug (f"signature: { signature } " )
147+ # logger.debug(f"Verifying message with [{self.to_der()}]")
148+ # logger.debug(f"hash: {hashed_message}")
149+ # logger.debug(f"signature: {signature}")
150+
151+ raw_signature_bytes = b64decode (signature )
152+ der_signature_bytes = raw_to_der_signature (raw_signature_bytes )
99153
100154 # NOTE: throws cryptography.exceptions.InvalidSignature on failure
101155
102156 self .pub_key .verify (
103- signature = urlsafe_b64decode ( signature ) ,
157+ signature = der_signature_bytes ,
104158 data = message ,
105159 signature_algorithm = ec .ECDSA (hashes .SHA256 ())
106160 )
0 commit comments