def _generate_domain(L, randfunc): """Generate a new set of DSA domain parameters""" N = {1024: 160, 2048: 224, 3072: 256}.get(L) if N is None: raise ValueError("Invalid modulus length (%d)" % L) outlen = SHA256.digest_size * 8 n = (L + outlen - 1) // outlen - 1 # ceil(L/outlen) -1 b_ = L - 1 - (n * outlen) # Generate q (A.1.1.2) q = Integer(4) upper_bit = 1 << (N - 1) while test_probable_prime(q, randfunc) != PROBABLY_PRIME: seed = randfunc(64) U = Integer.from_bytes(SHA256.new(seed).digest()) & (upper_bit - 1) q = U | upper_bit | 1 assert (q.size_in_bits() == N) # Generate p (A.1.1.2) offset = 1 upper_bit = 1 << (L - 1) while True: V = [ SHA256.new(seed + Integer(offset + j).to_bytes()).digest() for j in iter_range(n + 1) ] V = [Integer.from_bytes(v) for v in V] W = sum([V[i] * (1 << (i * outlen)) for i in iter_range(n)], (V[n] & ((1 << b_) - 1)) * (1 << (n * outlen))) X = Integer(W + upper_bit) # 2^{L-1} < X < 2^{L} assert (X.size_in_bits() == L) c = X % (q * 2) p = X - (c - 1) # 2q divides (p-1) if p.size_in_bits() == L and \ test_probable_prime(p, randfunc) == PROBABLY_PRIME: break offset += n + 1 # Generate g (A.2.3, index=1) e = (p - 1) // q for count in itertools.count(1): U = seed + b"ggen" + bchr(1) + Integer(count).to_bytes() W = Integer.from_bytes(SHA256.new(U).digest()) g = pow(W, e, p) if g != 1: break return (p, q, g, seed)
def test_very_long_data(self): cipher = AES.new(b'A' * 32, AES.MODE_CTR, nonce=b'') ct = cipher.encrypt(b'B' * 1000000) digest = SHA256.new(ct).hexdigest() self.assertEqual( digest, "96204fc470476561a3a8f3b6fe6d24be85c87510b638142d1d0fb90989f8a6a6")
def my_sha256(msg): """ sha256 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符 """ sh = SHA256.new() sh.update(msg.encode('utf-8')) return sh.hexdigest()
def verify_certificate(public_key, message, signature): message = SHA256.new(message) verifier = DSS.new(public_key, 'fips-186-3') try: verifier.verify(message, signature) print("Correct signature") except ValueError: print("Incorrect signature") pass
def hash_file(message_file): h = SHA256.new() #piece of message to hash can be passed to new() with open(message_file, "rb") as f: while True: buf = f.read(1024) #don't want to store the entire file in memory, you can transfer it in pieces. #print('check buf:',buf) if len(buf) == 0: break h.update(buf) #update to concatinate parts #print(h) #print( h.digest()) return h.digest() # hash like array baytov #Return the digest of the data passed to the update() method so far.
def key_exchange(self): #-------------------- 1 ------------------------------------------------------------------------ # -------------- Wait server Public_Key -------------------------------------------------------- # get Pickled public key pickled_server_public_key = self.socket.recv(LEN_UNIT_BUF).split(END_LINE)[0] server_public_key = pickle.loads(pickled_server_public_key) # -------------- Wait server hash Public_Key --------------------------------------------------------------------------- # Hashing original Public_Key calculated_hash_server_pickled_public_key = SHA256.new(pickle.dumps(server_public_key)).hexdigest() declared_hash_server_pickled_public_key = b64decode( self.socket.recv(LEN_UNIT_BUF).split(END_LINE)[0] ) if calculated_hash_server_pickled_public_key != declared_hash_server_pickled_public_key: return "Not Magic" #-------------------- 2 ------------------------------------------------------------------------ # ------------ Send client private key self.socket.send(pickle.dumps(self.crypto.private_key.exportKey()) + END_LINE) time.sleep(0.5) # ----------- send Base64 Hash of self.crypto.private_key self.socket.send( b64encode(SHA256.new(pickle.dumps(self.crypto.private_key.exportKey())).hexdigest()) + END_LINE) time.sleep(0.5) #-------------------- 3 ------------------------------------------------------------------------ # -------------- Send encrypted by server public key info containing symmetric key and hash symmetric key encrypted by client public key --------------------- if self.crypto.private_key.can_encrypt(): hash_sym_key = SHA256.new(self.key).hexdigest() print str(hash_sym_key) pickle_encrypt_hash_sym_key = pickle.dumps(self.crypto.private_key.publickey().encrypt(hash_sym_key, 32)) message = b64encode(self.key) + "#" + b64encode( pickle_encrypt_hash_sym_key ) print message splitted_pickled_message = [message[i:i+MAX_ENCRYPTED_MSG_SIZE] for i in xrange(0, len(message), MAX_ENCRYPTED_MSG_SIZE)] # Sending to server number of encrypted message parts self.socket.send(str(len(splitted_pickled_message)) + END_LINE) pickled_encrypted_message = '' for part in splitted_pickled_message: part_encrypted_pickled_message = server_public_key.encrypt(part, 32) pickled_part_encrypted_pickled_message = pickle.dumps(part_encrypted_pickled_message) self.socket.send(pickled_part_encrypted_pickled_message + END_LINE) pickled_encrypted_message += pickled_part_encrypted_pickled_message time.sleep(0.5)
def runTest(self): key = b'0' * 16 h = SHA256.new() for length in range(160): nonce = '{0:04d}'.format(length).encode('utf-8') data = bchr(length) * length cipher = AES.new(key, AES.MODE_GCM, nonce=nonce, **self._extra_params) ct, tag = cipher.encrypt_and_digest(data) h.update(ct) h.update(tag) self.assertEqual(h.hexdigest(), "7b7eb1ffbe67a2e53a912067c0ec8e62ebc7ce4d83490ea7426941349811bdf4")
def validate_transaction_data_consensus(transaction, blockchain): """ validates the transaction's data :param transaction: transaction to validate :type transaction: Transaction :param blockchain: blockchain to use to check transaction's validity :type blockchain: Blockchain :return: True if transaction is valid, False if not :rtype: tuple """ # validate input sources and signatures input_amount = 0 output_amount = 0 for input1 in transaction.inputs: block = blockchain.get_block_consensus_chain(input1[1]) input_transaction = block.transactions[input1[2] - 1] appears = False for source_output in input_transaction: if source_output[0] == input1[0]: appears = True input_amount += source_output[1] if not appears: return False, "transaction input's source does not appear in source block" hasher = SHA256.new(transaction.signing_format().encode("utf-8")) verifier = PKCS1_v1_5.new(RSA.import_key(input1[0])) if not verifier.verify(hasher, input1[3]): return False, "signature is not valid" # input sources and signatures are valid, check that input amount equals output amount for output in transaction.outputs: output_amount += output[1] if not output_amount - input_amount: return False, "input and output amounts are not equal" # input amount equals output amounts, validate that no transactions are a double spend for input1 in transaction.inputs: for x in range(input1[1] + 1, len(blockchain) + 1): block = blockchain.get_block_consensus_chain(x) for block_transaction in block.transactions: for input2 in block_transaction.inputs: if input2[0] == input1[0] and input2[1] == input1[ 1] and input2[2] == input1[2]: return False, "double spend" return True, ""
def test_asn1_encoding(self): """Verify ASN.1 encoding""" self.description = "ASN.1 encoding test" hash_obj = SHA256.new() signer = DSS.new(self.key_priv, 'fips-186-3', 'der') signature = signer.sign(hash_obj) # Verify that output looks like a DER SEQUENCE self.assertEqual(bord(signature[0]), 48) signer.verify(hash_obj, signature) # Verify that ASN.1 parsing fails as expected signature = bchr(7) + signature[1:] self.assertRaises(ValueError, signer.verify, hash_obj, signature)
def decrypt_and_verify(hsel, iv, ciphertext, h): #verify hashfunc = None if hsel == 'S512': hashfunc = SHA512.new() else: hashfunc = SHA256.new() hashfunc.update(ciphertext) h2 = hashfunc.digest() if h != h2: # todo: switch to timing-safe comparison print("Checksum failed") raise Exception("Hash Comparison Failed - Wrong Checksum\n") else: print("Checksum ok") #decrypt cipher = AES.new(shared_key, AES.MODE_CBC, iv) plaintext = cipher.decrypt(ciphertext).decode() return plaintext
def test1(self): q = 0x4000000000000000000020108A2E0CC0D99F8A5EF x = 0x09A4D6792295A7F730FC3F2B49CBC0F62E862272F p = 2 * q + 1 y = pow(2, x, p) key = DSA.construct([pow(y, 2, p), 2, p, q, x], False) signer = DSS.new(key, 'deterministic-rfc6979') # Test _int2octets self.assertEqual(hexlify(signer._int2octets(x)), b("009a4d6792295a7f730fc3f2b49cbc0f" "62e862272f")) # Test _bits2octets h1 = SHA256.new(b("sample")).digest() self.assertEqual(hexlify(signer._bits2octets(h1)), b("01795edf0d54db760f156d0dac04c032" "2b3a204224"))
def runTest(self): """SHA256: 512/520 MiB test""" from crypto.Hash import SHA256 zeros = bchr(0x00) * (1024 * 1024) h = SHA256.new(zeros) for i in range(511): h.update(zeros) # This test vector is from PyCrypto's old testdata.py file. self.assertEqual( '9acca8e8c22201155389f65abbf6bc9723edc7384ead80503839f49dcc56d767', h.hexdigest()) # 512 MiB for i in range(8): h.update(zeros) # This test vector is from PyCrypto's old testdata.py file. self.assertEqual( 'abf51ad954b246009dfe5a50ecd582fd5b8f1b8b27f30393853c3ef721e7fa6e', h.hexdigest()) # 520 MiB
def sign_message(private_key, message): h = SHA256.new(message) sign = DSS.new(private_key, 'fips-186-3') signature = sign.sign(h) return signature
data, address = client.recvfrom(1024) port = address[1] if str(port) == str(PORT): leaderdata = data RECV = True unpickled = pickle.loads(data) messages.append(unpickled[0].decode()) signs.append(unpickled[1]) print(messages) if len(messages) >= 3: if len(set(messages)) == 1: print("committed: ", messages[0]) else: sender = [] for i in range(len(signs)): digest = SHA256.new() digest.update(messages[i].encode()) sender.append(verifier.verify(digest, signs[i])) if all(flag == True for flag in sender) == True: print("no commit") else: signed_messages = [ messages[m] for m in range(len(sender)) if sender[m] == True ] if len(set(signed_messages)) == 1: print("committed: ", signed_messages[0]) else: print("no commit") STAGE = 'DONE'
from crypto.PublicKey import DSA from crypto.Signature import DSS from crypto.Hash import SHA256 key = DSA.generate(2048) f = open("public_key.pem", "w") f.write(key.publickey().export_key()) f.close() message = b"Hello" hash_obj = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(hash_obj) f = open("public_key.pem", "r") hash_obj = SHA256.new(message) pub_key = DSA.import_key(f.read()) verifier = DSS.new(pub_key, 'fips-186-3') try: verifier.verify(hash_obj, signature) print("The message is authentic.") except ValueError: print("The message is not authentic.")