From 5770e297330e0d6224e8693260934c26953cfcaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Sun, 15 Jul 2018 17:30:19 +0200 Subject: [PATCH] Move message checksum logic to crypto.py --- lib/tfw/crypto.py | 5 +++++ lib/tfw/event_handler_base.py | 14 ++++---------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/lib/tfw/crypto.py b/lib/tfw/crypto.py index 47ab64e..be2d54e 100644 --- a/lib/tfw/crypto.py +++ b/lib/tfw/crypto.py @@ -4,6 +4,7 @@ from functools import wraps from base64 import b64encode, b64decode from copy import deepcopy +from hashlib import md5 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.hashes import SHA256 @@ -13,6 +14,10 @@ from cryptography.exceptions import InvalidSignature from tfw.networking import message_bytes +def message_checksum(message): + return md5(message_bytes(message)).hexdigest() + + def sign_message(key, message): signature = HMAC(key, message_bytes(message)).signature message['signature'] = b64encode(signature).decode() diff --git a/lib/tfw/event_handler_base.py b/lib/tfw/event_handler_base.py index f6a094a..0cc023d 100644 --- a/lib/tfw/event_handler_base.py +++ b/lib/tfw/event_handler_base.py @@ -2,10 +2,9 @@ # All Rights Reserved. See LICENSE file for details. from abc import ABC, abstractmethod -from json import dumps -from hashlib import md5 from tfw.networking.event_handlers import ServerConnector +from tfw.crypto import message_checksum from tfw.config.logs import logging LOG = logging.getLogger(__name__) @@ -82,7 +81,7 @@ class EventHandlerBase(ABC): Note that you can subscribe to the same key several times in which case you will need to unsubscribe multiple times in order to stop receiving events. - + :param keys: list of keys to subscribe to """ for key in keys: @@ -152,7 +151,7 @@ class BroadcastingEventHandler(EventHandlerBase, ABC): self.own_message_hashes = [] def event_handler_callback(self, message): - message_hash = self.hash_message(message) + message_hash = message_checksum(message) if message_hash in self.own_message_hashes: self.own_message_hashes.remove(message_hash) @@ -160,10 +159,5 @@ class BroadcastingEventHandler(EventHandlerBase, ABC): response = self.dispatch_handling(message) if response: - self.own_message_hashes.append(self.hash_message(response)) + self.own_message_hashes.append(message_checksum(response)) self.server_connector.broadcast(response) - - @staticmethod - def hash_message(message): - message_bytes = dumps(message, sort_keys=True).encode() - return md5(message_bytes).hexdigest()