Python hmac.new() Examples
The following are 30
code examples of hmac.new().
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: utils.py From wechatpy with MIT License | 7 votes |
def calculate_signature_hmac(params, api_key): url = format_url(params, api_key) sign = to_text(hmac.new(api_key.encode(), msg=url, digestmod=hashlib.sha256).hexdigest().upper()) return sign
Example #2
Source File: auth.py From tornado-zh with MIT License | 6 votes |
def _oauth_get_user_future(self, access_token, callback): """Subclasses must override this to get basic information about the user. Should return a `.Future` whose result is a dictionary containing information about the user, which may have been retrieved by using ``access_token`` to make a request to the service. The access token will be added to the returned dictionary to make the result of `get_authenticated_user`. For backwards compatibility, the callback-based ``_oauth_get_user`` method is also supported. """ # By default, call the old-style _oauth_get_user, but new code # should override this method instead. self._oauth_get_user(access_token, callback)
Example #3
Source File: github.py From Matrix-NEB with Apache License 2.0 | 6 votes |
def cmd_create(self, event, *args): """Create a new issue. Format: 'create <owner/repo> <title> <desc(optional)>' E.g. 'create matrix-org/synapse A bug goes here 'create matrix-org/synapse "Title here" "desc here" """ if not args or len(args) < 2: return self.cmd_create.__doc__ project = args[0] others = args[1:] # others must contain a title, may contain a description. If it contains # a description, it MUST be in [1] and be longer than 1 word. title = ' '.join(others) desc = "" try: possible_desc = others[1] if ' ' in possible_desc: desc = possible_desc title = others[0] except: pass return self._create_issue( event["user_id"], project, title, desc )
Example #4
Source File: auth.py From wechat-analyse with MIT License | 6 votes |
def app_sign(self, expired=0): if not self._secret_id or not self._secret_key: return self.AUTH_SECRET_ID_KEY_ERROR puserid = '' if self._userid != '': if len(self._userid) > 64: return self.AUTH_URL_FORMAT_ERROR puserid = self._userid now = int(time.time()) rdm = random.randint(0, 999999999) plain_text = 'a=' + self._appid + '&k=' + self._secret_id + '&e=' + str(expired) + '&t=' + str(now) + '&r=' + str(rdm) + '&u=' + puserid + '&f=' bin = hmac.new(self._secret_key.encode(), plain_text.encode(), hashlib.sha1) s = bin.hexdigest() s = binascii.unhexlify(s) s = s + plain_text.encode('ascii') signature = base64.b64encode(s).rstrip() #生成签名 return signature
Example #5
Source File: key.py From rift-python with Apache License 2.0 | 6 votes |
def digest(self, message_parts): if self.key_id == 0: assert self.algorithm == "null" return b'' elif "hmac" in self.algorithm: assert self.algorithm in ALGORITHMS digestmod = ALGORITHM_TO_DIGESTMOD[self.algorithm] the_hmac = hmac.new(self.secret.encode(), digestmod=digestmod) for message_part in message_parts: if message_part is not None: the_hmac.update(message_part) return the_hmac.digest() else: assert self.algorithm in ALGORITHMS digestmod = ALGORITHM_TO_DIGESTMOD[self.algorithm] the_hash = hashlib.new(name=digestmod) the_hash.update(self.secret.encode()) for message_part in message_parts: if message_part is not None: the_hash.update(message_part) return the_hash.digest()
Example #6
Source File: aws_srp.py From warrant with Apache License 2.0 | 6 votes |
def process_challenge(self, challenge_parameters): user_id_for_srp = challenge_parameters['USER_ID_FOR_SRP'] salt_hex = challenge_parameters['SALT'] srp_b_hex = challenge_parameters['SRP_B'] secret_block_b64 = challenge_parameters['SECRET_BLOCK'] # re strips leading zero from a day number (required by AWS Cognito) timestamp = re.sub(r" 0(\d) ", r" \1 ", datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S UTC %Y")) hkdf = self.get_password_authentication_key(user_id_for_srp, self.password, hex_to_long(srp_b_hex), salt_hex) secret_block_bytes = base64.standard_b64decode(secret_block_b64) msg = bytearray(self.pool_id.split('_')[1], 'utf-8') + bytearray(user_id_for_srp, 'utf-8') + \ bytearray(secret_block_bytes) + bytearray(timestamp, 'utf-8') hmac_obj = hmac.new(hkdf, msg, digestmod=hashlib.sha256) signature_string = base64.standard_b64encode(hmac_obj.digest()) response = {'TIMESTAMP': timestamp, 'USERNAME': user_id_for_srp, 'PASSWORD_CLAIM_SECRET_BLOCK': secret_block_b64, 'PASSWORD_CLAIM_SIGNATURE': signature_string.decode('utf-8')} if self.client_secret is not None: response.update({ "SECRET_HASH": self.get_secret_hash(self.username, self.client_id, self.client_secret)}) return response
Example #7
Source File: test_release.py From controller with MIT License | 6 votes |
def test_release_no_change(self, mock_requests): """ Test that a release is created when an app is created, and then has 2 identical config set, causing a 409 as there was no change """ app_id = self.create_app() # check that updating config rolls a new release url = '/v2/apps/{app_id}/config'.format(**locals()) body = {'values': json.dumps({'NEW_URL1': 'http://localhost:8080/'})} response = self.client.post(url, body) self.assertEqual(response.status_code, 201, response.data) self.assertIn('NEW_URL1', response.data['values']) # trigger identical release url = '/v2/apps/{app_id}/config'.format(**locals()) body = {'values': json.dumps({'NEW_URL1': 'http://localhost:8080/'})} response = self.client.post(url, body) self.assertEqual(response.status_code, 409, response.data)
Example #8
Source File: test_release.py From controller with MIT License | 6 votes |
def test_admin_can_create_release(self, mock_requests): """If a non-user creates an app, an admin should be able to create releases.""" user = User.objects.get(username='autotest2') token = Token.objects.get(user=user).key self.client.credentials(HTTP_AUTHORIZATION='Token ' + token) app_id = self.create_app() # check that updating config rolls a new release url = '/v2/apps/{app_id}/config'.format(**locals()) body = {'values': json.dumps({'NEW_URL1': 'http://localhost:8080/'})} self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) response = self.client.post(url, body) self.assertEqual(response.status_code, 201, response.data) self.assertIn('NEW_URL1', response.data['values']) # check to see that an initial release was created url = '/v2/apps/{app_id}/releases'.format(**locals()) response = self.client.get(url) self.assertEqual(response.status_code, 200, response.data) # account for the config release as well self.assertEqual(response.data['count'], 2)
Example #9
Source File: auth.py From tornado-zh with MIT License | 6 votes |
def _oauth10a_signature(consumer_token, method, url, parameters={}, token=None): """Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request. See http://oauth.net/core/1.0a/#signing_process """ parts = urlparse.urlparse(url) scheme, netloc, path = parts[:3] normalized_url = scheme.lower() + "://" + netloc.lower() + path base_elems = [] base_elems.append(method.upper()) base_elems.append(normalized_url) base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v))) for k, v in sorted(parameters.items()))) base_string = "&".join(_oauth_escape(e) for e in base_elems) key_elems = [escape.utf8(urllib_parse.quote(consumer_token["secret"], safe='~'))] key_elems.append(escape.utf8(urllib_parse.quote(token["secret"], safe='~') if token else "")) key = b"&".join(key_elems) hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1) return binascii.b2a_base64(hash.digest())[:-1]
Example #10
Source File: auth.py From tornado-zh with MIT License | 6 votes |
def _oauth_signature(consumer_token, method, url, parameters={}, token=None): """Calculates the HMAC-SHA1 OAuth signature for the given request. See http://oauth.net/core/1.0/#signing_process """ parts = urlparse.urlparse(url) scheme, netloc, path = parts[:3] normalized_url = scheme.lower() + "://" + netloc.lower() + path base_elems = [] base_elems.append(method.upper()) base_elems.append(normalized_url) base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v))) for k, v in sorted(parameters.items()))) base_string = "&".join(_oauth_escape(e) for e in base_elems) key_elems = [escape.utf8(consumer_token["secret"])] key_elems.append(escape.utf8(token["secret"] if token else "")) key = b"&".join(key_elems) hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1) return binascii.b2a_base64(hash.digest())[:-1]
Example #11
Source File: __init__.py From controller with MIT License | 6 votes |
def _save_service_config(self, app, component, data): # fetch setvice definition with minimum structure svc = self._fetch_service_config(app) # always assume a .deis.io ending component = "%s.deis.io/" % component # add component to data and flatten data = {"%s%s" % (component, key): value for key, value in list(data.items()) if value} svc['metadata']['annotations'].update(morph.flatten(data)) # Update the k8s service for the application with new service information try: self._scheduler.svc.update(app, app, svc) except KubeException as e: raise ServiceUnavailable('Could not update Kubernetes Service {}'.format(app)) from e
Example #12
Source File: ipmisim.py From ipmisim with Apache License 2.0 | 6 votes |
def _got_rakp3(self, data): RmRc = struct.pack('B' * len(self.Rm + self.Rc), *(self.Rm + self.Rc)) self.sik = hmac.new(self.kg, RmRc + struct.pack("2B", self.rolem, len(self.username)) + self.username, hashlib.sha1).digest() self.session.k1 = hmac.new(self.sik, '\x01' * 20, hashlib.sha1).digest() self.session.k2 = hmac.new(self.sik, '\x02' * 20, hashlib.sha1).digest() self.session.aeskey = self.session.k2[0:16] hmacdata = struct.pack('B' * len(self.Rc), *self.Rc) + struct.pack("4B", *self.clientsessionid) +\ struct.pack("2B", self.rolem, len(self.username)) + self.username expectedauthcode = hmac.new(self.kuid, hmacdata, hashlib.sha1).digest() authcode = struct.pack("%dB" % len(data[8:]), *data[8:]) if expectedauthcode != authcode: self.close_server_session() return clienttag = data[0] if data[1] != 0: self.close_server_session() return self.session.localsid = struct.unpack('<I', struct.pack('4B', *self.managedsessionid))[0] logger.debug('IPMI rakp3 request') self.session.ipmicallback = self.handle_client_request self._send_rakp4(clienttag, 0)
Example #13
Source File: ipmisim.py From ipmisim with Apache License 2.0 | 6 votes |
def handle(self, data, address, socket): self.sock = socket # make sure self.session exists if not (address[0] in self.sessions.keys() and self.sessions[address[0]].port == address[1]) or not hasattr(self, 'session'): # new session for new source logger.info('New IPMI traffic from %s', address) self.session = FakeSession(address[0], "", "", address[1]) self.session.server = self self.uuid = uuid.uuid4() self.kg = None if not hasattr(self, 'session') or not self.session: return self.session.socket = self.sock self.sessions[address[0]] = self.session self.initiate_session(data, address, self.session) else: # session already exists logger.debug('Incoming IPMI traffic from %s', address) if self.session.stage == 0: self.close_server_session() else: self._got_request(data, address, self.session)
Example #14
Source File: securecookie.py From recruit with Apache License 2.0 | 6 votes |
def serialize(self, expires=None): """Serialize the secure cookie into a string. If expires is provided, the session will be automatically invalidated after expiration when you unseralize it. This provides better protection against session cookie theft. :param expires: an optional expiration date for the cookie (a :class:`datetime.datetime` object) """ if self.secret_key is None: raise RuntimeError("no secret key defined") if expires: self["_expires"] = _date_to_unix(expires) result = [] mac = hmac(self.secret_key, None, self.hash_method) for key, value in sorted(self.items()): result.append( ( "%s=%s" % (url_quote_plus(key), self.quote(value).decode("ascii")) ).encode("ascii") ) mac.update(b"|" + result[-1]) return b"?".join([base64.b64encode(mac.digest()).strip(), b"&".join(result)])
Example #15
Source File: auth.py From tornado-zh with MIT License | 6 votes |
def _oauth10a_signature(consumer_token, method, url, parameters={}, token=None): """Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request. See http://oauth.net/core/1.0a/#signing_process """ parts = urlparse.urlparse(url) scheme, netloc, path = parts[:3] normalized_url = scheme.lower() + "://" + netloc.lower() + path base_elems = [] base_elems.append(method.upper()) base_elems.append(normalized_url) base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v))) for k, v in sorted(parameters.items()))) base_string = "&".join(_oauth_escape(e) for e in base_elems) key_elems = [escape.utf8(urllib_parse.quote(consumer_token["secret"], safe='~'))] key_elems.append(escape.utf8(urllib_parse.quote(token["secret"], safe='~') if token else "")) key = b"&".join(key_elems) hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1) return binascii.b2a_base64(hash.digest())[:-1]
Example #16
Source File: securecookie.py From recruit with Apache License 2.0 | 6 votes |
def __init__(self, data=None, secret_key=None, new=True): ModificationTrackingDict.__init__(self, data or ()) # explicitly convert it into a bytestring because python 2.6 # no longer performs an implicit string conversion on hmac if secret_key is not None: secret_key = to_bytes(secret_key, "utf-8") self.secret_key = secret_key self.new = new if self.serialization_method is pickle: warnings.warn( "The default 'SecureCookie.serialization_method' will" " change from pickle to json in version 1.0. To upgrade" " existing tokens, override 'unquote' to try pickle if" " json fails.", stacklevel=2, )
Example #17
Source File: client.py From microgear-python with ISC License | 6 votes |
def client_on_connect(client, userdata, rc): global block microgear.state = True logging.info("Connected with result code "+str(rc)) if rc == 0 : on_connect() auto_subscribeAndpublish() elif rc == 1 : logging.warning("Unable to connect: Incorrect protocol version.") elif rc == 2 : logging.warning("Unable to connect: Invalid client identifier.") elif rc == 3 : logging.warning("Unable to connect: Server unavailable.") elif rc == 4 : unsubscribe(current_id) microgear.mqtt_client.disconnect() on_info("Invalid credential.") logging.info("Unable to connect: Invalid credential, requesting new one") resettoken() connect(block_loop) elif rc == 5 : on_warning("Not authorised.") logging.warning("Unable to connect: Not authorised.") else: logging.warning("Unable to connect: Unknown reason")
Example #18
Source File: RSA-AES-MD5-DES-DES3-MD5-SHA-HMAC.py From R-A-M-D-D3-S-M-H with MIT License | 5 votes |
def encrypt(self, text): """ 传入明文 :param text:bytes类型,长度是KEY的倍数 :return: """ if not isinstance(text, bytes): text = bytes(text, 'utf-8') x = len(text) % 8 text = text+b'\0'*x cryptor = DES3.new(self.key, self.mode) ciphertext = cryptor.encrypt(text) return ciphertext
Example #19
Source File: RSA-AES-MD5-DES-DES3-MD5-SHA-HMAC.py From R-A-M-D-D3-S-M-H with MIT License | 5 votes |
def aes(self): return AES.new(self.key, AES.MODE_ECB) # 初始化加密器
Example #20
Source File: __init__.py From bugbuzz-python with MIT License | 5 votes |
def decrypt(self, key, msg): from Crypto.Cipher import AES try: secret = self.getSecret(key) Initial16bytes = '0123456789012345' cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes) plain = self.depad(cipher.decrypt(decodestring(msg))) except: return msg try: return eval(plain) except SyntaxError: return plain
Example #21
Source File: aws_srp.py From warrant with Apache License 2.0 | 5 votes |
def compute_hkdf(ikm, salt): """ Standard hkdf algorithm :param {Buffer} ikm Input key material. :param {Buffer} salt Salt value. :return {Buffer} Strong key material. @private """ prk = hmac.new(salt, ikm, hashlib.sha256).digest() info_bits_update = info_bits + bytearray(chr(1), 'utf-8') hmac_hash = hmac.new(prk, info_bits_update, hashlib.sha256).digest() return hmac_hash[:16]
Example #22
Source File: __init__.py From bugbuzz-python with MIT License | 5 votes |
def _pam_sign(self, msg): return urlsafe_b64encode(hmac.new( self.secret_key.encode("utf-8"), msg.encode("utf-8"), sha256 ).digest())
Example #23
Source File: __init__.py From bugbuzz-python with MIT License | 5 votes |
def decrypt(self, key, msg): from Crypto.Cipher import AES secret = self.getSecret(key) Initial16bytes = '0123456789012345' cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes) return (cipher.decrypt( decodestring(msg.encode('utf-8')))).decode('utf-8')
Example #24
Source File: __init__.py From bugbuzz-python with MIT License | 5 votes |
def encrypt(self, key, msg): from Crypto.Cipher import AES secret = self.getSecret(key) Initial16bytes = '0123456789012345' cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes) return encodestring( cipher.encrypt(self.pad(msg.encode('utf-8')))).decode('utf-8')
Example #25
Source File: __init__.py From bugbuzz-python with MIT License | 5 votes |
def decrypt(self, key, msg): from Crypto.Cipher import AES try: secret = self.getSecret(key) Initial16bytes = '0123456789012345' cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes) plain = self.depad(cipher.decrypt(decodestring(msg))) except: return msg try: return eval(plain) except SyntaxError: return plain
Example #26
Source File: __init__.py From bugbuzz-python with MIT License | 5 votes |
def encrypt(self, key, msg): from Crypto.Cipher import AES secret = self.getSecret(key) Initial16bytes = '0123456789012345' cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes) enc = encodestring(cipher.encrypt(self.pad(msg))) return enc
Example #27
Source File: web.py From tornado-zh with MIT License | 5 votes |
def add_handlers(self, host_pattern, host_handlers): """添加给定的handler到我们的handler表. Host 模式将按照它们的添加顺序进行处理. 所有匹配模式将被考虑. """ if not host_pattern.endswith("$"): host_pattern += "$" handlers = [] # The handlers with the wildcard host_pattern are a special # case - they're added in the constructor but should have lower # precedence than the more-precise handlers added later. # If a wildcard handler group exists, it should always be last # in the list, so insert new groups just before it. if self.handlers and self.handlers[-1][0].pattern == '.*$': self.handlers.insert(-1, (re.compile(host_pattern), handlers)) else: self.handlers.append((re.compile(host_pattern), handlers)) for spec in host_handlers: if isinstance(spec, (tuple, list)): assert len(spec) in (2, 3, 4) spec = URLSpec(*spec) handlers.append(spec) if spec.name: if spec.name in self.named_handlers: app_log.warning( "Multiple handlers named %s; replacing previous value", spec.name) self.named_handlers[spec.name] = spec
Example #28
Source File: web.py From tornado-zh with MIT License | 5 votes |
def transform_first_chunk(self, status_code, headers, chunk, finishing): if 'Vary' in headers: headers['Vary'] += b', Accept-Encoding' else: headers['Vary'] = b'Accept-Encoding' if self._gzipping: ctype = _unicode(headers.get("Content-Type", "")).split(";")[0] self._gzipping = self._compressible_type(ctype) and \ (not finishing or len(chunk) >= self.MIN_LENGTH) and \ ("Content-Encoding" not in headers) if self._gzipping: headers["Content-Encoding"] = "gzip" self._gzip_value = BytesIO() self._gzip_file = gzip.GzipFile(mode="w", fileobj=self._gzip_value, compresslevel=self.GZIP_LEVEL) chunk = self.transform_chunk(chunk, finishing) if "Content-Length" in headers: # The original content length is no longer correct. # If this is the last (and only) chunk, we can set the new # content-length; otherwise we remove it and fall back to # chunked encoding. if finishing: headers["Content-Length"] = str(len(chunk)) else: del headers["Content-Length"] return status_code, headers, chunk
Example #29
Source File: web.py From tornado-zh with MIT License | 5 votes |
def _create_signature_v1(secret, *parts): hash = hmac.new(utf8(secret), digestmod=hashlib.sha1) for part in parts: hash.update(utf8(part)) return utf8(hash.hexdigest())
Example #30
Source File: web.py From tornado-zh with MIT License | 5 votes |
def _create_signature_v2(secret, s): hash = hmac.new(utf8(secret), digestmod=hashlib.sha256) hash.update(utf8(s)) return utf8(hash.hexdigest())