mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-22 19:21:31 +00:00
Add crypto module with HMAC-SHA256 implementation
This commit is contained in:
parent
16d98c75ca
commit
eb2c3a8dd0
47
lib/tfw/crypto.py
Normal file
47
lib/tfw/crypto.py
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
# Copyright (C) 2018 Avatao.com Innovative Learning Kft.
|
||||||
|
# All Rights Reserved. See LICENSE file for details.
|
||||||
|
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
class HMAC:
|
||||||
|
def __init__(self, key, message):
|
||||||
|
self.key = key
|
||||||
|
self.message = message
|
||||||
|
self._hmac = _HMAC(
|
||||||
|
key=key,
|
||||||
|
algorithm=SHA256(),
|
||||||
|
backend=default_backend()
|
||||||
|
)
|
||||||
|
|
||||||
|
def _reload_if_finalized(f):
|
||||||
|
# pylint: disable=no-self-argument,not-callable
|
||||||
|
@wraps(f)
|
||||||
|
def wrapped(instance, *args, **kwargs):
|
||||||
|
if getattr(instance, '_finalized', False):
|
||||||
|
instance.__init__(instance.key, instance.message)
|
||||||
|
ret_val = f(instance, *args, **kwargs)
|
||||||
|
setattr(instance, '_finalized', True)
|
||||||
|
return ret_val
|
||||||
|
return wrapped
|
||||||
|
|
||||||
|
@property
|
||||||
|
@_reload_if_finalized
|
||||||
|
def signature(self):
|
||||||
|
self._hmac.update(self.message)
|
||||||
|
signature = self._hmac.finalize()
|
||||||
|
return signature
|
||||||
|
|
||||||
|
@_reload_if_finalized
|
||||||
|
def verify(self, signature):
|
||||||
|
self._hmac.update(self.message)
|
||||||
|
try:
|
||||||
|
self._hmac.verify(signature)
|
||||||
|
return True
|
||||||
|
except InvalidSignature:
|
||||||
|
return False
|
@ -5,3 +5,4 @@ terminado==0.8.1
|
|||||||
watchdog==0.8.3
|
watchdog==0.8.3
|
||||||
PyYAML==3.12
|
PyYAML==3.12
|
||||||
Jinja2==2.10
|
Jinja2==2.10
|
||||||
|
cryptography==2.2.2
|
||||||
|
Loading…
Reference in New Issue
Block a user