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类sha512()的实例源码
def generate(password):
'''Generate a ShadowHashData structure as used by macOS 10.8+'''
iterations = arc4random.randrange(30000, 50000)
salt = make_salt(32)
keylen = 128
try:
entropy = hashlib.pbkdf2_hmac(
'sha512', password, salt, iterations, dklen=keylen)
except AttributeError:
# old Python, do it a different way
entropy = pbkdf2.pbkdf2_bin(
password, salt, iterations=iterations, keylen=keylen,
hashfunc=hashlib.sha512)
data = {'SALTED-SHA512-PBKDF2': {'entropy': buffer(entropy),
'iterations': iterations,
'salt': buffer(salt)},
}
return plistutils.write_plist(data, plist_format='binary')
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 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 auth_local(self, username, password):
password = hashlib.sha512(password.encode('utf-8')).hexdigest()
user = User.query.filter_by(username = username).first()
if (user == None):
return {"success":'false', "reason": "User did not exist"}
if (user.password != password):
return {"success":'false', "reason": "Wrong password"}
result = {
"success": 'true',
"data":{
"username" : user.username,
"avatar" : user.avatar,
"nickname" : user.nickname,
"description" : user.description,
"status" : user.status,
"group" : user.user_group,
"token" : user.generate_auth_token(),
}
}
return result
def hash_iterative(s, n, k):
'''
Uses Hashing technique mentioned in BLISS pg 19
i/p: string s to be hashed to binary string of length n and weight k
'''
i = 0 # seed which increases till we get Bk^n
while(True):
Bk = [0] * n
I_val = int(hashlib.sha512(s + str(i)).hexdigest(), 16)
count = 0
while(I_val > 0):
pos = I_val % n
I_val /= n
if(Bk[pos] == 0):
Bk[pos] = 1
count += 1
if(count == k):
return np.array(Bk)
i += 1
def read_tar(f):
result = {}
try:
with tarfile.open(f) as t:
for m in t:
if m.isfile():
f = t.extractfile(m)
sha512 = sha512_file(f)
else:
sha512 = None
result[m.name] = TarMemberInfo(m, sha512)
except tarfile.ReadError:
# if we can't read the tar archive, we should never consider it to have
# the same contents as another tar archive...
result[f] = None
return result
#
#
#
def read_packages(rel_area, arch):
packages = defaultdict(Package)
# <arch>/ noarch/ and src/ directories are considered
for root in ['noarch', 'src', arch]:
releasedir = os.path.join(rel_area, root)
logging.debug('reading packages from %s' % releasedir)
for (dirpath, subdirs, files) in os.walk(releasedir, followlinks=True):
read_package(packages, rel_area, dirpath, files)
logging.debug("%d packages read" % len(packages))
return packages
# helper function to compute sha512 for a particular file
# (block_size should be some multiple of sha512 block size which can be efficiently read)
def get_mosfit_hash(salt=u''):
"""Return a unique hash for the MOSFiT code."""
import fnmatch
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
matches = []
for root, dirnames, filenames in os.walk(dir_path):
for filename in fnmatch.filter(filenames, '*.py'):
matches.append(os.path.join(root, filename))
matches = list(sorted(list(matches)))
code_str = salt
for match in matches:
with codecs.open(match, 'r', 'utf-8') as f:
code_str += f.read()
return hashlib.sha512(hash_bytes(code_str)).hexdigest()[:16]
def query_private(self, method, req={}, conn = None):
"""API queries that require a valid key/secret pair.
Arguments:
method -- API method name (string, no default)
req -- additional API request parameters (default: {})
conn -- connection object to reuse (default: None)
"""
urlpath = '/' + self.apiversion + '/private/' + method
req['nonce'] = int(1000*time.time())
postdata = urllib.urlencode(req)
message = urlpath + hashlib.sha256(str(req['nonce']) +
postdata).digest()
signature = hmac.new(base64.b64decode(self.secret),
message, hashlib.sha512)
headers = {
'API-Key': self.key,
'API-Sign': base64.b64encode(signature.digest())
}
return self._query(urlpath, req, conn, headers)
def decrypt(self, data, ciphername='aes-256-cbc'):
"""
Decrypt data with ECIES method using the local private key
"""
blocksize = OpenSSL.get_cipher(ciphername).get_blocksize()
iv = data[:blocksize]
i = blocksize
curve, pubkey_x, pubkey_y, i2 = ECC._decode_pubkey(data[i:])
i += i2
ciphertext = data[i:len(data)-32]
i += len(ciphertext)
mac = data[i:]
key = sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
key_e, key_m = key[:32], key[32:]
if not equals(hmac_sha256(key_m, data[:len(data) - 32]), mac):
raise RuntimeError("Fail to verify data")
ctx = Cipher(key_e, iv, 0, ciphername)
return ctx.ciphering(ciphertext)
def malware_sample():
sampledata = BytesIO(b'clean')
buf = sampledata.read()
sampledata.seek(0)
md5_hash = hashlib.md5(buf).hexdigest()
sha1_hash = hashlib.sha1(buf).hexdigest()
sha256_hash = hashlib.sha256(buf).hexdigest()
sha512_hash = hashlib.sha512(buf).hexdigest()
ctph = ssdeep.hash(buf)
Sample = namedtuple(
'Sample',
['data', 'filename', 'md5', 'sha1', 'sha256', 'sha512', 'ctph'])
sample = Sample(
data='sampledata', filename='blah.zip', md5=md5_hash, sha1=sha1_hash,
sha256=sha256_hash, sha512=sha512_hash, ctph=ctph)
return sample
def _call(self, topic: str, args: dict() = {}):
if topic in ['returnTicker', 'return24Volume', 'returnOrderBook', 'returnTradeHistory', 'returnChartData', 'returnCurrencies', 'returnLoanOrders']:
api = [self.public_url, 'get', topic]
else:
api = [self.private_url, 'post', topic, self.secrets]
def __call(api_details, uri):
request = getattr(requests, api_details[1])
headers = {}
del uri['self']
uri['command'] = api_details[2]
if api_details[2] == 'post':
uri['nonce'] = int(time.time() * 1000)
sign = hmac.new(api_details[3]['secret'], uri, hashlib.sha512).hexdigest()
headers['Sign'] = sign
headers['Key'] = api_details[3]['api_key']
return json.loads(request(api_details[0], uri, headers=headers).content.decode())
with self.limiter:
return __call(api, args)
def hashPasswordTuple(password, digestMod=hashlib.sha512, iterations=10000,
saltSize=32):
"""
Module function to hash a password according to the PBKDF2 specification.
@param password clear text password (string)
@param digestMod hash function
@param iterations number of times hash function should be applied (integer)
@param saltSize size of the salt (integer)
@return tuple of digestname (string), number of iterations (integer),
salt (bytes) and hashed password (bytes)
"""
salt = os.urandom(saltSize)
password = password.encode("utf-8")
hash = pbkdf2(password, salt, iterations, digestMod)
digestname = digestMod.__name__.replace("openssl_", "")
return digestname, iterations, salt, hash
def hashPassword(password, digestMod=hashlib.sha512, iterations=10000,
saltSize=32):
"""
Module function to hash a password according to the PBKDF2 specification.
@param password clear text password (string)
@param digestMod hash function
@param iterations number of times hash function should be applied (integer)
@param saltSize size of the salt (integer)
@return hashed password entry according to PBKDF2 specification (string)
"""
digestname, iterations, salt, hash = \
hashPasswordTuple(password, digestMod, iterations, saltSize)
return Delimiter.join([
digestname,
str(iterations),
base64.b64encode(salt).decode("ascii"),
base64.b64encode(hash).decode("ascii")
])
def get_shared_secret(priv, pub):
""" Derive the share secret between ``priv`` and ``pub``
:param `Base58` priv: Private Key
:param `Base58` pub: Public Key
:return: Shared secret
:rtype: hex
The shared secret is generated such that::
Pub(Alice) * Priv(Bob) = Pub(Bob) * Priv(Alice)
"""
pub_point = pub.point()
priv_point = int(repr(priv), 16)
res = pub_point * priv_point
res_hex = '%032x' % res.x()
# Zero padding
res_hex = '0' * (64 - len(res_hex)) + res_hex
return hashlib.sha512(unhexlify(res_hex)).hexdigest()
def init_aes(shared_secret, nonce):
""" Initialize AES instance
:param hex shared_secret: Shared Secret to use as encryption key
:param int nonce: Random nonce
:return: AES instance and checksum of the encryption key
:rtype: length 2 tuple
"""
" Seed "
ss = unhexlify(shared_secret)
n = struct.pack("<Q", int(nonce))
encryption_key = hashlib.sha512(n + ss).hexdigest()
" Check'sum' "
check = hashlib.sha256(unhexlify(encryption_key)).digest()
check = struct.unpack_from("<I", check[:4])[0]
" AES "
key = unhexlify(encryption_key[0:64])
iv = unhexlify(encryption_key[64:96])
return AES.new(key, AES.MODE_CBC, iv), check
def decrypt(self, data, ciphername='aes-256-cbc'):
"""
Decrypt data with ECIES method using the local private key
"""
blocksize = OpenSSL.get_cipher(ciphername).get_blocksize()
iv = data[:blocksize]
i = blocksize
curve, pubkey_x, pubkey_y, i2 = ECC._decode_pubkey(data[i:])
i += i2
ciphertext = data[i:len(data)-32]
i += len(ciphertext)
mac = data[i:]
key = sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
key_e, key_m = key[:32], key[32:]
if not equals(hmac_sha256(key_m, data[:len(data) - 32]), mac):
raise RuntimeError("Fail to verify data")
ctx = Cipher(key_e, iv, 0, ciphername)
return ctx.ciphering(ciphertext)
def hashPasswordTuple(password, digestMod=hashlib.sha512, iterations=10000,
saltSize=32):
"""
Module function to hash a password according to the PBKDF2 specification.
@param password clear text password (string)
@param digestMod hash function
@param iterations number of times hash function should be applied (integer)
@param saltSize size of the salt (integer)
@return tuple of digestname (string), number of iterations (integer),
salt (bytes) and hashed password (bytes)
"""
salt = os.urandom(saltSize)
password = password.encode("utf-8")
hash = pbkdf2(password, salt, iterations, digestMod)
digestname = digestMod.__name__.replace("openssl_", "")
return digestname, iterations, salt, hash
def hashPassword(password, digestMod=hashlib.sha512, iterations=10000,
saltSize=32):
"""
Module function to hash a password according to the PBKDF2 specification.
@param password clear text password (string)
@param digestMod hash function
@param iterations number of times hash function should be applied (integer)
@param saltSize size of the salt (integer)
@return hashed password entry according to PBKDF2 specification (string)
"""
digestname, iterations, salt, hash = \
hashPasswordTuple(password, digestMod, iterations, saltSize)
return Delimiter.join([
digestname,
str(iterations),
base64.b64encode(salt).decode("ascii"),
base64.b64encode(hash).decode("ascii")
])
def sign(self, url, endpoint, endpoint_path, method_verb, *args, **kwargs):
try:
req = kwargs['params']
except KeyError:
req = {}
req['nonce'] = self.nonce()
postdata = urllib.parse.urlencode(req)
# Unicode-objects must be encoded before hashing
encoded = (str(req['nonce']) + postdata).encode('utf-8')
message = (endpoint_path.encode('utf-8') +
hashlib.sha256(encoded).digest())
signature = hmac.new(base64.b64decode(self.secret),
message, hashlib.sha512)
sigdigest = base64.b64encode(signature.digest())
headers = {
'API-Key': self.key,
'API-Sign': sigdigest.decode('utf-8')
}
return url, {'data': req, 'headers': headers}
def sign(self, uri, endpoint, endpoint_path, method_verb, *args, **kwargs):
nonce = self.nonce()
try:
params = kwargs['params']
except KeyError:
params = {}
params['apikey'] = self.key
params['nonce'] = nonce
post_params = params
post_params.update({'nonce': nonce, 'method': endpoint})
post_params = urllib.parse.urlencode(post_params)
url = uri + post_params
sig = hmac.new(url, self.secret, hashlib.sha512)
headers = {'apisign': sig}
return url, {'headers': headers}
def sign(self, url, endpoint, endpoint_path, method_verb, *args, **kwargs):
try:
params = kwargs['params']
except KeyError:
params = {}
nonce = self.nonce()
req_string = endpoint_path + '?apikey=' + self.key + "&nonce=" + nonce + '&'
req_string += urllib.parse.urlencode(params)
headers = {"apisign": hmac.new(self.secret.encode('utf-8'),
(self.uri + req_string).encode('utf-8'),
hashlib.sha512).hexdigest()}
return self.uri + req_string, {'headers': headers, 'params': {}}
def sign(self, payload):
"""
Signature method which wraps signature and nonce parameters around a
payload dictionary.
:param payload:
:return:
"""
nonce = str(int(time.time() * 1000))
package = {'apikey': self.key,
'message': {'nonce': nonce, 'payload': payload}}
signature = hmac.new(self.secret, json.dumps(payload).hexdigest,
hashlib.sha512).hexdigest()
package['signature'] = signature
return json.dumps(package)
def __call__(self, r):
r.headers["Content-type"] = "application/x-www-form-urlencoded"
r.headers["API-Key"] = self.key.replace(" ", "+")
urlpath = '/0/private/' + self.method
postdata = urllib.urlencode(self.params)
#print "params:", self.params
#print "nonce:", self.params["nonce"]
message = urlpath + hashlib.sha256(str(self.params["nonce"]) + postdata).digest()
#print message
signature = hmac.new(base64.b64decode(self.secret.replace(" ", "+")), message, hashlib.sha512)
r.headers["API-Sign"] = base64.b64encode(signature.digest())
#print r.headers
return r
def get_shared_secret(priv, pub):
""" Derive the share secret between ``priv`` and ``pub``
:param `Base58` priv: Private Key
:param `Base58` pub: Public Key
:return: Shared secret
:rtype: hex
The shared secret is generated such that::
Pub(Alice) * Priv(Bob) = Pub(Bob) * Priv(Alice)
"""
pub_point = pub.point()
priv_point = int(repr(priv), 16)
res = pub_point * priv_point
res_hex = '%032x' % res.x()
# Zero padding
res_hex = '0' * (64 - len(res_hex)) + res_hex
return hashlib.sha512(unhexlify(res_hex)).hexdigest()
def init_aes(shared_secret, nonce):
""" Initialize AES instance
:param hex shared_secret: Shared Secret to use as encryption key
:param int nonce: Random nonce
:return: AES instance and checksum of the encryption key
:rtype: length 2 tuple
"""
" Seed "
ss = unhexlify(shared_secret)
n = struct.pack("<Q", int(nonce))
encryption_key = hashlib.sha512(n + ss).hexdigest()
" Check'sum' "
check = hashlib.sha256(unhexlify(encryption_key)).digest()
check = struct.unpack_from("<I", check[:4])[0]
" AES "
key = unhexlify(encryption_key[0:64])
iv = unhexlify(encryption_key[64:96])
return AES.new(key, AES.MODE_CBC, iv), check
def get_shared_secret(priv, pub):
""" Derive the share secret between ``priv`` and ``pub``
:param `Base58` priv: Private Key
:param `Base58` pub: Public Key
:return: Shared secret
:rtype: hex
The shared secret is generated such that::
Pub(Alice) * Priv(Bob) = Pub(Bob) * Priv(Alice)
"""
pub_point = pub.point()
priv_point = int(repr(priv), 16)
res = pub_point * priv_point
res_hex = '%032x' % res.x()
# Zero padding
res_hex = '0' * (64 - len(res_hex)) + res_hex
return hashlib.sha512(unhexlify(res_hex)).hexdigest()
def master_key_from_seed(seed):
""" Generates a master key from a provided seed.
Args:
seed (bytes or str): a string of bytes or a hex string
Returns:
HDPrivateKey: the master private key.
"""
S = get_bytes(seed)
I = hmac.new(b"Bitcoin seed", S, hashlib.sha512).digest()
Il, Ir = I[:32], I[32:]
parse_Il = int.from_bytes(Il, 'big')
if parse_Il == 0 or parse_Il >= bitcoin_curve.n:
raise ValueError("Bad seed, resulting in invalid key!")
return HDPrivateKey(key=parse_Il, chain_code=Ir, index=0, depth=0)