本文整理匯總了Python中hashlib.sha384方法的典型用法代碼示例。如果您正苦於以下問題:Python hashlib.sha384方法的具體用法?Python hashlib.sha384怎麽用?Python hashlib.sha384使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類hashlib
的用法示例。
在下文中一共展示了hashlib.sha384方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: sri_hash
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def sri_hash(data, url_safe=False):
"""
Return a subresource integrity attribute string for a file
containing the given binary data.
SRI attributes are a string of the form "{algorithm}-{hash}", where
{algorithm} is the hash algorithm, and {hash} is a base64-encoded
hash of the data using the specified algorithm.
:param data:
Bytes-like object containing the data to hash.
"""
digest = sha384(data).digest()
if url_safe:
data_hash = urlsafe_b64encode(digest)
else:
data_hash = b64encode(digest)
return "sha384-" + data_hash.decode()
示例2: test_rfc_6979
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def test_rfc_6979(self):
msg = 'sample'
x = 0x09A4D6792295A7F730FC3F2B49CBC0F62E862272F
q = 0x4000000000000000000020108A2E0CC0D99F8A5EF
expected = 0x09744429FA741D12DE2BE8316E35E84DB9E5DF1CD
nonce = RFC6979(msg, x, q, sha1).gen_nonce()
self.assertTrue(nonce == expected)
expected = 0x323E7B28BFD64E6082F5B12110AA87BC0D6A6E159
nonce = RFC6979(msg, x, q, sha224).gen_nonce()
self.assertTrue(nonce == expected)
expected = 0x23AF4074C90A02B3FE61D286D5C87F425E6BDD81B
nonce = RFC6979(msg, x, q, sha256).gen_nonce()
self.assertTrue(nonce == expected)
expected = 0x2132ABE0ED518487D3E4FA7FD24F8BED1F29CCFCE
nonce = RFC6979(msg, x, q, sha384).gen_nonce()
self.assertTrue(nonce == expected)
expected = 0x00BBCC2F39939388FDFE841892537EC7B1FF33AA3
nonce = RFC6979(msg, x, q, sha512).gen_nonce()
self.assertTrue(nonce == expected)
示例3: sendIcoBenchRequest
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def sendIcoBenchRequest(cls, queryParams=(), pathParams={}, data=()):
hash = hmac.new(cls.icoBenchApi["ICOBENCH_PRIVATE_KEY"].encode('utf-8'), ''.encode('utf-8'), hashlib.sha384)
dataJSON = json.dumps(data)
hash.update(dataJSON.encode('utf-8'))
sign = hash.digest()
sign = base64.b64encode(sign)
request_headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-ICObench-Key': cls.icoBenchApi["ICOBENCH_PUBLIC_KEY"],
'X-ICObench-Sig': sign
}
url = cls.icoBenchApi["API_URL"];
for val in pathParams:
url = url + val + "/"
if all(queryParams) and url.endswith('/'):
url = url[:-1]
dataJSON = json.dumps(data)
response = requests.post(url=url, params=queryParams, data=dataJSON, headers=request_headers)
return response.json()
示例4: main
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def main(text, hashType):
encoder = text.encode('utf_8')
myHash = ''
if hashType.lower() == 'md5':
myHash = hashlib.md5(encoder).hexdigest()
elif hashType.lower() == 'sha1':
myHash = hashlib.sha1(encoder).hexdigest()
elif hashType.lower() == 'sha224':
myHash = hashlib.sha224(encoder).hexdigest()
elif hashType.lower() == 'sha256':
myHash = hashlib.sha256(encoder).hexdigest()
elif hashType.lower() == 'sha384':
myHash = hashlib.sha384(encoder).hexdigest()
elif hashType.lower() == 'sha512':
myHash = hashlib.sha512(encoder).hexdigest()
else:
print('[!] The script does not support this hash type')
exit(0)
print("Your hash is: ", myHash)
示例5: _model_dir_path
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def _model_dir_path(self):
if self.parent.config.directory is None:
return None
_to_hash = self.features + [
self.classification,
str(len(self.cids)),
self.parent.config.model_path,
]
model = hashlib.sha384("".join(_to_hash).encode("utf-8")).hexdigest()
# Needed to save updated model
if not os.path.isdir(self.parent.config.directory):
raise NotADirectoryError(
"%s is not a directory" % (self.parent.config.directory)
)
os.makedirs(
os.path.join(self.parent.config.directory, model), exist_ok=True
)
return os.path.join(self.parent.config.directory, model)
示例6: _feature_predict_hash
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def _feature_predict_hash(self):
params = sorted(
[
"{}{}".format(k, v)
for k, v in self.parent.config._asdict().items()
if k
not in [
"features",
"predict",
"vwcmd",
"class_cost",
"importance",
"tag",
"base",
]
]
)
params = "".join(params)
return hashlib.sha384(
"".join([params] + self.features).encode()
).hexdigest()
示例7: test_dumpb_loadb
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def test_dumpb_loadb(self):
async with PNGConfigLoader.withconfig({}) as configloader:
async with configloader() as ctx:
image_bytes = (
pathlib.Path(__file__).parent
/ ".."
/ ".."
/ ".."
/ "examples"
/ "MNIST"
/ "image1.png"
).read_bytes()
original = await ctx.loadb(image_bytes)
hash_original = hashlib.sha384(
json.dumps(original.flatten().tolist()).encode()
).hexdigest()
self.assertEqual(original.shape, (280, 280, 3))
self.assertEqual(hash_original, IMAGE1_HASH)
示例8: test_idx3
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def test_idx3(self, filename):
feature_name = "image"
async with IDX3Source(
IDX3SourceConfig(filename=str(filename), feature=feature_name)
) as source:
async with source() as sctx:
records = [record async for record in sctx.records()]
self.assertEqual(len(records), 60000)
self.assertIn(feature_name, records[0].features())
for i in range(-1, 1):
with self.subTest(index=i):
is_hash = hashlib.sha384(
json.dumps(
records[i].feature(feature_name)
).encode()
).hexdigest()
self.assertEqual(is_hash, IDX3_FIRST_LAST[i])
示例9: sha2_384
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def sha2_384(self):
"""Get SHA2-384 hash
The SHA-2 (Secure Hash Algorithm 2) hash functions were designed by the NSA. SHA-2
includes significant changes from its predecessor, SHA-1. The SHA-2 family consists of
hash functions with digests (hash values) that are 224, 256, 384 or 512 bits: SHA224,
SHA256, SHA384, SHA512. SHA-512 operates on 64-bit words. SHA-256 operates on 32-bit
words. SHA-384 is largely identical to SHA-512 but is truncated to 384 bytes. SHA-224
is largely identical to SHA-256 but is truncated to 224 bytes. SHA-512/224 and SHA-512/256
are truncated versions of SHA-512, but the initial values are generated using the method
described in Federal Information Processing Standards (FIPS) PUB 180-4.
Returns:
Chepy: The Chepy object.
"""
self.state = hashlib.sha384(self._convert_to_bytes()).hexdigest()
return self
示例10: sign
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def sign(self, url, endpoint, endpoint_path, method_verb, *args, **kwargs):
try:
req = kwargs['params']
except KeyError:
req = {}
if self.version == 'v1':
req['request'] = endpoint_path
req['nonce'] = self.nonce()
js = json.dumps(req)
data = base64.standard_b64encode(js.encode('utf8'))
else:
data = '/api/' + endpoint_path + self.nonce() + json.dumps(req)
h = hmac.new(self.secret.encode('utf8'), data, hashlib.sha384)
signature = h.hexdigest()
headers = {"X-BFX-APIKEY": self.key,
"X-BFX-SIGNATURE": signature,
"X-BFX-PAYLOAD": data}
if self.version == 'v2':
headers['content-type'] = 'application/json'
return url, {'headers': headers}
示例11: sign
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def sign(self, uri, endpoint, endpoint_path, method_verb, *args, **kwargs):
nonce = self.nonce()
try:
params = kwargs['params']
except KeyError:
params = {}
payload = params
payload['nonce'] = nonce
payload['request'] = endpoint_path
js = json.dumps(payload)
data = base64.standard_b64encode(js.encode('utf8'))
h = hmac.new(self.secret.encode('utf8'), data, hashlib.sha384)
signature = h.hexdigest()
headers = {'X-GEMINI-APIKEY': self.key,
'X-GEMINI-PAYLOAD': data,
'X-GEMINI-SIGNATURE': signature}
return uri, {'headers': headers}
示例12: sign
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def sign(self, uri, endpoint, endpoint_path, method_verb, *args, **kwargs):
nonce = self.nonce()
try:
params = kwargs['params']
except KeyError:
params = {}
payload = params
payload['nonce'] = int(nonce)
payload['request'] = endpoint_path
msg = nonce + uri
sig = hmac.new(self.secret.encode(), msg.encode(), hashlib.sha384).hexdigest()
headers = {'X-TRT-APIKEY': self.key,
'X-TRT-Nonce': nonce,
'X-TRT-SIGNATURE': sig, 'Content-Type': 'application/json'}
return uri, {'headers': headers}
示例13: verify_signature_pubkey
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def verify_signature_pubkey(data, signature, pubkey):
"""
Verify a signature.
If the signature is valid, returns True. If the signature is invalid, raise
an exception explaining why.
"""
# Data must be encoded as bytes
if isinstance(data, str):
data = data.encode()
# Content signature implicitly adds a prefix to signed data
data = b"Content-Signature:\x00" + data
# fastecdsa expects ASCII armored keys, but ours is unarmored. Add the
# armor before passing the key to the library.
EC_PUBLIC_HEADER = "-----BEGIN PUBLIC KEY-----"
EC_PUBLIC_FOOTER = "-----END PUBLIC KEY-----"
verifying_pubkey = PEMEncoder.decode_public_key(
"\n".join([EC_PUBLIC_HEADER, pubkey, EC_PUBLIC_FOOTER])
)
try:
signature = base64.urlsafe_b64decode(signature)
signature = ecdsa.util.sigdecode_string(signature, order=ecdsa.curves.NIST384p.order)
except binascii.Error as e:
if BASE64_WRONG_LENGTH_RE.match(e.args[0]):
raise WrongSignatureSize("Base64 encoded signature was not a multiple of 4")
else:
raise
except ecdsa.util.MalformedSignature:
raise WrongSignatureSize()
verified = fastecdsa.ecdsa.verify(
signature, data, verifying_pubkey, curve=fastecdsa.curve.P384, hashfunc=hashlib.sha384
)
if not verified:
raise SignatureDoesNotMatch()
return True
示例14: test_sha384_rfc4231
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def test_sha384_rfc4231(self):
self._rfc4231_test_cases(hashlib.sha384)
示例15: __init__
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha384 [as 別名]
def __init__(self, apikey, secretkey):
def httpGet(url, resource, params, apikey, secretkey):
nonce = str(int(round(time.time() * 10000)))
params["nonce"] = nonce
params["request"] = resource
data = base64.b64encode(json.dumps(params).encode())
sign = hmac.new(self._secretkey, data, hashlib.sha384).hexdigest()
headers = {
"X-BFX-APIKEY": self._apikey,
"X-BFX-SIGNATURE": sign,
"AX-BFX-PAYLOAD": data,
}
return self.session.get('https://' + url + resource,
headers=headers, data=json.dumps(params)).json()
def httpPost(url, resource, params, apikey, secretkey):
nonce = str(int(round(time.time() * 10000)))
params["nonce"] = nonce
params["request"] = resource
data = base64.b64encode(json.dumps(params).encode())
sign = hmac.new(self._secretkey, data, hashlib.sha384).hexdigest()
headers = {
"X-BFX-APIKEY": self._apikey,
"X-BFX-SIGNATURE": sign,
"AX-BFX-PAYLOAD": data,
}
return self.session.post('https://' + url + resource,
headers=headers, data=json.dumps(params)).json()
super(Bitfinex, self).__init__(apikey, secretkey)
self.session = requests.session()
self.httpPost = httpPost
self.httpGet = httpGet