本文整理汇总了Python中Crypto.Hash.SHA512类的典型用法代码示例。如果您正苦于以下问题:Python SHA512类的具体用法?Python SHA512怎么用?Python SHA512使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SHA512类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DecryptECIES
def DecryptECIES(curve_name, R, enc, t, pwd):
'''Performs ECIES decryption.'''
# Setup for Decryption
E = PredefinedCurves(curve_name)
# Get secret key s
hashpwd = SHA512.new(pwd).hexdigest() + RIPEMD.new(pwd).hexdigest()
s = int(str(int(hashpwd,16))[0: len(str(E.N))]) % E.N
if s < 2:
s = E.N/2
# Begin Decryption
Z = E.multPoint(s,R)
RZ = str(R)+str(Z)
H1 = SHA512.new(RZ).hexdigest()
k1 = H1[0:32]
k2 = H1[32:128]
H2 = RIPEMD.new(enc+k2).digest()
# If the hashes don't match, stop
if base64.b64decode(t) != H2:
return "Error: Hashes don't match! Your public key password is most likely incorrect. It is also possible, though improbable, that you selected the wrong encrypted image."
cipher = AES.new(k1)
message = cipher.decrypt(base64.b64decode(enc))
return message
示例2: _get_hash
def _get_hash(obj):
"""
Returns a SHA512 object for the given object. Works in a similar fashion
to a Merkle tree (see https://en.wikipedia.org/wiki/Merkle_tree) should
the object be tree like in structure - but only returns the "root" hash.
"""
obj_type = type(obj)
if obj_type is dict:
hash_list = []
for k in sorted(obj):
hash_list.append(_get_hash(k).hexdigest())
hash_list.append(_get_hash(obj[k]).hexdigest())
seed = ''.join(hash_list)
return SHA512.new(seed)
elif obj_type is list:
hash_list = []
for item in obj:
hash_list.append(_get_hash(item).hexdigest())
seed = ''.join(hash_list)
return SHA512.new(seed)
elif obj_type is NoneType:
return SHA512.new('null')
elif obj_type is bool:
return SHA512.new(str(obj).lower())
else:
return SHA512.new(str(obj))
示例3: sha2_hmac
def sha2_hmac(key, message):
"""
This is the PRF used in the RFC; an implementation of HMAC using SHA512
"""
hashfunc = SHA512.new()
opad = bytearray([0x5c]*blocksize)
ipad = bytearray([0x36]*blocksize)
key = bytearray(key)
if len(key) > blocksize:
hashfunc.update(bytearray(key)) #truncate key to blocksize if required
key = bytearray(hashfunc.digest())
if len(key) < blocksize:
key = key + bytearray([0x00]*(blocksize - len(key))) #pad right with 0s if needed
o_key_pad = bytearray([a^b for a,b in zip(key, opad)]) #compute key XORs
i_key_pad = bytearray([a^b for a,b in zip(key, ipad)])
hashfunc.update(i_key_pad + bytearray(message)) #internal hash
ihash = bytearray(hashfunc.digest())
hashfunc = SHA512.new() #reset hash function for outer hash
hashfunc.update(o_key_pad + ihash)
ohash = hashfunc.digest() #inner hash result
return bytearray(ohash) #return in byte array format
示例4: otp
def otp():
if not request.json:
abort(400)
i9 = request.json['iv1']
i10 = request.json['iv2']
k9 = request.json['k9']
k10 = merchant.decrypt(request.json['k10'])
block1 = request.json['block1']
block2 = request.json['block2']
aes10 = AES.new(k10, AES.MODE_CFB, iv2)
decrypt_block2 = aes10.decrypt(block2)
authdata = decrypt_block2[:-128]
hash_authdata = decrypt_block1[-128:]
if SHA512.new(authdata).hexdigest() != hash_authdata:
return 'hash of auth doesnt match'
authdata = 'the customer is trying to send his otp, take it'
k11 = Random.get_random_bytes(16)
i11 = Random.get_random_bytes(16)
aes = AES.new(k11, AES.MODE_CFB, i11)
encrypted_authdata = aes.encrypt(authdata)
signed_auth_data = merchant.sign(encrypted_authdata)
encrypted_k11 = paymentgateway_publickey.encrypt(k11)
data = {'k11': k11, 'i7': i11, 'authdata': encrypted_authdata, 'hash_authdata': signed_auth_data,
'eotp': block1, 'k9': k9, 'i9': i9}
response = requests.post('http://loclahost:8002/otp', data=data)
data = response.json()
encrypt_auth_data = data['authdata']
signed_auth_data = data['signature']
auth_data_iv = data['iv']
kx = merchant.decrypt(data['kx'])
aes = AES.new(kx, AES.MODE_CFB, auth_data_iv)
auth_data = aes.decrypt(encrypt_auth_data)
if paymentgateway_publickey.verify(SHA512.new(auth_data).hexdigest(), signed_auth_data) == False:
return {'status': "couldnt verify paymentgateway response"}
if auth_data != 'everything is good':
return {'status': 'something went wrong while starting transaction'}
auth_data = 'everything is good'
iv = Random.get_random_bytes(16)
aes = AES.new(k10, AES.MODE_CFB, iv)
encrypted_authdata = aes.encrypt(auth_data)
signature = merchant.sign(SHA512.new(signature).hexdigest())
return {'iv': iv, 'authdata': encrypted_authdata, 'signature': signature}
示例5: remunge
def remunge(params, raw_uid):
"""Creates a new PGPv3 key and PGPv4 signature.
"""
n, e, d, p, q = params = [long(param) for param in params]
pubkey = v3pubkey(n, e)
restamped_pub = dumpbuffer(str(pubkey))[0]
raw_uid = (raw_uid.encode('utf-8')
if isinstance(raw_uid, unicode)
else raw_uid)
uid = (bytearray([0xb4]) +
bytearray(four_octet(len(raw_uid))) +
bytearray(raw_uid))
sigtohash = bytearray(
[0x04, # version
0x13, # type
0x01, # pub_algo
0x0a, # hash_algo == SHA512
0x00, # first octet of length
len(_HASHED_SUBPACKETS)]) + _HASHED_SUBPACKETS
sigtrailer = bytearray([0x04, 0xff, 0x00, 0x00, 0x00,
len(sigtohash)])
# (n, e, d, p, q)
#params = (sk.modulus, long(sk.exponent), sk.exponent_d,
# sk.prime_p, sk.prime_q)
rsa_key = RSA.construct(params)
signer = PKCS1_v1_5.new(rsa_key)
message = restamped_pub.raw_data + uid + sigtohash + sigtrailer
h = SHA512.new(bytes(message))
signature = signer.sign(h)
digest = h.digest()
new_sig = (sigtohash
+ chr(0)
+ chr(10)
+ chr(9) # Length of issuer subpacket; always 8 + 1
+ '\x10' # Issuer subpacket marker
+ long_to_bytes(long(restamped_pub.key_id, base=16))
+ digest[:2]
+ to_mpi(bytes_to_long(signature)))
new_sig = '\x89' + pack('>H', len(new_sig)) + new_sig
complete = bytes(bytearray().join([restamped_pub.raw_data,
b"\xb4" + chr(len(raw_uid)),
raw_uid, new_sig]))
with open(urlsafe_b64encode(SHA512.new(complete).digest()), 'w') as f:
f.write(complete)
return complete
示例6: password
def password():
if not request.json:
abort(400)
k5 = request.json['k5']
k6 = merchant.decrypt(request.json['k6'])
i5 = request.json['iv1']
i6 = request.json['i5']
block1 = request.json['block1']
block2 = request.json['block2']
aes6 = AES.new(k6, AES.MODE_CFB, i6)
decrypt_block2 = aes6.decrypt(block2)
authdata = decrypt_block2[:-128]
hash_authdata = decrypt_block1[-128:]
if SHA512.new(authdata).hexdigest() != hash_authdata:
return 'hash of auth doesnt match'
authdata = 'the customer is trying to send his pass, take it'
k7 = Random.get_random_bytes(16)
i7 = Random.get_random_bytes(16)
aes = AES.new(k7, AES.MODE_CFB, i7)
encrypted_authdata = aes.encrypt(authdata)
signed_auth_data = merchant.sign(SHA512.new(encrypted_authdata).hexdigest())
encrypted_k7 = paymentgateway_publickey.encrypt(k7)
data = {'k7': encrypted_k7, 'i7': i7, 'authdata': encrypted_authdata, 'hash_authdata': hash_authdata,
'epassword': block1, 'k5': k5, 'i5': i5}
response = requests.post('http://loclahost:8002/password', data=data)
data = response.json()
encrypt_auth_data = data['authdata']
signed_auth_data = data['signature']
auth_data_iv = data['iv']
k4 = merchant.decrypt(data['k4'])
aes = AES.new(k4, AES.MODE_CFB, auth_data_iv)
auth_data = aes.decrypt(encrypt_auth_data)
if paymentgateway_publickey.verify(SHA512.new(auth_data).hexdigest(), signed_auth_data) == False:
return {'status': "couldnt verify paymentgateway response"}
if auth_data != 'everything is good':
return {'status': 'something went wrong while starting transaction'}
auth_data = 'everything is good'
iv = Random.get_random_bytes(16)
aes = AES.new(k6, AES.MODE_CFB, iv)
encrypted_authdata = aes.encrypt(auth_data)
signature = merchant.sign(SHA512.new(signature).hexdigest())
return {'iv': iv, 'authdata': encrypted_authdata, 'signature': signature}
示例7: convert
def convert(args: object) -> int:
""" Convert from sha256 hashed key to using a master key and encrypting the
master key with a password based key.
"""
filename = args.filename
password = get_pass("password", verify=False)
# Read the accounts dictionary into accounts_dict.
accounts_dict, encrypted_key, master_key = read_file(filename, password)
# Try to convert from old sha256 format to the new format.
print("Converting...", end="")
tmp_accounts_dict = {}
for account_hash, account_data in accounts_dict.items():
account_dict = crypt_to_dict_sha256(account_data, password=password, skip_invalid=True)
if account_dict:
new_account_data = dict_to_crypt(account_dict, master_key)
else:
raise (Exception("Invalid password. Can't convert."))
account_name = account_dict.get("Account Name", "")
new_account_hash = SHA512.new(account_name.encode()).hexdigest()
tmp_accounts_dict[new_account_hash] = new_account_data
write_file(filename, tmp_accounts_dict, encrypted_key)
print("Done.")
return 0
示例8: send
def send(self, obj, commit = False):
msg = {'msg' : obj}
if not commit:
logger.info('[+] Sending: {0}'.format(msg['msg']))
else:
msg['COMMIT'] = obj
# serialize input
data = pickle.dumps(obj)
# padding
pad = AES.block_size - len(data) % AES.block_size
# create an header [pck length (4 bytes), pad length (1 byte), random (3 bytes))]
plaintext = pack('>IB', len(data) + pad + SHA512.digest_size, pad)
plaintext += Random.new().read(AES.block_size - len(plaintext))
# add payload plus padding
plaintext += data
plaintext += Random.new().read(pad)
# encryption
ciphertext = self.cipher_out.encrypt(plaintext)
# integrity
hsha = HMAC.new(self.key_hmac_out, digestmod=SHA512.new())
hsha.update(plaintext)
hsha.update(pack('>I', self.seq_out))
self.seq_out = (self.seq_out + 1) & 0xFFFFFFFF
ciphertext += hsha.digest()
self.socket.sendall(ciphertext)
示例9: sendfile
def sendfile(self, dst_link, filepath):
def _callback(err):
if self._ret_sendfile(filekey, err) and err != None:
with Auth.change_current_iden(self._idendesc, self._auth):
self.call(dst_link + "imc/", "abort_sendfile", 65536, filekey, err)
filekey = SHA512.new(uuid.uuid1().bytes + ssl.RAND_bytes(64)).hexdigest()
filesize = os.stat(filepath).st_size
fileresult = FileResult(filekey)
self._info_filekeymap[filekey] = {
"filesize": filesize,
"filepath": filepath,
"fileresult": fileresult,
"timer": self._ioloop.add_timeout(
datetime.timedelta(days=1), lambda: self._ret_sendfile(filekey, "Etimeout")
),
"callback": tornado.stack_context.wrap(_callback),
}
with Auth.change_current_iden(self._idendesc, self._auth):
stat, ret = self.call(dst_link + "imc/", "pend_recvfile", 65536, self._link, filekey, filesize)
if stat == False:
self._ret_sendfile(filekey, "Enoexist")
return fileresult
示例10: crypto_hash_sha512
def crypto_hash_sha512(data):
"""
调用 Crypto 库的 sha512 函数进行哈希操作
:param data: 待哈希的数值, 比如 b"test_hash"
:return: "5a32f0967623012cdd4c29257f808f3f209184e992c39dc6d931f89831e7b1eb9379f9e3a20da09eb06d0ca53bd9c0845dda91baed17a713c0cac8a24259c0b9"
"""
return SHA512.new(data).hexdigest()
示例11: insert_encrypted_file
def insert_encrypted_file(file, master_password):
filename = file.path
obj = SHA256.new()
obj.update(file.author)
obj.update(filename)
obj.update(file.title)
title = obj.hexdigest()
obj_pass = SHA512.new()
obj_pass.update(file.author)
obj_pass.update(master_password)
obj_pass.update(file.title)
encfs_password = obj_pass.hexdigest()
mount_f = media_dir + os.path.sep + mount_dir + os.path.sep + title
store_f = media_dir + os.path.sep + store_dir + os.path.sep + title
print store_f
if os.path.exists(store_f):
return
if not os.path.exists(mount_f):
os.makedirs(mount_f)
if not os.path.exists(store_f):
os.makedirs(store_f)
subprocess.call(["expect", "encfs.exp", encfs_password, os.path.abspath(mount_f), os.path.abspath(store_f)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
subprocess.call(["fusermount","-z","-u", os.path.abspath(mount_f)])
subprocess.call(["/bin/sh", "-c", 'echo '+encfs_password+' | encfs -S -o allow_root --idle=1 '+os.path.abspath(store_f)+' '+os.path.abspath(mount_f)])
shutil.copyfile("../media/" + filename, mount_f + os.path.sep + filename)
示例12: load_table_index
def load_table_index(self,key):
#FIXME no overlap check currently
hash = SHA512.new(key);
self.blockdevice.seek(0);
self.blockdevice.seek(self._hash_to_location(hash.hexdigest()));
hextowrite = ord(self.blockdevice.read(1));
self.indexlocation = hextowrite * (512 * 1024) + 2;
示例13: make_hash
def make_hash(data):
""" make hash
@param data:
@type data:
"""
sha = SHA512.new(data)
return sha.hexdigest()
示例14: check_sign
def check_sign(self, data, signature, key):
"""验证签名"""
verifier = PKCS1_v1_5.new(key)
if verifier.verify(SHA512.new(data), signature):
print "the signature is authentic"
else:
print "the signature is not authentic"
示例15: compare_password
def compare_password(password, hash):
split = hash.split(':')
salt = base64.b64decode(split[0])
new_hash = SHA512.new()
new_hash.update(salt)
new_hash.update(password.encode('utf8'))
return is_equal(new_hash.digest(), base64.b64decode(split[1]))