Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/ellipticcurve/signature.py: 39%

35 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

1from .utils.compatibility import * 

2from .utils.der import parse, encodeConstructed, encodePrimitive, DerFieldType 

3from .utils.binary import hexFromByteString, byteStringFromHex, base64FromByteString, byteStringFromBase64 

4 

5 

6class Signature: 

7 

8 def __init__(self, r, s, recoveryId=None): 

9 self.r = r 

10 self.s = s 

11 self.recoveryId = recoveryId 

12 

13 def toDer(self, withRecoveryId=False): 

14 hexadecimal = self._toString() 

15 encodedSequence = byteStringFromHex(hexadecimal) 

16 if not withRecoveryId: 

17 return encodedSequence 

18 return toBytes(chr(27 + self.recoveryId)) + encodedSequence 

19 

20 def toBase64(self, withRecoveryId=False): 

21 return base64FromByteString(self.toDer(withRecoveryId)) 

22 

23 @classmethod 

24 def fromDer(cls, string, recoveryByte=False): 

25 recoveryId = None 

26 if recoveryByte: 

27 recoveryId = string[0] if isinstance(string[0], intTypes) else ord(string[0]) 

28 recoveryId -= 27 

29 string = string[1:] 

30 

31 hexadecimal = hexFromByteString(string) 

32 return cls._fromString(string=hexadecimal, recoveryId=recoveryId) 

33 

34 @classmethod 

35 def fromBase64(cls, string, recoveryByte=False): 

36 der = byteStringFromBase64(string) 

37 return cls.fromDer(der, recoveryByte) 

38 

39 def _toString(self): 

40 return encodeConstructed( 

41 encodePrimitive(DerFieldType.integer, self.r), 

42 encodePrimitive(DerFieldType.integer, self.s), 

43 ) 

44 

45 @classmethod 

46 def _fromString(cls, string, recoveryId=None): 

47 r, s = parse(string)[0] 

48 return Signature(r=r, s=s, recoveryId=recoveryId)