BytestringSplitter for #114.

pull/116/head
jMyles 2017-11-11 01:10:29 -08:00
parent 7e43f3caad
commit 4f803ba2df
3 changed files with 42 additions and 6 deletions

View File

@ -1,7 +1,7 @@
from nkms.crypto import api as API
class Signature(object):
class Signature(bytes):
"""
The Signature object allows signatures to be made and verified.
"""
@ -29,6 +29,9 @@ class Signature(object):
self._r = r
self._s = s
def __repr__(self):
return "{} v{}: {} - {}".format(__class__.__name__, self._v, self._r, self._s)
def verify(self, message: bytes, pubkey: bytes) -> bool:
"""
Verifies that a message's signature was valid.

View File

@ -1,7 +1,27 @@
from nkms.crypto import api
def verify(signature: bytes, message: bytes, pubkey: bytes) -> bool:
msg_digest = api.keccak_digest(message)
ecdsa_sig = api.ecdsa_load_sig(bytes(signature))
return api.ecdsa_verify(*ecdsa_sig, msg_digest, pubkey)
class BytestringSplitter(object):
def __init__(self, *message_types):
"""
:param message_types: A collection of types of messages to parse.
"""
self.message_types = message_types
def __call__(self, splittable):
if self.total_expected_length() != len(splittable):
raise ValueError("Wrong number of bytes to constitute message types {} - need {}, got {}".format(self.message_types, self.total_expected_length(), len(splittable)))
cursor = 0
message_objects = []
for message_type in self.message_types:
expected_end_of_object_bytes = cursor + message_type._EXPECTED_LENGTH
bytes_for_this_object = splittable[cursor:cursor + expected_end_of_object_bytes]
message_objects.append(message_type(bytes_for_this_object))
cursor = expected_end_of_object_bytes
return message_objects
def total_expected_length(self):
return sum(m._EXPECTED_LENGTH for m in self.message_types)

View File

@ -0,0 +1,13 @@
from nkms.crypto.api import secure_random
from nkms.crypto.signature import Signature
from nkms.crypto.utils import BytestringSplitter
def test_split_two_signatures():
"""
We make two random Signatures and concat them. Then split them and show that we got the proper result.
"""
sig1, sig2 = Signature(secure_random(65)), Signature(secure_random(65))
two_signature_splitter = BytestringSplitter(Signature, Signature)
rebuilt_sig1, rebuilt_sig2 = two_signature_splitter(sig1 + sig2)
assert (sig1, sig2) == (rebuilt_sig1, rebuilt_sig2)