-
-
Save diek/a0ea64b4d818c323a636760a0d791daf to your computer and use it in GitHub Desktop.
Python example of how to create a salt and use a secret key to generate a signature using the salt. This was tested with Python 3.6.8
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
import hmac | |
import os | |
import hashlib | |
import base64 | |
import unittest | |
__author__ = 'drem' | |
class SecurityUtil(object): | |
@staticmethod | |
def generate_salt(): | |
salt = os.urandom(16) | |
return str(base64.b64encode(salt)) | |
@staticmethod | |
def generate_signature(salt, secret_key, encoding): | |
secret_key_bytes = bytes(secret_key, encoding) | |
salt_bytes = bytes(salt, encoding) | |
dig = hmac.new(secret_key_bytes, salt_bytes, hashlib.sha256).digest() | |
signature = base64.b64encode(dig) | |
return signature | |
class TestSecurityUtil(unittest.TestCase): | |
def test_generate_salt(self): | |
salt = SecurityUtil.generate_salt() | |
self.assertNotEqual(None, salt) | |
print("Salt: " + salt) | |
print() | |
def test_generate_signature(self): | |
salt = SecurityUtil.generate_salt() | |
print("Salt: " + salt) | |
signature = SecurityUtil.generate_signature(salt, "secretKey", "utf-8") | |
self.assertNotEqual(None, signature) | |
print("Signature: " + str(signature)) | |
print() | |
def test_signatures_equal(self): | |
salt = SecurityUtil.generate_salt() | |
print("Salt: " + salt) | |
signature1 = SecurityUtil.generate_signature(salt, "secretKey", "utf-8") | |
self.assertNotEqual(None, signature1) | |
print("Signature1: " + str(signature1)) | |
signature2 = SecurityUtil.generate_signature(salt, "secretKey", "utf-8") | |
self.assertNotEqual(None, signature2) | |
print("Signature2: " + str(signature2)) | |
print() | |
self.assertEqual(signature1, signature2) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment