Skip to content

Instantly share code, notes, and snippets.

@drem-darios
Created March 9, 2017 18:06
Show Gist options
  • Save drem-darios/36c7a1e57e623d59919b9702fae0a1b9 to your computer and use it in GitHub Desktop.
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
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
print
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
print
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
print
self.assertEqual(signature1, signature2)
if __name__ == '__main__':
unittest.main()
@balasmeh
Copy link

well, good job and thank you for the code sir, but after running the code, im getting this error, line 42, in init
raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).name)
TypeError: key: expected bytes or bytearray, but got 'str'

i'm using spyder python 3.6

thank you again sir.

@drem-darios
Copy link
Author

Hi @balasmeh,

This code was written for python 2.7. I will create a 3.6 gist for you and post it.

@drem-darios
Copy link
Author

Python 3.6 implementation can be found here: https://gist.github.com/drem-darios/2622dffe0642054be71dcbaa62ea8491

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment