本文整理匯總了Python中hmac.HMAC屬性的典型用法代碼示例。如果您正苦於以下問題:Python hmac.HMAC屬性的具體用法?Python hmac.HMAC怎麽用?Python hmac.HMAC使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類hmac
的用法示例。
在下文中一共展示了hmac.HMAC屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _hi
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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')
示例2: _authenticate_cram_md5
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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)
示例3: generate_sas_token
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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)
示例4: test_legacy_block_size_warnings
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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')
示例5: _buildIoTHubSasToken
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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)
示例6: _hi
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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')
示例7: _authenticate_cram_md5
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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)
示例8: _hmacedString
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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()
示例9: makeMAC
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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()
示例10: verify
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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
示例11: _hi
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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')
示例12: _authenticate_cram_md5
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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)
示例13: _generate_sas_token
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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)
示例14: _build_token
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
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
示例15: _create_mac
# 需要導入模塊: import hmac [as 別名]
# 或者: from hmac import HMAC [as 別名]
def _create_mac(key, msg, method):
if callable(method):
return hmac.HMAC(key, msg, method)
def hashfunc(d=b""):
return hashlib.new(method, d)
# Python 2.7 used ``hasattr(digestmod, '__call__')``
# to detect if hashfunc is callable
hashfunc.__call__ = hashfunc
return hmac.HMAC(key, msg, hashfunc)