From b2cb60ef0214b9de8632ecfea752f70ee9f2e3df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Sun, 15 Jul 2018 17:29:16 +0200 Subject: [PATCH] Implement message signing and verification logic --- lib/tfw/crypto.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lib/tfw/crypto.py b/lib/tfw/crypto.py index 413a1d6..47ab64e 100644 --- a/lib/tfw/crypto.py +++ b/lib/tfw/crypto.py @@ -2,12 +2,32 @@ # All Rights Reserved. See LICENSE file for details. from functools import wraps +from base64 import b64encode, b64decode +from copy import deepcopy from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.hashes import SHA256 from cryptography.hazmat.primitives.hmac import HMAC as _HMAC from cryptography.exceptions import InvalidSignature +from tfw.networking import message_bytes + + +def sign_message(key, message): + signature = HMAC(key, message_bytes(message)).signature + message['signature'] = b64encode(signature).decode() + + +def verify_message(key, message): + message = deepcopy(message) + try: + signature_b64 = message.pop('signature') + signature = b64decode(signature_b64) + actual_signature = HMAC(key, message_bytes(message)).signature + return signature == actual_signature + except KeyError: + return False + class HMAC: def __init__(self, key, message):