def GetIntegrity(self, data):
"""Calculate the integirty value of given data using remote peers hash"""
if self.hash_type == None:
return None
elif self.hash_type == 0:
# SHA-1
return hashlib.sha1(data).digest()
elif self.hash_type == 1:
# SHA-224
return hashlib.sha224(data).digest()
elif self.hash_type == 2:
# SHA-256
return hashlib.sha256(data).digest()
elif self.hash_type == 3:
# SHA-384
return hashlib.sha384(data).digest()
elif self.hash_type == 4:
# SHA-512
return hashlib.sha512(data).digest()
else:
return None
python类sha384()的实例源码
def get_hashsums(file_path):
hash_sums = od()
hash_sums['md5sum'] = hashlib.md5()
hash_sums['sha1sum'] = hashlib.sha1()
hash_sums['sha224sum'] = hashlib.sha224()
hash_sums['sha256sum'] = hashlib.sha256()
hash_sums['sha384sum'] = hashlib.sha384()
hash_sums['sha512sum'] = hashlib.sha512()
with open(file_path, 'rb') as fd:
data_chunk = fd.read(1024)
while data_chunk:
for hashsum in hash_sums.keys():
hash_sums[hashsum].update(data_chunk)
data_chunk = fd.read(1024)
results = od()
for key,value in hash_sums.items():
results[key] = value.hexdigest()
return results
def get_digest(value):
"""Return a hashlib digest algorithm from a string."""
if not isinstance(value, str):
return value
value = value.lower()
if value == "md5":
return md5
elif value == "sha1":
return sha1
elif value == "sha224":
return sha224
elif value == "sha256":
return sha256
elif value == "sha384":
return sha384
elif value == "sha512":
return sha512
else:
raise ValueError("Invalid digest algorithm: %s" % value)
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}
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}
def get_digest(value):
"""
Returns a hashlib digest algorithm from a string
"""
if not isinstance(value, str):
return value
value = value.lower()
if value == "md5":
return md5
elif value == "sha1":
return sha1
elif value == "sha224":
return sha224
elif value == "sha256":
return sha256
elif value == "sha384":
return sha384
elif value == "sha512":
return sha512
else:
raise ValueError("Invalid digest algorithm: %s" % value)
def get_digest(value):
"""
Returns a hashlib digest algorithm from a string
"""
if not isinstance(value, str):
return value
value = value.lower()
if value == "md5":
return hashlib.md5
elif value == "sha1":
return hashlib.sha1
elif value == "sha224":
return hashlib.sha224
elif value == "sha256":
return hashlib.sha256
elif value == "sha384":
return hashlib.sha384
elif value == "sha512":
return hashlib.sha512
else:
raise ValueError("Invalid digest algorithm: %s" % value)
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}
def prepare(self, params):
"""
Prepare, return the required HTTP headers.
Base 64 encode the parameters, sign it with the secret key,
create the HTTP headers, return the whole payload.
Arguments:
params -- a dictionary of parameters
"""
jsonparams = json.dumps(params)
payload = base64.b64encode(jsonparams.encode())
signature = hmac.new(self.secret_key.encode(), payload,
hashlib.sha384).hexdigest()
return {'X-GEMINI-APIKEY': self.api_key,
'X-GEMINI-PAYLOAD': payload,
'X-GEMINI-SIGNATURE': signature}
def _sign_payload(self, method, path, params=None, payload=None):
route = build_route(path, params)
nonce = gen_nonce()
if payload:
j = json.dumps(payload).encode('utf-8')
encoded_body = base64.standard_b64encode(j).decode('utf-8')
string = method + ' ' + route + ' ' + encoded_body + ' ' + nonce
else:
string = method + ' ' + route + ' ' + nonce
h = hmac.new(key=self.SECRET.encode('utf-8'),
msg=string.encode('utf-8'),
digestmod=hashlib.sha384)
signature = h.hexdigest()
return {
'X-SBTC-APIKEY': self.KEY,
'X-SBTC-NONCE': nonce,
'X-SBTC-SIGNATURE': signature,
'Content-Type': 'application/json',
}
def _sign_payload(self, path, payload=None):
timestamp = str(int(time.time()))
msg = timestamp + path
if payload:
for value in [str(payload[k]) for k in sorted(payload.keys())]:
msg += value
signature = hmac.new(key=self.SECRET.encode('utf-8'),
msg=msg.encode('utf-8'),
digestmod=hashlib.sha384).hexdigest()
# Request fails with 'get_requests_not_allowed' when
# 'Content-Type': 'application/json' is present
return {
'X-MKT-APIKEY': self.KEY,
'X-MKT-SIGNATURE': signature,
'X-MKT-TIMESTAMP': timestamp,
}
# Request fails with 'get_requests_not_allowed' when
# json.dumps()' is used
def get_digest(value):
"""
Returns a hashlib digest algorithm from a string
"""
if not isinstance(value, str):
return value
value = value.lower()
if value == "md5":
return md5
elif value == "sha1":
return sha1
elif value == "sha224":
return sha224
elif value == "sha256":
return sha256
elif value == "sha384":
return sha384
elif value == "sha512":
return sha512
else:
raise ValueError("Invalid digest algorithm: %s" % value)
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)
def get_digest(value):
"""Return a hashlib digest algorithm from a string."""
if not isinstance(value, str):
return value
value = value.lower()
if value == "md5":
return md5
elif value == "sha1":
return sha1
elif value == "sha224":
return sha224
elif value == "sha256":
return sha256
elif value == "sha384":
return sha384
elif value == "sha512":
return sha512
else:
raise ValueError("Invalid digest algorithm: %s" % value)
def authenticate(u, p):
if u and p:
if u in (current_app.config['ADMIN_MAIL'],):
p_salt = p + current_app.config["SECRET_KEY"]
e_salt = chaabi + current_app.config["SECRET_KEY"]
d = hashlib.sha384()
e = hashlib.sha384()
d.update(p_salt.encode())
e.update(e_salt.encode())
return d.hexdigest() == e.hexdigest()
else:
return False
else:
return False
def get_digest(value):
"""
Returns a hashlib digest algorithm from a string
"""
if not isinstance(value, str):
return value
value = value.lower()
if value == "md5":
return md5
elif value == "sha1":
return sha1
elif value == "sha224":
return sha224
elif value == "sha256":
return sha256
elif value == "sha384":
return sha384
elif value == "sha512":
return sha512
else:
raise ValueError("Invalid digest algorithm: %s" % value)
def main():
redis_conn = Redis()
q = Queue(connection=redis_conn)
if not os.path.isdir(BLOB_DIR):
os.mkdir(BLOB_DIR)
try:
num_blobs = int(sys.argv[1])
except IndexError:
num_blobs = 1
blobs = []
for i in range(num_blobs):
blob_contents = os.urandom(BLOB_SIZE)
blob_hash = hashlib.sha384(blob_contents).hexdigest()
blob_path = os.path.join(BLOB_DIR, blob_hash)
with open(blob_path, 'wb') as f:
f.write(blob_contents)
blobs.append(blob_hash)
for blob_hash in blobs:
q.enqueue(process_blob, blob_hash, 1)
def sha384(string, salt=None, front=False, back=False, **placeholder):
"""
Create an SHA384 hash from a given string
> :param string:
> :return:
Example:
>>> sha384("test")
768412320f7b0aa5812fce428dc4706b3cae50e02a64caa16a782249bfe8efc4b7ef1ccb126255d196047dfedf17a0a9
"""
if type(string) is unicode:
string = lib.settings.force_encoding(string)
if type(string) is unicode:
string = lib.settings.force_encoding(string)
obj = hashlib.sha384()
if salt is not None and front and not back:
obj.update(salt + string)
elif salt is not None and back and not front:
obj.update(string + salt)
else:
obj.update(string)
return obj.hexdigest()
def _sign_payload(self, method, path, params=None, payload=None):
route = build_route(path, params)
nonce = gen_nonce()
if payload:
j = json.dumps(payload).encode('utf-8')
encoded_body = base64.standard_b64encode(j).decode('utf-8')
string = method + ' ' + route + ' ' + encoded_body + ' ' + nonce
else:
string = method + ' ' + route + ' ' + nonce
h = hmac.new(key=self.SECRET.encode('utf-8'),
msg=string.encode('utf-8'),
digestmod=hashlib.sha384)
signature = h.hexdigest()
return {
'X-SBTC-APIKEY': self.KEY,
'X-SBTC-NONCE': nonce,
'X-SBTC-SIGNATURE': signature,
'Content-Type': 'application/json',
}
def get_digest(value):
"""
Returns a hashlib digest algorithm from a string
"""
if not isinstance(value, str):
return value
value = value.lower()
if value == "md5":
return md5
elif value == "sha1":
return sha1
elif value == "sha224":
return sha224
elif value == "sha256":
return sha256
elif value == "sha384":
return sha384
elif value == "sha512":
return sha512
else:
raise ValueError("Invalid digest algorithm: %s" % value)
def hash(self, method="md5"):
'''
??hash??
'''
content = open(self._fileName,"rb").read(self._MAXSIZE)
if method == "md5":
return hashlib.md5(content).hexdigest()
if method == "sha" or method == "sha1":
return hashlib.sha1(content).hexdigest()
if method == "sha224":
return hashlib.sha224(content).hexdigest()
if method == "sha256":
return hashlib.sha256(content).hexdigest()
if method == "sha384":
return hashlib.sha384(content).hexdigest()
if method == "sha512":
return hashlib.sha512(content).hexdigest()
if method == "crc32":
return "{0:x}".format(binascii.crc32(content) & 0xffffffff)
def generate_keys(path):
salt = '5dIFp5Nb8n1kyPRSU8dKGyhJHx317PA3'
keyOffsets = [8, 25, 22, 47, 24, 5, 16, 9, 33, 3, 45, 1, 30, 34, 37, 36,
15, 39, 11, 14, 23, 29, 26, 40, 31, 7, 13, 38, 27, 17, 12, 21]
ivOffsets = [28, 19, 2, 46, 4, 20, 18, 41, 32, 43, 0, 6, 44, 10, 35, 42]
filename = basename(path)
toHash = salt + filename + salt + filename
hashed = bytes(hashlib.sha384(toHash.encode('ASCII')).digest())
key = [0] * 32
for offset, i in zip(keyOffsets, range(32)):
key[i] = hashed[offset]
iv = bytearray([0]*16)
for offset, i in zip(ivOffsets, range(16)):
iv[i] = hashed[offset]
iv = bytes(iv)
iv = unpack('<Q', iv[:8])[0] | (unpack('<Q', iv[8:])[0] << 64)
return key, iv
def encode_sha384(self, *, message : str):
'''Generate SHA-384 hash'''
await self.bot.embed_reply(hashlib.sha384(message.encode("utf-8")).hexdigest())
def sha384(hash):
climax = hashlib.sha384(hash).hexdigest()
return climax
def toptobottom(crack):
i = 0
while i < (len(asshole)/2):
if len(crack) == 32:
if crack == md5(asshole[i]):
print "\n\t[p1] 3===D passwd is = %s\n"%asshole[i]
break
elif len(crack) == 40:
if crack == sha1(asshole[i]):
print "\n\t[p1] 3===D passwd is = %s\n"%asshole[i]
break
elif len(crack) == 56:
if crack == sha224(asshole[i]):
print "\n\t[p1] 3===D passwd is = %s\n"%asshole[i]
break
elif len(crack) == 64:
if crack == sha256(asshole[i]):
print "\n\t[p1] 3===D passwd is = %s\n"%asshole[i]
break
elif len(crack) == 96:
if crack == sha384(asshole[i]):
print "\n\t[p1] 3===D passwd is = %s\n"%asshole[i]
break
elif len(crack) == 128:
if crack == sha512(asshole[i]):
print "\n\t[p1] 3===D passwd is = %s\n"%asshole[i]
break
else:
print "[-] not support hash"
sys.exit()
i += 1
def bottomtotop(crack):
k = 0
big = len(asshole) - len(asshole)/2
while k < (big):
if len(crack) == 32:
if crack == md5(asshole[-k]):
print "\n\t[p2] 3===D passwd is = %s\n"%asshole[-k]
break
elif len(crack) == 40:
if crack == sha1(asshole[-k]):
print "\n\t[p2] 3===D passwd is = %s\n"%asshole[-k]
break
elif len(crack) == 56:
if crack == sha224(asshole[-k]):
print "\n\t[p2] 3===D passwd is = %s\n"%asshole[-k]
break
elif len(crack) == 64:
if crack == sha256(asshole[-k]):
print "\n\t[p2] 3===D passwd is = %s\n"%asshole[-k]
break
elif len(crack) == 96:
if crack == sha384(asshole[-k]):
print "\n\t[p2] 3===D passwd is = %s\n"%asshole[-k]
break
elif len(crack) == 128:
if crack == sha512(asshole[-k]):
print "\n\t[p2] 3===D passwd is = %s\n"%asshole[-k]
break
else:
sys.exit()
k += 1
def pkcs_mgf1(mgfSeed, maskLen, h):
"""
Implements generic MGF1 Mask Generation function as described in
Appendix B.2.1 of RFC 3447. The hash function is passed by name.
valid values are 'md2', 'md4', 'md5', 'sha1', 'tls, 'sha256',
'sha384' and 'sha512'. Returns None on error.
Input:
mgfSeed: seed from which mask is generated, an octet string
maskLen: intended length in octets of the mask, at most 2^32 * hLen
hLen (see below)
h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
'sha256', 'sha384'). hLen denotes the length in octets of
the hash function output.
Output:
an octet string of length maskLen
"""
# steps are those of Appendix B.2.1
if not _hashFuncParams.has_key(h):
warning("pkcs_mgf1: invalid hash (%s) provided")
return None
hLen = _hashFuncParams[h][0]
hFunc = _hashFuncParams[h][1]
if maskLen > 2**32 * hLen: # 1)
warning("pkcs_mgf1: maskLen > 2**32 * hLen")
return None
T = "" # 2)
maxCounter = math.ceil(float(maskLen) / float(hLen)) # 3)
counter = 0
while counter < maxCounter:
C = pkcs_i2osp(counter, 4)
T += hFunc(mgfSeed + C)
counter += 1
return T[:maskLen]
def pkcs_emsa_pkcs1_v1_5_encode(M, emLen, h): # section 9.2 of RFC 3447
"""
Implements EMSA-PKCS1-V1_5-ENCODE() function described in Sect.
9.2 of RFC 3447.
Input:
M : message to be encode, an octet string
emLen: intended length in octets of the encoded message, at least
tLen + 11, where tLen is the octet length of the DER encoding
T of a certain value computed during the encoding operation.
h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
'sha256', 'sha384'). hLen denotes the length in octets of
the hash function output.
Output:
encoded message, an octet string of length emLen
On error, None is returned.
"""
hLen = _hashFuncParams[h][0] # 1)
hFunc = _hashFuncParams[h][1]
H = hFunc(M)
hLeadingDigestInfo = _hashFuncParams[h][2] # 2)
T = hLeadingDigestInfo + H
tLen = len(T)
if emLen < tLen + 11: # 3)
warning("pkcs_emsa_pkcs1_v1_5_encode: intended encoded message length too short")
return None
PS = '\xff'*(emLen - tLen - 3) # 4)
EM = '\x00' + '\x01' + PS + '\x00' + T # 5)
return EM # 6)
# XXX should add other pgf1 instance in a better fashion.
def _rsassa_pkcs1_v1_5_sign(self, M, h):
"""
Implements RSASSA-PKCS1-v1_5-SIGN() function as described in
Sect. 8.2.1 of RFC 3447.
Input:
M: message to be signed, an octet string
h: hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls'
'sha256', 'sha384').
Output:
the signature, an octet string.
"""
# 1) EMSA-PKCS1-v1_5 encoding
k = self.modulusLen / 8
EM = pkcs_emsa_pkcs1_v1_5_encode(M, k, h)
if EM is None:
warning("Key._rsassa_pkcs1_v1_5_sign(): unable to encode")
return None
# 2) RSA signature
m = pkcs_os2ip(EM) # 2.a)
s = self._rsasp1(m) # 2.b)
S = pkcs_i2osp(s, k) # 2.c)
return S # 3)
def pkcs_mgf1(mgfSeed, maskLen, h):
"""
Implements generic MGF1 Mask Generation function as described in
Appendix B.2.1 of RFC 3447. The hash function is passed by name.
valid values are 'md2', 'md4', 'md5', 'sha1', 'tls, 'sha256',
'sha384' and 'sha512'. Returns None on error.
Input:
mgfSeed: seed from which mask is generated, an octet string
maskLen: intended length in octets of the mask, at most 2^32 * hLen
hLen (see below)
h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
'sha256', 'sha384'). hLen denotes the length in octets of
the hash function output.
Output:
an octet string of length maskLen
"""
# steps are those of Appendix B.2.1
if not _hashFuncParams.has_key(h):
warning("pkcs_mgf1: invalid hash (%s) provided")
return None
hLen = _hashFuncParams[h][0]
hFunc = _hashFuncParams[h][1]
if maskLen > 2**32 * hLen: # 1)
warning("pkcs_mgf1: maskLen > 2**32 * hLen")
return None
T = "" # 2)
maxCounter = math.ceil(float(maskLen) / float(hLen)) # 3)
counter = 0
while counter < maxCounter:
C = pkcs_i2osp(counter, 4)
T += hFunc(mgfSeed + C)
counter += 1
return T[:maskLen]