def filter_sha(group): hash_name = group['sha'] if hash_name == "SHA-512": return SHA512 elif hash_name == "SHA-512/224": return SHA512.new(truncate="224") elif hash_name == "SHA-512/256": return SHA512.new(truncate="256") elif hash_name == "SHA3-512": return SHA3_512 elif hash_name == "SHA-384": return SHA384 elif hash_name == "SHA3-384": return SHA3_384 elif hash_name == "SHA-256": return SHA256 elif hash_name == "SHA3-256": return SHA3_256 elif hash_name == "SHA-224": return SHA224 elif hash_name == "SHA3-224": return SHA3_224 elif hash_name == "SHA-1": return SHA1 else: raise ValueError("Unknown hash algorithm: " + hash_name)
def UploadFile(socket, address, key, size_uncompressed, size_compressed, buffer=2048): with open("temp.tar.gz", "rb") as f: file_hash_uc = SHA512.new(); file_hash_c = SHA512.new(); for address_singular in address: with open(address_singular, "rb") as filehandle: while True: block = filehandle.read(buffer); if not block: break; file_hash_uc.update(block); with Progress(TextColumn("[bold blue]{task.description}", justify="right"), BarColumn(bar_width=None), "[progress.percentage]{task.percentage:>3.1f}%", "•", DownloadColumn(), "•", TransferSpeedColumn(), "•", TimeRemainingColumn(),) as progress: task = progress.add_task("Uploading file(s)", total=size_compressed); while not progress.finished: l = f.read(buffer); if not l: break; select.select([], [socket], []); sendEncryptedMessage(socket, l, key); progress.update(task, advance=len(l)); file_hash_c.update(l); return (file_hash_uc, file_hash_c);
def get_local_vault_keys(password, salt, e_mk_d, e_ok_d): iter = 100000 p_data('Salt', salt, dump=False) raw_key = hashlib.pbkdf2_hmac('sha512', password, salt, iter, dklen=64) op_kek_mk = raw_key[0:32] op_kek_hmac = raw_key[32:64] p_data('Derived key', op_kek_mk) p_data('Derived HMAC key', op_kek_hmac) master_key_data = decrypt_opdata(e_mk_d, op_kek_mk, op_kek_hmac) h_raw = SHA512.new(master_key_data).digest() op_mk = h_raw[0:32] op_mk_hmac = h_raw[32:64] p_data('Priv vault MK', op_mk) p_data('Priv vault MK HMAC', op_mk_hmac) overview_key_data = decrypt_opdata(e_ok_d, op_kek_mk, op_kek_hmac) h_raw = SHA512.new(overview_key_data).digest() op_ok = h_raw[0:32] op_ok_hmac = h_raw[32:64] p_data('Priv vault OK', op_ok) p_data('Priv vault OK HMAC', op_ok_hmac) return op_mk, op_mk_hmac, op_ok, op_ok_hmac
def add_tests(self, filename): comps = "Cryptodome.SelfTest.Signature.test_vectors.wycheproof".split( ".") with open(pycryptodome_filename(comps, filename), "rt") as file_in: tv_tree = json.load(file_in) class TestVector(object): pass self.tv = [] for group in tv_tree['testGroups']: key = RSA.import_key(group['keyPem']) hash_name = group['sha'] if hash_name == "SHA-512": hash_module = SHA512 elif hash_name == "SHA-512/224": hash_module = SHA512.new(truncate="224") elif hash_name == "SHA-512/256": hash_module = SHA512.new(truncate="256") elif hash_name == "SHA3-512": hash_module = SHA3_512 elif hash_name == "SHA-384": hash_module = SHA384 elif hash_name == "SHA3-384": hash_module = SHA3_384 elif hash_name == "SHA-256": hash_module = SHA256 elif hash_name == "SHA3-256": hash_module = SHA3_256 elif hash_name == "SHA-224": hash_module = SHA224 elif hash_name == "SHA3-224": hash_module = SHA3_224 elif hash_name == "SHA-1": hash_module = SHA1 else: raise ValueError("Unknown hash algorithm: " + hash_name) type_name = group['type'] if type_name not in ("RsassaPkcs1Verify", "RsassaPkcs1Generate"): raise ValueError("Unknown type name " + type_name) for test in group['tests']: tv = TestVector() tv.id = test['tcId'] tv.comment = test['comment'] for attr in 'msg', 'sig': setattr(tv, attr, unhexlify(test[attr])) tv.key = key tv.hash_module = hash_module tv.valid = test['result'] != "invalid" tv.warning = test['result'] == "acceptable" self.tv.append(tv)
def test_length_extension_attack_sha512(secret, original_data, data_to_add): assume(len(original_data) > 0) assume(len(data_to_add) > 0) h = SHA512.new(secret + original_data).hexdigest() digest, message = hashpump(h, original_data, data_to_add, len(secret)) assert message.startswith(original_data) assert message != original_data assert message.endswith(data_to_add) pad = message[len(original_data) : -len(data_to_add)] assert original_data + pad + data_to_add == message assert SHA512.new(secret + message).hexdigest() == digest
def test_loopback(self): hashed_msg = SHA512.new(b("test")) signer = DSS.new(self.key_priv, 'fips-186-3') signature = signer.sign(hashed_msg) verifier = DSS.new(self.key_pub, 'fips-186-3') verifier.verify(hashed_msg, signature)
def test_loopback(self): hashed_msg = SHA512.new(b("test")) signer = DSS.new(self.key_priv, 'deterministic-rfc6979') signature = signer.sign(hashed_msg) verifier = DSS.new(self.key_pub, 'deterministic-rfc6979') verifier.verify(hashed_msg, signature)
def sha512_from_str(str): sha512 = SHA512.new() sha512.update(str) return sha512.digest()
def get_file_hash(self, filename, chunksize=24 * 1024): hash = SHA512.new() with open(filename, 'rb') as f: while True: chunk = f.read(chunksize) if len(chunk) == 0: break hash.update(chunk) return hash.hexdigest()
def get_hash_module(hash_name): if hash_name == "SHA-512": hash_module = SHA512 elif hash_name == "SHA-512/224": hash_module = SHA512.new(truncate="224") elif hash_name == "SHA-512/256": hash_module = SHA512.new(truncate="256") elif hash_name == "SHA-384": hash_module = SHA384 elif hash_name == "SHA-256": hash_module = SHA256 elif hash_name == "SHA-224": hash_module = SHA224 elif hash_name == "SHA-1": hash_module = SHA1 else: raise ValueError("Unknown hash algorithm: " + hash_name) return hash_module
def DownloadFile(socket, name, key, size_uncompressed, size_compressed, buffer=2048): with open("temp.tar.gz", "wb") as f: file_hash = SHA512.new(); with Progress(TextColumn("[bold blue]{task.description}", justify="right"), BarColumn(bar_width=None), "[progress.percentage]{task.percentage:>3.1f}%", "•", DownloadColumn(), "•", TransferSpeedColumn(), "•", TimeRemainingColumn(),) as progress: task = progress.add_task(f"Downloading file(s)", total=size_compressed); while not progress.finished: select.select([client_socket], [], []); user_data = receive_message(socket); l = recieveEncryptedMessage(socket, key)["data"]; f.write(l); progress.update(task, advance=len(l)); file_hash.update(l); user_data = receive_message(socket); l = recieveEncryptedMessage(socket, key)["data"]; if l[:8] == "SFTP END".encode('utf-8'): print(f"{RT.BLUE}SFTP END{RT.RESET}"); else: print(f"{RT.RED}SFTP Did Not End! Retry File Transfer.{RT.End}"); return; split_data = l.split(CUSTOM_SEPARATOR); received_file_hash_uc = split_data[1].decode('utf-8'); received_file_hash_c = split_data[2].decode('utf-8'); if received_file_hash_c == file_hash.hexdigest(): FileDecompressor("temp.tar.gz", name); ucfilehash = SHA512.new(); for name_singular in name: with open(name_singular, "rb") as filehandle: while True: block = filehandle.read(buffer); if not block: break; ucfilehash.update(block); if received_file_hash_c == file_hash.hexdigest() and received_file_hash_uc == ucfilehash.hexdigest(): print(f"{RT.GREEN}SFTP Checksum Matched!{RT.RESET}"); else: print(f"{RT.RED}SFTP Checksum Did Not Match! File Is Corrupt{RT.RESET}");
def public_key_verify_signature(public_key, signature, message): # At the receiver side, verification can be done like using the public part of the RSA key: # RSA Signature Verification h = SHA512.new() h.update(message) verifier = PKCS.new(public_key) if verifier.verify(h, signature): return True else: return False
def gen_local_vault_keys(password, salt, mk_d, mk_iv, mk_p, ok_d, ok_iv,ok_p): p_debug('\n** Generating MasterKey (MK) and OverviewKey (OK) profile info') iter = 100000 p_data('Salt', salt, dump=False) raw_key = hashlib.pbkdf2_hmac('sha512', password, salt, iter, dklen=64) op_kek_mk = raw_key[0:32] op_kek_hmac = raw_key[32:64] p_data('Derived key', op_kek_mk) p_data('Derived HMAC key', op_kek_hmac) enc_master_key = encrypt_opdata(mk_d, op_kek_mk, op_kek_hmac, iv=mk_iv, padding=mk_p) h_raw = SHA512.new(mk_d).digest() op_mk = h_raw[0:32] op_mk_hmac = h_raw[32:64] p_data('Priv vault MK', op_mk) p_data('Priv vault MK HMAC', op_mk_hmac) enc_overview_key = encrypt_opdata(ok_d, op_kek_mk, op_kek_hmac, iv=ok_iv, padding=ok_p) h_raw = SHA512.new(ok_d).digest() op_ok = h_raw[0:32] op_ok_hmac = h_raw[32:64] p_data('Priv vault OK', op_ok) p_data('Priv vault OK HMAC', op_ok_hmac) out = {'master_key': op_mk, 'master_key_hmac': op_mk_hmac, 'overview_key': op_ok, 'overview_key_hmac': op_ok_hmac, 'enc_master_key_data': enc_master_key, 'enc_overview_key_data': enc_overview_key} return out
def checksum(data): """ Compute the checksum of arbitrary binary input. Args: data (bytes): data as bytes Returns: bytes: checksum of the data """ chksum = SHA512.new(truncate="256") chksum.update(data) return chksum.digest()
def pycrypto(): import Crypto from Crypto.Hash import MD2 from Crypto.Hash import MD4 from Crypto.Hash import MD5 from Crypto.Hash import SHA from Crypto.Hash import SHA224 from Crypto.Hash import SHA256 from Crypto.Hash import SHA384 from Crypto.Hash import SHA512 from Crypto.Hash import HMAC Crypto.Hash.MD2.new() # Noncompliant MD2.new() # Noncompliant MD4.new() # Noncompliant MD5.new() # Noncompliant SHA.new() # Noncompliant SHA224.new() # Noncompliant SHA256.new() # Noncompliant SHA384.new() # Noncompliant SHA512.new() # Noncompliant HMAC.new(b"\x00") # Noncompliant
def cryptodome(): import Cryptodome from Cryptodome.Hash import MD2 from Cryptodome.Hash import MD4 from Cryptodome.Hash import MD5 from Cryptodome.Hash import SHA1 from Cryptodome.Hash import SHA224 from Cryptodome.Hash import SHA256 from Cryptodome.Hash import SHA384 from Cryptodome.Hash import SHA512 from Cryptodome.Hash import HMAC Cryptodome.Hash.MD2.new() # Noncompliant MD2.new() # Noncompliant MD4.new() # Noncompliant MD5.new() # Noncompliant SHA1.new() # Noncompliant SHA224.new() # Noncompliant SHA256.new() # OK SHA384.new() # OK SHA512.new() # OK HMAC.new(b"\x00") # OK
def digitalSignatureVerifier(): from Cryptodome.Hash import SHA512 # Verifying the signature of Data received from Server with the server public key of the RSA key pair verifier = pkcs1_15.new(RSA.import_key(serverPublicKey)) digest = SHA512.new(data=data) if digest.digest() == serverDigest: try: # If the signaature is valid, the function will return True verifier.verify(digest, serverSignature) return True except: # If the signaature is not valid, the function will return False return False else: return False
def digitalSignatureOperation(): # Import SHA512 from Cryptodome hash from Cryptodome.Hash import SHA512 # Generating the key pair for client clientRSAKeyPair = RSA.generate(2048) # Extracting client public key from the generated key pair clientPublicKey = clientRSAKeyPair.publickey() # Generating SHA-512 digest of the AES encrypted data digest = SHA512.new(data=data) # Signing the SHA-512 digest of the AES encrypted data with the private key of the RSA key pair signer = pkcs1_15.new(clientRSAKeyPair) signature = signer.sign(digest) # Returning the digest, client public key and digital signature of a AES Encrypted Data in bytes return digest, clientPublicKey, signature
def hash(self, plaintext, salt): """ Hashes the plaintext using the given salt. Inputs: plaintext - The text to hash. salt - The salt to use in the hash. Outputs: The hashed value of the plaintext. """ hashObj = SHA512.new() hashObj.update(plaintext) hashObj.update(salt) return hashObj.digest()
def verify(message, signature, pub_key, hash="SHA256"): signer = PKCS1_v1_5.new(pub_key) if (hash == "SHA512"): digest = SHA512.new() elif (hash == "SHA384"): digest = SHA384.new() elif (hash == "SHA256"): digest = SHA256.new() elif (hash == "SHA1"): digest = SHA.new() else: digest = MD5.new() digest.update(message) return signer.verify(digest, signature)
def sign(fileIn, privKeyPath, signatureOut=None): if not signatureOut: signatureOut = fileIn + '.sign' with open(fileIn, 'rb') as f: data = f.read() with open(privKeyPath, 'rb') as f: privKey = RSA.import_key(f.read()) dataHash = SHA512.new(data) signature = pss.new(privKey).sign(dataHash) with open(signatureOut, 'w') as f: f.write(PEM.encode(signature, 'PKCS1-PSS SIGNATURE'))
def sign(message, priv_key, hashAlg="SHA-256"): global hash_type hash_type = hashAlg signer = PKCS1_v1_5.new(priv_key) if (hash_type == "SHA-512"): digest = SHA512.new() elif (hash_type == "SHA-384"): digest = SHA384.new() elif (hash_type == "SHA-256"): digest = SHA256.new() elif (hash_type == "SHA-1"): digest = SHA.new() else: digest = MD5.new() digest.update(message) return signer.sign(digest)
def esmd_kernel_digest(path): sha512 = SHA512.new() if not os.path.isfile(path): err(1, f'{path}: not found') with tempfile.NamedTemporaryFile() as temp: esmd_objcopy_run(path, temp.name) fbuf = temp.read(FILE_CHUNK_SZ) while len(fbuf) > 0: sha512.update(fbuf) fbuf = temp.read(FILE_CHUNK_SZ) kernel_size = os.path.getsize(temp.name) return sha512.digest(), kernel_size
def sign(message, priv_key, hash="SHA256"): priv_key = importKey(priv_key) signer = PKCS1_v1_5.new(priv_key) if (hash == "SHA512"): digest = SHA512.new() elif (hash == "SHA384"): digest = SHA384.new() elif (hash == "SHA256"): digest = SHA256.new() elif (hash == "SHA1"): digest = SHA.new() else: digest = MD5.new() digest.update(message) return signer.sign(digest)
def verify(fileIn, signaturePath, pubKeyPath): with open(fileIn, 'rb') as f: data = f.read() with open(signaturePath, 'r') as f: signature = PEM.decode(f.read())[0] with open(pubKeyPath, 'rb') as f: pubKey = RSA.import_key(f.read()) fileHash = SHA512.new(data) verifier = pss.new(pubKey) try: verifier.verify(fileHash, signature) return True except (ValueError, TypeError): return False
def SHA_512(file_name): print() print('SHA-512:- The hash value for ' + file_name + ' is: ') with open(file_name + ".txt", "r") as myfile: data = myfile.read() plaintext = bytes(data, 'utf-8') hash_gen = SHA512.new() t1 = datetime.now() hash_gen.update(plaintext) t2 = datetime.now() hash_time = t2 - t1 print('TIME TAKEN FOR HASHING:(micro seconds) ' + str(hash_time.microseconds)) print(hash_gen.hexdigest()) with open(file_name + "_SHA512.txt", "w") as text_file: text_file.write(hash_gen.hexdigest()) print("THE HASH FILE IS SAVED AS: " + file_name + "_SHA512.txt .....SUCCESS!") statinfo = os.stat(file_name + ".txt") size = statinfo.st_size hash_byte = hash_time.microseconds / size print("HASH SPEED PER BYTE: " + str(hash_byte))
def sha512_from_file(path): """Get sha512 of file contents. Args: path (str): Path to file. Returns: sha512 digest. """ sha512 = SHA512.new() try: with open(path, mode='rb') as input: fbuf = input.read(FILE_CHUNK_SZ) while len(fbuf) > 0: sha512.update(fbuf) fbuf = input.read(FILE_CHUNK_SZ) except OSError as e: err(1, f'{path}: {e.strerror}') return sha512.digest()
def sha512Hash(data): h = SHA512.new() h.update(bytes(data, 'utf-8')); return h.hexdigest()
# For more details: https://www.dlitz.net/software/pycrypto/api/current/Crypto.Hash-module.html from Cryptodome.Hash import MD5, SHA256, SHA512 print("Let's introduce you to some simple hashing using the PyCrypto library") print("=-=-=" * 5) # First we select the message we want to encode -- in this case the letter "a" msg = "My secret message" # All strings in Python 3 are Unicode by default # The hash functions expect to work only on bytes, so we need convert it to ASCII # This can be done by either encoding the message: msg = msg.encode("ascii") # or by initialising the string with a "b" infront of it, indiciating it's a byte string msg = b"My secret message" # or by using the bytes converter msg = bytes("My secret message", "ascii") print("We'll hash the string %s" % msg) print("MD5 Hexdigest (128 bit):") print(MD5.new(msg).hexdigest()) print("SHA256 Hexdigest (256 bit):") print(SHA256.new(msg).hexdigest()) print("SHA512 Hexdigest (512 bit):") print(SHA512.new(msg).hexdigest()) print() print() # This will pause the console on Windows machines so that the output can be read input("End of task -- press Enter")
def import_openssh_private_generic(data, password): # https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.key?annotate=HEAD # https://github.com/openssh/openssh-portable/blob/master/sshkey.c # https://coolaj86.com/articles/the-openssh-private-key-format/ # https://coolaj86.com/articles/the-ssh-public-key-format/ if not data.startswith(b'openssh-key-v1\x00'): raise ValueError("Incorrect magic value") data = data[15:] ciphername, data = read_string(data) kdfname, data = read_string(data) kdfoptions, data = read_bytes(data) number_of_keys, data = read_int4(data) if number_of_keys != 1: raise ValueError("We only handle 1 key at a time") _, data = read_string(data) # Public key encrypted, data = read_bytes(data) if data: raise ValueError("Too much data") if len(encrypted) % 8 != 0: raise ValueError("Incorrect payload length") # Decrypt if necessary if ciphername == 'none': decrypted = encrypted else: if (ciphername, kdfname) != ('aes256-ctr', 'bcrypt'): raise ValueError("Unsupported encryption scheme %s/%s" % (ciphername, kdfname)) salt, kdfoptions = read_bytes(kdfoptions) iterations, kdfoptions = read_int4(kdfoptions) if len(salt) != 16: raise ValueError("Incorrect salt length") if kdfoptions: raise ValueError("Too much data in kdfoptions") pwd_sha512 = SHA512.new(password).digest() # We need 32+16 = 48 bytes, therefore 2 bcrypt outputs are sufficient stripes = [] constant = b"OxychromaticBlowfishSwatDynamite" for count in range(1, 3): salt_sha512 = SHA512.new(salt + struct.pack(">I", count)).digest() out_le = _bcrypt_hash(pwd_sha512, 6, salt_sha512, constant, False) out = struct.pack("<IIIIIIII", *struct.unpack(">IIIIIIII", out_le)) acc = bytearray(out) for _ in range(1, iterations): out_le = _bcrypt_hash(pwd_sha512, 6, SHA512.new(out).digest(), constant, False) out = struct.pack("<IIIIIIII", *struct.unpack(">IIIIIIII", out_le)) strxor(acc, out, output=acc) stripes.append(acc[:24]) result = b"".join([bchr(a) + bchr(b) for (a, b) in zip(*stripes)]) cipher = AES.new(result[:32], AES.MODE_CTR, nonce=b"", initial_value=result[32:32 + 16]) decrypted = cipher.decrypt(encrypted) checkint1, decrypted = read_int4(decrypted) checkint2, decrypted = read_int4(decrypted) if checkint1 != checkint2: raise ValueError("Incorrect checksum") ssh_name, decrypted = read_string(decrypted) return ssh_name, decrypted
def smb3_sha512(message): return array.array('B', SHA512.new(message.tostring()).digest())