def shatest(key, data, digest): h = HMAC(key, data, digestmod=_hashlib.sha1) assertEqual(h.hexdigest().upper(), digest.upper()) assertEqual(h.name, "hmac-sha1") assertEqual(h.digest_size, 20) assertEqual(h.block_size, 64) h = HMAC(key, data, digestmod='sha1') assertEqual(h.hexdigest().upper(), digest.upper()) assertEqual(h.name, "hmac-sha1") assertEqual(h.digest_size, 20) assertEqual(h.block_size, 64)
def hmactest(key, data, hexdigests): hmac_name = "hmac-" + hash_name h = HMAC(key, data, digestmod=hashfunc) assertEqual(h.hexdigest().lower(), hexdigests[hashfunc]) assertEqual(h.name, hmac_name) assertEqual(h.digest_size, digest_size) assertEqual(h.block_size, block_size) h = HMAC(key, data, digestmod=hash_name) assertEqual(h.hexdigest().lower(), hexdigests[hashfunc]) assertEqual(h.name, hmac_name) assertEqual(h.digest_size, digest_size) assertEqual(h.block_size, block_size)
def test_hmac_package(self): from hmac import HMAC import hashlib k_hex = binascii.hexlify("") hmac = HMAC(k_hex, digestmod=hashlib.sha1) self.assertEquals(hmac.hexdigest(), self.result['empty']) k_hex = binascii.hexlify("key") d_hex = binascii.hexlify("The quick brown fox jumps over the lazy dog") hmac1 = HMAC(k_hex, digestmod=hashlib.sha1) hmac1.update(d_hex) self.assertEquals(hmac.hexdigest(), self.result['empty'])
def dynamic_truncation(raw_key: hmac.HMAC, length: int) -> str: bitstring = bin(int(raw_key.hexdigest(), base=16)) last_four_bits = bitstring[-4:] offset = int(last_four_bits, base=2) chosen_32_bits = bitstring[offset * 8:offset * 8 + 32] full_totp = str(int(chosen_32_bits, base=2)) return full_totp[-length:]
def generate_signature(self): from hmac import HMAC from hashlib import sha256 key = self.webhook.secret.encode("utf-8") msg = self.payload.encode("utf-8") mac = HMAC(key, msg, digestmod=sha256) return "sha256=" + mac.hexdigest()
def make_signature(endpoint, force_ts=None): # # Pick a timestamp and perform the signature required. # assert endpoint[0] == '/' and 'api.coinkite.com' not in endpoint, \ "Expecting abs url, got: %s" % endpoint ts = force_ts or datetime.datetime.utcnow().isoformat() data = endpoint + "|" + ts hm = HMAC(API_SECRET, msg=data, digestmod=sha256) return hm.hexdigest(), ts
def _make_request(self, data): bsecret = self._secret.encode('ascii') sign = HMAC(bsecret, digestmod=sha512) sign.update(data.encode('ascii')) header = { 'Content-type': self.content_type, 'Key': self._key, 'Sign': sign.hexdigest() } return Request(self.base, data, header)
def compute_signature(self, nb): """Compute a notebook's signature by hashing the entire contents of the notebook via HMAC digest. """ hmac = HMAC(self.secret, digestmod=self.digestmod) # don't include the previous hash in the content to hash with signature_removed(nb): # sign the whole thing for b in yield_everything(nb): hmac.update(b) return hmac.hexdigest()
def generate_signature(key, message): """ Generate a signature for an utf8-encoded payload. Similar implementations: - https://developer.github.com/webhooks/securing/ - https://stripe.com/docs/webhooks#signatures """ from hashlib import sha256 from hmac import HMAC timestamp = int(datetime.now().timestamp()) message = "{t}.{message}".format(t=timestamp, message=message) mac = HMAC(key, message.encode("utf-8"), digestmod=sha256) return "t={t}, sha256={sha256}".format(t=timestamp, sha256=mac.hexdigest())
def dynamic_truncation(raw_key: hmac.HMAC, length: int) -> str: """ Convert a hash into a binary string, then into an integer Args: raw_key (hmac.HMAC) length (int) Returns: str """ bitstring = bin(int(raw_key.hexdigest(), base=16)) last_four_bits = bitstring[-4:] offset = int(last_four_bits, base=2) chosen_32_bits = bitstring[offset * 8:offset * 8 + 32] full_totp = str(int(chosen_32_bits, base=2)) return full_totp[-length:]
def send_status(session,msg_type='doorspush'): if not msg_type in ['doorspush','doorsbeat']: raise ValueError('msg_type must be "doorspush" or "doorsbeat" not "{}"'.format(msg_type)) stat=get_status(session) is_open=None if stat.req_type=='open': is_open=True if stat.req_type=='close': is_open=False changed_on=stat.date.isoformat() payload={'type':msg_type,'open':is_open,'changed_on':changed_on} data=json.dumps({'client_id':config.fablab_client_id,'created_on':datetime.now(utc).isoformat(),'payload':payload}).encode('UTF-8') hmac=HMAC(msg=data,key=config.fablab_client_key.encode('UTF-8')) postdata=json.dumps({'hmac':hmac.hexdigest(),'data':data.decode('UTF-8')}) try: req=urlopen(config.api_addr,data=postdata.encode('UTF-8')) except HTTPError as e: return (e) return req
def test_signature_generation(): message = b"Hello world" key = b"hunter2" signature = generate_signature(key, message) ts, sha = signature.split(", ") sre = re.match(r"t=(\d+)", ts) assert sre t = int(sre.group(1)) sre = re.match(r"sha256=([a-f0-9]{64})", sha) assert sre sha = sre.group(1) # check the signature expected_msg = "{t}.{message}".format(t=t, message=message).encode("utf-8") expected_sig = HMAC(key, expected_msg, digestmod=sha256) assert sha == expected_sig.hexdigest()
def anonymize(value): key = settings.SECRET_KEY.encode("utf-8") h = HMAC(key, str(value).encode("utf-8"), digestmod=sha256) return h.hexdigest()