Created
March 9, 2017 18:06
-
-
Save drem-darios/36c7a1e57e623d59919b9702fae0a1b9 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 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): | |
dig = hmac.new(secret_key, salt, 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 | |
def test_generate_signature(self): | |
salt = SecurityUtil.generate_salt() | |
print "Salt: " + salt | |
signature = SecurityUtil.generate_signature(salt, "secretKey") | |
self.assertNotEqual(None, signature) | |
print "Signature: " + signature | |
def test_signatures_equal(self): | |
salt = SecurityUtil.generate_salt() | |
print "Salt: " + salt | |
signature1 = SecurityUtil.generate_signature(salt, "secretKey") | |
self.assertNotEqual(None, signature1) | |
print "Signature1: " + signature1 | |
signature2 = SecurityUtil.generate_signature(salt, "secretKey") | |
self.assertNotEqual(None, signature2) | |
print "Signature2: " + signature2 | |
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 3.6 implementation can be found here: https://gist.github.com/drem-darios/2622dffe0642054be71dcbaa62ea8491