Python hmac.HMAC Examples
The following are 30
code examples of hmac.HMAC().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
hmac
, or try the search function
.
Example #1
Source File: sastoken.py From azure-iot-sdk-python with MIT License | 6 votes |
def _build_token(self): """Buid SasToken representation Returns: String representation of the token """ try: message = (self._uri + "\n" + str(self.expiry_time)).encode(self._encoding_type) signing_key = base64.b64decode(self._key.encode(self._encoding_type)) signed_hmac = hmac.HMAC(signing_key, message, hashlib.sha256) signature = urllib.parse.quote(base64.b64encode(signed_hmac.digest())) except (TypeError, base64.binascii.Error) as e: raise SasTokenError("Unable to build SasToken from given values", e) if self._key_name: token = self._service_token_format.format( self._uri, signature, str(self.expiry_time), self._key_name ) else: token = self._device_token_format.format(self._uri, signature, str(self.expiry_time)) return token
Example #2
Source File: test_azure_iothub_receive.py From azure-uamqp-python with MIT License | 6 votes |
def generate_sas_token(self): """ Create a shared access signiture token as a string literal. Returns: result (str): SAS token as string literal. """ encoded_uri = quote_plus(self.uri) ttl = int(self.expiry) sign_key = '%s\n%d' % (encoded_uri, ttl) signature = b64encode(HMAC(b64decode(self.key), sign_key.encode('utf-8'), sha256).digest()) result = { 'sr': self.uri, 'sig': signature, 'se': str(ttl) } if self.policy: result['skn'] = self.policy return 'SharedAccessSignature ' + urlencode(result)
Example #3
Source File: auth.py From recruit with Apache License 2.0 | 6 votes |
def _hi(data, salt, iterations): """A simple implementation of PBKDF2.""" mac = hmac.HMAC(data, None, _SHA1MOD) def _digest(msg, mac=mac): """Get a digest for msg.""" _mac = mac.copy() _mac.update(msg) return _mac.digest() from_bytes = _from_bytes to_bytes = _to_bytes _u1 = _digest(salt + _BIGONE) _ui = from_bytes(_u1, 'big') for _ in range(iterations - 1): _u1 = _digest(_u1) _ui ^= from_bytes(_u1, 'big') return to_bytes(_ui, 20, 'big')
Example #4
Source File: test_hmac.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_legacy_block_size_warnings(self): class MockCrazyHash(object): """Ain't no block_size attribute here.""" def __init__(self, *args): self._x = hashlib.sha1(*args) self.digest_size = self._x.digest_size def update(self, v): self._x.update(v) def digest(self): return self._x.digest() with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) with self.assertRaises(RuntimeWarning): hmac.HMAC('a', 'b', digestmod=MockCrazyHash) self.fail('Expected warning about missing block_size') MockCrazyHash.block_size = 1 with self.assertRaises(RuntimeWarning): hmac.HMAC('a', 'b', digestmod=MockCrazyHash) self.fail('Expected warning about small block_size')
Example #5
Source File: SenseHat_IoTHub_Http_C2D_LED.py From IIoT with MIT License | 6 votes |
def _buildIoTHubSasToken(self, deviceId): resourceUri = '%s/devices/%s' % (self.iotHost, deviceId) targetUri = resourceUri.lower() expiryTime = self._buildExpiryOn() toSign = '%s\n%s' % (targetUri, expiryTime) key = base64.b64decode(self.keyValue.encode('utf-8')) if sys.version_info[0] < 3: signature = urllib.quote( base64.b64encode( hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest() ) ).replace('/', '%2F') else: signature = urllib.parse.quote( base64.b64encode( hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest() ) ).replace('/', '%2F') return self.TOKEN_FORMAT % (signature, expiryTime, self.keyName, targetUri)
Example #6
Source File: SenseHat_IoTHub_Http_Lab_Key.py From IIoT with MIT License | 6 votes |
def _buildIoTHubSasToken(self, deviceId): resourceUri = '%s/devices/%s' % (self.iotHost, deviceId) targetUri = resourceUri.lower() expiryTime = self._buildExpiryOn() toSign = '%s\n%s' % (targetUri, expiryTime) key = base64.b64decode(self.keyValue.encode('utf-8')) if sys.version_info[0] < 3: signature = urllib.quote( base64.b64encode( hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest() ) ).replace('/', '%2F') else: signature = urllib.parse.quote( base64.b64encode( hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest() ) ).replace('/', '%2F') return self.TOKEN_FORMAT % (signature, expiryTime, self.keyName, targetUri)
Example #7
Source File: SenseHat_IoTHub_Http_Lab.py From IIoT with MIT License | 6 votes |
def _buildIoTHubSasToken(self, deviceId): resourceUri = '%s/devices/%s' % (self.iotHost, deviceId) targetUri = resourceUri.lower() expiryTime = self._buildExpiryOn() toSign = '%s\n%s' % (targetUri, expiryTime) key = base64.b64decode(self.keyValue.encode('utf-8')) if sys.version_info[0] < 3: signature = urllib.quote( base64.b64encode( hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest() ) ).replace('/', '%2F') else: signature = urllib.parse.quote( base64.b64encode( hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest() ) ).replace('/', '%2F') return self.TOKEN_FORMAT % (signature, expiryTime, self.keyName, targetUri)
Example #8
Source File: SenseHat_IoTHub_Http.py From IIoT with MIT License | 6 votes |
def _buildIoTHubSasToken(self, deviceId): resourceUri = '%s/devices/%s' % (self.iotHost, deviceId) targetUri = resourceUri.lower() expiryTime = self._buildExpiryOn() toSign = '%s\n%s' % (targetUri, expiryTime) key = base64.b64decode(self.keyValue.encode('utf-8')) if sys.version_info[0] < 3: signature = urllib.quote( base64.b64encode( hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest() ) ).replace('/', '%2F') else: signature = urllib.parse.quote( base64.b64encode( hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest() ) ).replace('/', '%2F') return self.TOKEN_FORMAT % (signature, expiryTime, self.keyName, targetUri)
Example #9
Source File: auth.py From vnpy_crypto with MIT License | 6 votes |
def _hi(hash_name, data, salt, iterations): """A simple implementation of PBKDF2-HMAC.""" mac = hmac.HMAC(data, None, getattr(hashlib, hash_name)) def _digest(msg, mac=mac): """Get a digest for msg.""" _mac = mac.copy() _mac.update(msg) return _mac.digest() from_bytes = _from_bytes to_bytes = _to_bytes _u1 = _digest(salt + b'\x00\x00\x00\x01') _ui = from_bytes(_u1, 'big') for _ in range(iterations - 1): _u1 = _digest(_u1) _ui ^= from_bytes(_u1, 'big') return to_bytes(_ui, mac.digest_size, 'big')
Example #10
Source File: auth.py From vnpy_crypto with MIT License | 6 votes |
def _authenticate_cram_md5(credentials, sock_info): """Authenticate using CRAM-MD5 (RFC 2195) """ source = credentials.source username = credentials.username password = credentials.password # The password used as the mac key is the # same as what we use for MONGODB-CR passwd = _password_digest(username, password) cmd = SON([('saslStart', 1), ('mechanism', 'CRAM-MD5'), ('payload', Binary(b'')), ('autoAuthorize', 1)]) response = sock_info.command(source, cmd) # MD5 as implicit default digest for digestmod is deprecated # in python 3.4 mac = hmac.HMAC(key=passwd.encode('utf-8'), digestmod=hashlib.md5) mac.update(response['payload']) challenge = username.encode('utf-8') + b' ' + mac.hexdigest().encode('utf-8') cmd = SON([('saslContinue', 1), ('conversationId', response['conversationId']), ('payload', Binary(challenge))]) sock_info.command(source, cmd)
Example #11
Source File: test_hmac.py From oss-ftp with MIT License | 6 votes |
def test_legacy_block_size_warnings(self): class MockCrazyHash(object): """Ain't no block_size attribute here.""" def __init__(self, *args): self._x = hashlib.sha1(*args) self.digest_size = self._x.digest_size def update(self, v): self._x.update(v) def digest(self): return self._x.digest() with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) with self.assertRaises(RuntimeWarning): hmac.HMAC('a', 'b', digestmod=MockCrazyHash) self.fail('Expected warning about missing block_size') MockCrazyHash.block_size = 1 with self.assertRaises(RuntimeWarning): hmac.HMAC('a', 'b', digestmod=MockCrazyHash) self.fail('Expected warning about small block_size')
Example #12
Source File: knownhosts.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def _hmacedString(key, string): """ Return the SHA-1 HMAC hash of the given key and string. @param key: The HMAC key. @type key: L{bytes} @param string: The string to be hashed. @type string: L{bytes} @return: The keyed hash value. @rtype: L{bytes} """ hash = hmac.HMAC(key, digestmod=sha1) if isinstance(string, unicode): string = string.encode("utf-8") hash.update(string) return hash.digest()
Example #13
Source File: transport.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def makeMAC(self, seqid, data): """ Create a message authentication code (MAC) for the given packet using the outgoing MAC values. @type seqid: L{int} @param seqid: The sequence ID of the outgoing packet. @type data: L{bytes} @param data: The data to create a MAC for. @rtype: L{str} @return: The serialized MAC. """ if not self.outMAC[0]: return b'' data = struct.pack('>L', seqid) + data return hmac.HMAC(self.outMAC.key, data, self.outMAC[0]).digest()
Example #14
Source File: transport.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def verify(self, seqid, data, mac): """ Verify an incoming MAC using the incoming MAC values. @type seqid: L{int} @param seqid: The sequence ID of the incoming packet. @type data: L{bytes} @param data: The packet data to verify. @type mac: L{bytes} @param mac: The MAC sent with the packet. @rtype: L{bool} @return: C{True} if the MAC is valid. """ if not self.inMAC[0]: return mac == b'' data = struct.pack('>L', seqid) + data outer = hmac.HMAC(self.inMAC.key, data, self.inMAC[0]).digest() return mac == outer
Example #15
Source File: auth.py From satori with Apache License 2.0 | 6 votes |
def _hi(data, salt, iterations): """A simple implementation of PBKDF2.""" mac = hmac.HMAC(data, None, sha1) def _digest(msg, mac=mac): """Get a digest for msg.""" _mac = mac.copy() _mac.update(msg) return _mac.digest() from_bytes = _from_bytes to_bytes = _to_bytes _u1 = _digest(salt + b'\x00\x00\x00\x01') _ui = from_bytes(_u1, 'big') for _ in range(iterations - 1): _u1 = _digest(_u1) _ui ^= from_bytes(_u1, 'big') return to_bytes(_ui, 20, 'big')
Example #16
Source File: auth.py From satori with Apache License 2.0 | 6 votes |
def _authenticate_cram_md5(credentials, sock_info): """Authenticate using CRAM-MD5 (RFC 2195) """ source = credentials.source username = credentials.username password = credentials.password # The password used as the mac key is the # same as what we use for MONGODB-CR passwd = _password_digest(username, password) cmd = SON([('saslStart', 1), ('mechanism', 'CRAM-MD5'), ('payload', Binary(b'')), ('autoAuthorize', 1)]) response = sock_info.command(source, cmd) # MD5 as implicit default digest for digestmod is deprecated # in python 3.4 mac = hmac.HMAC(key=passwd.encode('utf-8'), digestmod=md5) mac.update(response['payload']) challenge = username.encode('utf-8') + b' ' + b(mac.hexdigest()) cmd = SON([('saslContinue', 1), ('conversationId', response['conversationId']), ('payload', Binary(challenge))]) sock_info.command(source, cmd)
Example #17
Source File: test_hmac.py From BinderFilter with MIT License | 6 votes |
def test_legacy_block_size_warnings(self): class MockCrazyHash(object): """Ain't no block_size attribute here.""" def __init__(self, *args): self._x = hashlib.sha1(*args) self.digest_size = self._x.digest_size def update(self, v): self._x.update(v) def digest(self): return self._x.digest() with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) with self.assertRaises(RuntimeWarning): hmac.HMAC('a', 'b', digestmod=MockCrazyHash) self.fail('Expected warning about missing block_size') MockCrazyHash.block_size = 1 with self.assertRaises(RuntimeWarning): hmac.HMAC('a', 'b', digestmod=MockCrazyHash) self.fail('Expected warning about small block_size')
Example #18
Source File: client.py From azure-event-hubs-python with MIT License | 6 votes |
def _generate_sas_token(uri, policy, key, expiry=None): """Create a shared access signiture token as a string literal. :returns: SAS token as string literal. :rtype: str """ from base64 import b64encode, b64decode from hashlib import sha256 from hmac import HMAC if not expiry: expiry = time.time() + 3600 # Default to 1 hour. encoded_uri = quote_plus(uri) ttl = int(expiry) sign_key = '%s\n%d' % (encoded_uri, ttl) signature = b64encode(HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest()) result = { 'sr': uri, 'sig': signature, 'se': str(ttl)} if policy: result['skn'] = policy return 'SharedAccessSignature ' + urlencode(result)
Example #19
Source File: auth.py From recruit with Apache License 2.0 | 6 votes |
def _authenticate_cram_md5(credentials, sock_info, cmd_func): """Authenticate using CRAM-MD5 (RFC 2195) """ source, username, password = credentials # The password used as the mac key is the # same as what we use for MONGODB-CR passwd = _password_digest(username, password) cmd = SON([('saslStart', 1), ('mechanism', 'CRAM-MD5'), ('payload', Binary(b(''))), ('autoAuthorize', 1)]) response, _ = cmd_func(sock_info, source, cmd) # MD5 as implicit default digest for digestmod is deprecated # in python 3.4 mac = hmac.HMAC(key=passwd.encode('utf-8'), digestmod=_DMOD) mac.update(response['payload']) challenge = username.encode('utf-8') + b(' ') + b(mac.hexdigest()) cmd = SON([('saslContinue', 1), ('conversationId', response['conversationId']), ('payload', Binary(challenge))]) cmd_func(sock_info, source, cmd)
Example #20
Source File: session.py From Computable with MIT License | 5 votes |
def _key_changed(self, name, old, new): if new: self.auth = hmac.HMAC(new, digestmod=self.digest_mod) else: self.auth = None
Example #21
Source File: imaplib.py From oss-ftp with MIT License | 5 votes |
def _CRAM_MD5_AUTH(self, challenge): """ Authobject to use with CRAM-MD5 authentication. """ import hmac return self.user + " " + hmac.HMAC(self.password, challenge).hexdigest()
Example #22
Source File: session.py From Computable with MIT License | 5 votes |
def sign(self, msg_list): """Sign a message with HMAC digest. If no auth, return b''. Parameters ---------- msg_list : list The [p_header,p_parent,p_content] part of the message list. """ if self.auth is None: return b'' h = self.auth.copy() for m in msg_list: h.update(m) return str_to_bytes(h.hexdigest())
Example #23
Source File: test_hmac.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_md5_vectors(self): # Test the HMAC module against test vectors from the RFC. def md5test(key, data, digest): h = hmac.HMAC(key, data) self.assertEqual(h.hexdigest().upper(), digest.upper()) md5test(chr(0x0b) * 16, "Hi There", "9294727A3638BB1C13F48EF8158BFC9D") md5test("Jefe", "what do ya want for nothing?", "750c783e6ab0b503eaa86e310a5db738") md5test(chr(0xAA)*16, chr(0xDD)*50, "56be34521d144c88dbb8c733f0e8b3f6") md5test("".join([chr(i) for i in range(1, 26)]), chr(0xCD) * 50, "697eaf0aca3a3aea3a75164746ffaa79") md5test(chr(0x0C) * 16, "Test With Truncation", "56461ef2342edc00f9bab995690efd4c") md5test(chr(0xAA) * 80, "Test Using Larger Than Block-Size Key - Hash Key First", "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd") md5test(chr(0xAA) * 80, ("Test Using Larger Than Block-Size Key " "and Larger Than One Block-Size Data"), "6f630fad67cda0ee1fb1f562db3aa53e")
Example #24
Source File: test_hmac.py From oss-ftp with MIT License | 5 votes |
def test_normal(self): # Standard constructor call. failed = 0 try: h = hmac.HMAC("key") except: self.fail("Standard constructor call raised exception.")
Example #25
Source File: test_hmac.py From oss-ftp with MIT License | 5 votes |
def test_withmodule(self): # Constructor call with text and digest module. try: h = hmac.HMAC("key", "", hashlib.sha1) except: self.fail("Constructor call with hashlib.sha1 raised exception.")
Example #26
Source File: test_hmac.py From oss-ftp with MIT License | 5 votes |
def test_default_is_md5(self): # Testing if HMAC defaults to MD5 algorithm. # NOTE: this whitebox test depends on the hmac class internals h = hmac.HMAC("key") self.assertTrue(h.digest_cons == hashlib.md5)
Example #27
Source File: test_hmac.py From oss-ftp with MIT License | 5 votes |
def test_exercise_all_methods(self): # Exercising all methods once. # This must not raise any exceptions try: h = hmac.HMAC("my secret key") h.update("compute the hash of this text!") dig = h.digest() dig = h.hexdigest() h2 = h.copy() except: self.fail("Exception raised during normal usage of HMAC class.")
Example #28
Source File: test_hmac.py From oss-ftp with MIT License | 5 votes |
def test_attributes(self): # Testing if attributes are of same type. h1 = hmac.HMAC("key") h2 = h1.copy() self.assertTrue(h1.digest_cons == h2.digest_cons, "digest constructors don't match.") self.assertTrue(type(h1.inner) == type(h2.inner), "Types of inner don't match.") self.assertTrue(type(h1.outer) == type(h2.outer), "Types of outer don't match.")
Example #29
Source File: imaplib.py From Computable with MIT License | 5 votes |
def _CRAM_MD5_AUTH(self, challenge): """ Authobject to use with CRAM-MD5 authentication. """ import hmac return self.user + " " + hmac.HMAC(self.password, challenge).hexdigest()
Example #30
Source File: test_hmac.py From oss-ftp with MIT License | 5 votes |
def test_realcopy(self): # Testing if the copy method created a real copy. h1 = hmac.HMAC("key") h2 = h1.copy() # Using id() in case somebody has overridden __cmp__. self.assertTrue(id(h1) != id(h2), "No real copy of the HMAC instance.") self.assertTrue(id(h1.inner) != id(h2.inner), "No real copy of the attribute 'inner'.") self.assertTrue(id(h1.outer) != id(h2.outer), "No real copy of the attribute 'outer'.")