本文整理汇总了Python中hmac.digest方法的典型用法代码示例。如果您正苦于以下问题:Python hmac.digest方法的具体用法?Python hmac.digest怎么用?Python hmac.digest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hmac
的用法示例。
在下文中一共展示了hmac.digest方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rootxprv_from_seed
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def rootxprv_from_seed(seed: Octets, version: Optional[Octets] = None) -> bytes:
"""Return BIP32 root master extended private key from seed."""
seed = bytes_from_octets(seed)
hd = hmac.digest(b"Bitcoin seed", seed, "sha512")
k = b"\x00" + hd[:32]
if version is None:
v = NETWORKS["mainnet"]["bip32_prv"]
else:
v = bytes_from_octets(version)
if v not in _XPRV_VERSIONS_ALL:
raise ValueError(f"unknown extended private key version {v!r}")
d: BIP32KeyDict = {
"version": v,
"depth": 0,
"parent_fingerprint": b"\x00\x00\x00\x00",
"index": b"\x00\x00\x00\x00",
"chain_code": hd[32:],
"key": k,
}
return serialize(d)
示例2: add_auth
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def add_auth(self, req, **kwargs):
"""
Add AWS3 authentication to a request.
:type req: :class`boto.connection.HTTPRequest`
:param req: The HTTPRequest object.
"""
# This could be a retry. Make sure the previous
# authorization header is removed first.
if 'X-Amzn-Authorization' in req.headers:
del req.headers['X-Amzn-Authorization']
req.headers['X-Amz-Date'] = formatdate(usegmt=True)
if self._provider.security_token:
req.headers['X-Amz-Security-Token'] = self._provider.security_token
string_to_sign, headers_to_sign = self.string_to_sign(req)
boto.log.debug('StringToSign:\n%s' % string_to_sign)
hash_value = sha256(string_to_sign.encode('utf-8')).digest()
b64_hmac = self.sign_string(hash_value)
s = "AWS3 AWSAccessKeyId=%s," % self._provider.access_key
s += "Algorithm=%s," % self.algorithm()
s += "SignedHeaders=%s," % ';'.join(headers_to_sign)
s += "Signature=%s" % b64_hmac
req.headers['X-Amzn-Authorization'] = s
示例3: _calc_signature
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def _calc_signature(self, params, verb, path, server_name):
boto.log.debug('using _calc_signature_2')
string_to_sign = '%s\n%s\n%s\n' % (verb, server_name.lower(), path)
if self._hmac_256:
hmac = self._hmac_256.copy()
params['SignatureMethod'] = 'HmacSHA256'
else:
hmac = self._hmac.copy()
params['SignatureMethod'] = 'HmacSHA1'
keys = params.keys()
keys.sort()
pairs = []
for key in keys:
val = boto.utils.get_utf8_value(params[key])
pairs.append(urllib.quote(key, safe='') + '=' +
urllib.quote(val, safe='-_~'))
qs = '&'.join(pairs)
boto.log.debug('query string: %s' % qs)
string_to_sign += qs
boto.log.debug('string_to_sign: %s' % string_to_sign)
hmac.update(string_to_sign)
b64 = base64.b64encode(hmac.digest())
boto.log.debug('len(b64)=%d' % len(b64))
boto.log.debug('base64 encoded digest: %s' % b64)
return (qs, b64)
示例4: hash
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def hash(self, msg: bytes) -> bytes:
return hmac.digest(self._cookie, msg, self.digest)
示例5: _ckd
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def _ckd(d: ExtendedBIP32KeyDict, index: bytes) -> None:
# d is a prvkey
if d["key"][0] == 0:
d["depth"] += 1
Pbytes = bytes_from_point(mult(d["q"]))
d["parent_fingerprint"] = hash160(Pbytes)[:4]
d["index"] = index
if index[0] >= 0x80: # hardened derivation
h = hmac.digest(d["chain_code"], d["key"] + index, "sha512")
else: # normal derivation
h = hmac.digest(d["chain_code"], Pbytes + index, "sha512")
d["chain_code"] = h[32:]
offset = int.from_bytes(h[:32], byteorder="big")
d["q"] = (d["q"] + offset) % ec.n
d["key"] = b"\x00" + d["q"].to_bytes(32, "big")
d["Q"] = INF
# d is a pubkey
else:
if index[0] >= 0x80:
raise ValueError("hardened derivation from pubkey is impossible")
d["depth"] += 1
d["parent_fingerprint"] = hash160(d["key"])[:4]
d["index"] = index
h = hmac.digest(d["chain_code"], d["key"] + index, "sha512")
d["chain_code"] = h[32:]
offset = int.from_bytes(h[:32], byteorder="big")
Offset = mult(offset)
d["Q"] = ec.add(d["Q"], Offset)
d["key"] = bytes_from_point(d["Q"])
d["q"] = 0
示例6: crack_prvkey
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def crack_prvkey(parent_xpub: BIP32Key, child_xprv: BIP32Key) -> bytes:
if isinstance(parent_xpub, dict):
p = copy.copy(parent_xpub)
else:
p = deserialize(parent_xpub)
if p["key"][0] not in (2, 3):
m = "extended parent key is not a public key: "
m += f"{serialize(p).decode()}"
raise ValueError(m)
if isinstance(child_xprv, dict):
c = child_xprv
else:
c = deserialize(child_xprv)
if c["key"][0] != 0:
m = f"extended child key is not a private key: {serialize(c).decode()}"
raise ValueError(m)
# check depth
if c["depth"] != p["depth"] + 1:
raise ValueError("not a parent's child: wrong depths")
# check fingerprint
if c["parent_fingerprint"] != hash160(p["key"])[:4]:
raise ValueError("not a parent's child: wrong parent fingerprint")
# check normal derivation
if c["index"][0] >= 0x80:
raise ValueError("hardened child derivation")
p["version"] = c["version"]
h = hmac.digest(p["chain_code"], p["key"] + c["index"], "sha512")
child_q = int.from_bytes(c["key"][1:], byteorder="big")
offset = int.from_bytes(h[:32], byteorder="big")
parent_q = (child_q - offset) % ec.n
p["key"] = b"\x00" + parent_q.to_bytes(32, byteorder="big")
return serialize(p)
示例7: generate_hmac
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def generate_hmac(self, secret_key, counter):
"""Create a 160-bit HMAC from secret and counter.
Args:
secret_key: a byte string (recommended minimum 20 bytes) that is
the shared secret between the client and server.
counter: an integer value represented in an 8-byte string with
the most significant byte first and least significant byte
last
Returns:
The HMAC digest; a byte string, 20 bytes long.
Raises:
TypeError: if the counter and secret are not byte strings.
ValueError: if the counter is not 8 bytes long.
"""
from hashlib import sha1
import hmac
if not isinstance(secret_key, bytes):
raise TypeError('secret_key must be a byte string')
if not isinstance(counter, bytes):
raise TypeError('counter must be a byte string')
if (8 != len(counter)):
raise ValueError('counter must be 8 bytes')
hmac = hmac.new(secret_key, counter, sha1)
hash = hmac.digest()
return hash
示例8: sign_string
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def sign_string(self, string_to_sign):
new_hmac = self._get_hmac()
new_hmac.update(string_to_sign.encode('utf-8'))
return encodebytes(new_hmac.digest()).decode('utf-8').strip()
示例9: _sign
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def _sign(self, key, msg, hex=False):
if not isinstance(key, bytes):
key = key.encode('utf-8')
if hex:
sig = hmac.new(key, msg.encode('utf-8'), sha256).hexdigest()
else:
sig = hmac.new(key, msg.encode('utf-8'), sha256).digest()
return sig
示例10: _calc_signature
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def _calc_signature(self, params, *args):
boto.log.debug('using _calc_signature_0')
hmac = self._get_hmac()
s = params['Action'] + params['Timestamp']
hmac.update(s.encode('utf-8'))
keys = params.keys()
keys.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
pairs = []
for key in keys:
val = boto.utils.get_utf8_value(params[key])
pairs.append(key + '=' + urllib.parse.quote(val))
qs = '&'.join(pairs)
return (qs, base64.b64encode(hmac.digest()))
示例11: sign_string
# 需要导入模块: import hmac [as 别名]
# 或者: from hmac import digest [as 别名]
def sign_string(self, string_to_sign):
boto.log.debug('Canonical: %s' % string_to_sign)
if self._hmac_256:
hmac = self._hmac_256.copy()
else:
hmac = self._hmac.copy()
hmac.update(string_to_sign)
return base64.encodestring(hmac.digest()).strip()