Implement message signing and verification logic

This commit is contained in:
Kristóf Tóth 2018-07-15 17:29:16 +02:00
parent eb2c3a8dd0
commit b2cb60ef02

View File

@ -2,12 +2,32 @@
# All Rights Reserved. See LICENSE file for details. # All Rights Reserved. See LICENSE file for details.
from functools import wraps from functools import wraps
from base64 import b64encode, b64decode
from copy import deepcopy
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.hashes import SHA256 from cryptography.hazmat.primitives.hashes import SHA256
from cryptography.hazmat.primitives.hmac import HMAC as _HMAC from cryptography.hazmat.primitives.hmac import HMAC as _HMAC
from cryptography.exceptions import InvalidSignature 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: class HMAC:
def __init__(self, key, message): def __init__(self, key, message):