Last active
June 18, 2024 15:44
-
-
Save animatedlew/0fee76290dea4c6d568295e1dc164f19 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pathlib import Path | |
import pickle | |
import hmac | |
path = Path(__file__).parent | |
def run(): | |
secret_key = b"@SECRET@" | |
data = {'seed': 42} | |
save(data, 'data.pkl', secret_key) | |
return verify('data.pkl', secret_key) | |
# utils | |
def sign(data, secret_key): | |
return hmac.new(secret_key, data, digestmod='sha256').hexdigest() | |
def save(data, filename, secret_key): | |
with open(path / filename, 'wb') as f: | |
pickle.dump(data, f) | |
signature = sign(open(path / filename, 'rb').read(), secret_key) | |
with open(path / f'{filename}.sig', 'w') as f: | |
f.write(signature) | |
def verify(filename, secret_key): | |
with open(path / filename, 'rb') as f: | |
data = pickle.load(f) | |
with open(path / f'{filename}.sig', 'r') as f: | |
expected_signature = f.read() | |
signature = sign(open(path / filename, 'rb').read(), secret_key) | |
if signature != expected_signature: | |
raise ValueError('Data signature mismatch!') | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment