本文整理匯總了Python中hmac.new方法的典型用法代碼示例。如果您正苦於以下問題:Python hmac.new方法的具體用法?Python hmac.new怎麽用?Python hmac.new使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類hmac
的用法示例。
在下文中一共展示了hmac.new方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: client_on_connect
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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")
示例2: handle
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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)
示例3: _got_rakp3
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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)
示例4: _save_service_config
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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
示例5: test_admin_can_create_release
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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)
示例6: test_release_no_change
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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)
示例7: app_sign
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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
示例8: cmd_create
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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
)
示例9: digest
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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()
示例10: _oauth_get_user_future
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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)
示例11: _oauth10a_signature
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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]
示例12: _oauth_signature
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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]
示例13: process_challenge
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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
示例14: __init__
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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,
)
示例15: serialize
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import new [as 別名]
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)])