Created
February 10, 2020 06:08
-
-
Save drem-darios/2622dffe0642054be71dcbaa62ea8491 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 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
Python 2.7 version: https://gist.github.com/drem-darios/36c7a1e57e623d59919b9702fae0a1b9