def dataReceiver(self): while True: start = '' while start != self._message_prefix: start = (start + (yield 1))[-len(self._message_prefix):] command = (yield 12).rstrip('\0') length, = struct.unpack('<I', (yield 4)) if length > self._max_payload_length: print 'length too large' continue checksum = yield 4 payload = yield length if hashlib.sha3_256(payload).digest()[:4] != checksum: print 'invalid hash for', self.transport.getPeer().host, repr(command), length, checksum.encode('hex') if p2pool.DEBUG: print hashlib.sha3_256(payload).digest()[:4].encode('hex'), payload.encode('hex') self.badPeerHappened() continue type_ = getattr(self, 'message_' + command, None) if type_ is None: if p2pool.DEBUG: print 'no type for', repr(command) continue try: self.packetReceived(command, type_.unpack(payload, self.ignore_trailing_payload)) except: print 'RECV', command, payload[:100].encode('hex') + ('...' if len(payload) > 100 else '') log.err(None, 'Error handling message: (see RECV line)') self.disconnect()
def hasherFromString(s): import hashlib if s == 'sha1': return hashlib.sha1() elif s == 'sha224': return hashlib.sha224() elif s == 'sha256': return hashlib.sha256() elif s == 'sha384': return hashlib.sha384() elif s == 'sha512': return hashlib.sha512() elif s == 'blake2b': return hashlib.blake2b() elif s == 'blake2s': return hashlib.blake2s() elif s == 'md5': return hashlib.md5() elif s == 'sha3_224': return hashlib.sha3_224() elif s == 'sha3_256': return hashlib.sha3_256() elif s == 'sha3_384': return hashlib.sha3_384() elif s == 'sha3_512': return hashlib.sha3_512() elif s == 'shake_128': return hashlib.shake_128() elif s == 'shake_256': return hashlib.shake_256() else: return None
def handshake_mac(*args): _logger.debug('Client handshake MACing %s (%d) with key %s (%d)' % ( ascii_bin(b''.join(args[1:])), len(b''.join(args[1:])), ascii_bin(args[0]), len(args[0]))) return hashlib.sha3_256(b''.join(args)).digest()[:8]
def sha3_256(s): import hashlib import sys if sys.version_info < (3, 4): import sha3 return hashlib.sha3_256(s).digest()
def verify_tree_sha(self, node, path_to_node, hashtype): """ Verify tree elements are hashed correctly, assuming that the node is a MerkleTree, using a specific SHA hash type. """ if node.nodes is None: self.assertEqual(None, node.bin_hash) else: hash_count = 0 # pylint: disable=redefined-variable-type if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: # pylint: disable=no-member sha = hashlib.sha3_256() for node_ in node.nodes: path_to_file = os.path.join(path_to_node, node_.name) if isinstance(node_, MerkleLeaf): self.verify_leaf_sha(node_, path_to_file, hashtype) elif isinstance(node_, MerkleTree): self.verify_tree_sha(node_, path_to_file, hashtype) else: self.fail("unknown node type!") if node_.bin_hash is not None: hash_count += 1 sha.update(node_.bin_hash) # take care to compare values of the same type; # node.binHash is binary, node.hexHash is hex if hash_count == 0: self.assertEqual(None, node.bin_hash) else: self.assertEqual(sha.digest(), node.bin_hash)
def check_node(self, node, using_sha): assert node is not None pub = node.pub_key id_ = node.node_id # pylint: disable=redefined-variable-type if using_sha == QQQ.USING_SHA1: self.assertEqual(20, len(id_)) sha = hashlib.sha1() elif using_sha == QQQ.USING_SHA2: self.assertEqual(32, len(id_)) sha = hashlib.sha256() elif using_sha == QQQ.USING_SHA3: self.assertEqual(32, len(id_)) # pylint: disable=no-member sha = hashlib.sha3_256() sha.update(pub.exportKey()) expected_id = sha.digest() self.assertEqual(expected_id, id_) # make a random array of bytes count = 16 + RNG.nextInt16(256) msg = bytearray(count) RNG.nextBytes(msg) # sign it and verify that it verifies sig = node.sign(msg) self.assertTrue(node.verify(msg, sig)) # flip some bits and verify that it doesn't verify with the same sig msg[0] = msg[0] ^ 0x36 self.assertFalse(node.verify(msg, sig))
def do_test_simple_constructor(self, hashtype): """ Test constructor for specific SHA type. """ check_hashtype(hashtype) # pylint: disable=redefined-variable-type if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: sha = hashlib.sha3_256() file_name = self.rng.next_file_name(8) nnn = self.rng.some_bytes(8) sha.update(nnn) hash0 = sha.digest() leaf0 = MerkleLeaf(file_name, hashtype, hash0) self.assertEqual(file_name, leaf0.name) self.assertEqual(hash0, leaf0.bin_hash) file_name2 = file_name while file_name2 == file_name: file_name2 = self.rng.next_file_name(8) nnn = self.rng.some_bytes(8) self.rng.next_bytes(nnn) sha.update(nnn) hash1 = sha.digest() leaf1 = MerkleLeaf(file_name2, hashtype, hash1) self.assertEqual(file_name2, leaf1.name) self.assertEqual(hash1, leaf1.bin_hash) self.assertTrue(leaf0.equal(leaf0)) self.assertFalse(leaf0.equal(leaf1))
def verify_tree_sha(self, node, path_to_tree, hashtype): # we assume that the node is a MerkleTree check_hashtype(hashtype) if node.nodes is None: self.assertEqual(None, node.bin_hash) else: hash_count = 0 # pylint: disable=redefined-variable-type if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: # pylint: disable=no-member sha = hashlib.sha3_256() for node_ in node.nodes: path_to_node = os.path.join(path_to_tree, node_.name) if isinstance(node_, MerkleLeaf): self.verify_leaf_sha(node_, path_to_node, hashtype) elif isinstance(node_, MerkleTree): self.verify_tree_sha(node_, path_to_node, hashtype) else: print("DEBUG: unknown node type!") self.fail("unknown node type!") if node_.bin_hash is not None: hash_count += 1 sha.update(node_.bin_hash) if hash_count == 0: self.assertEqual(None, node.bin_hash) else: self.assertEqual(sha.digest(), node.bin_hash)
def get_utxoset_merkle_root(self): """Returns the merkle root of the utxoset. This implies that the utxoset is first put into a merkle tree. For now, the merkle tree and its root will be computed each time. This obviously is not efficient and a better approach that limits the repetition of the same computation when unnecesary should be sought. For instance, future optimizations could simply re-compute the branches of the tree that were affected by a change. The transaction hash (id) and output index should be sufficient to uniquely identify a utxo, and consequently only that information from a utxo record is needed to compute the merkle root. Hence, each node of the merkle tree should contain the tuple (txid, output_index). .. important:: The leaves of the tree will need to be sorted in some kind of lexicographical order. Returns: str: Merkle root in hexadecimal form. """ utxoset = backend.query.get_unspent_outputs(self.connection) # TODO Once ready, use the already pre-computed utxo_hash field. # See common/transactions.py for details. hashes = [ sha3_256( '{}{}'.format(utxo['transaction_id'], utxo['output_index']).encode() ).digest() for utxo in utxoset ] # TODO Notice the sorted call! return merkleroot(sorted(hashes))
def handshake_mac(*args): print('Test MACing %s (%d) with key %s (%d)' % ( ascii_bin(b''.join(args[1:])), len(b''.join(args[1:])), ascii_bin(args[0]), len(args[0]))) return hashlib.sha3_256(b''.join(args)).digest()[:8]
def test_sha3256(self): """ Test SHA3-256 hash. """ if "sha3_256" not in hashlib.algorithms_available: pass else: assert bh.hashlib_hash("tempfile.txt", hashlib.sha3_256()) == "a9797b62d8b3573c9134406f42e601219e086150e6c2f32c90c5cee0149b6877"
def sha3_256Encode(self, text): if not os.path.isfile(str(text)): if not text: return "No String passed to method" else: m = hashlib.sha3_256() m.update(text.encode('utf-8')) return (m.hexdigest()) else: BLOCKSIZE = 65536 hasher = hashlib.sha3_256() with open(text, 'rb') as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) return (hasher.hexdigest())
def mac(k,m): def htonll(num): return struct.pack('!q', num) s = sha3_256() s.update(htonll(len(k))) s.update(k) s.update(m) return s.digest()
def test_get_seedhash(): assert pyethash.get_seedhash(0).encode('hex') == '0' * 64 import hashlib, sha3 expected = pyethash.get_seedhash(0) #print "checking seed hashes:", for i in range(0, 30000*2048, 30000): #print i // 30000, assert pyethash.get_seedhash(i) == expected expected = hashlib.sha3_256(expected).digest()
def bogonsHasChanged(self, newFile): if sys.version_info < (3, 4): import sha3 hf = hashlib.sha3_256() hf.update(newFile) if hf.hexdigest() == self.bogonsHash: return False self.bogonsHash = hf.hexdigest() return True
def do_test_random_dir(self, hashtype): """ Test building random directories with specific SHA hash type. """ check_hashtype(hashtype) depth = 1 + self.rng.next_int16(3) # so 1 to 3 width = 1 + self.rng.next_int16(16) # so 1 to 16 blk_count = 1 + self.rng.next_int16(3) # so 1 to 3 # last block will usually be only partically populated max_len = BuildList.BLOCK_SIZE * (blk_count - 1) +\ self.rng.next_int16(BuildList.BLOCK_SIZE) min_len = 1 # we want the directory name to be unique path_to_dir = os.path.join('tmp', self.rng.next_file_name(8)) while os.path.exists(path_to_dir): path_to_dir = os.path.join('tmp', self.rng.next_file_name(8)) self.rng.next_data_dir(path_to_dir, depth, width, max_len, min_len) data = bytearray(max_len) # that many null bytes self.rng.next_bytes(data) # fill with random data if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: # pylint:disable=no-member sha = hashlib.sha3_256() elif hashtype == HashTypes.BLAKE2B: sha = hashlib.blake2b(digest_size=32) else: raise NotImplementedError sha.update(data) hash_ = sha.hexdigest() file_name = self.rng.next_file_name(8) path_to_file = os.path.join('tmp', file_name) while os.path.exists(path_to_file): file_name = self.rng.next_file_name(8) path_to_file = os.path.join('tmp', file_name) with open(path_to_file, 'wb') as file: file.write(data) if hashtype == HashTypes.SHA1: file_hash = file_sha1hex(path_to_file) elif hashtype == HashTypes.SHA2: file_hash = file_sha2hex(path_to_file) elif hashtype == HashTypes.SHA3: file_hash = file_sha3hex(path_to_file) elif hashtype == HashTypes.BLAKE2B: file_hash = file_blake2b_hex(path_to_file) else: raise NotImplementedError self.assertEqual(hash_, file_hash)
def populate_tree(self, tree, data_path, u_dir, hashtype): """ Generate nnn and nnn unique random values, where nnn is at least 16. """ nnn = 16 + self.rng.next_int16(16) # DEBUG # print("nnn = %d" % nnn) # EnnnD values = [] hashes = [] for count in range(nnn): # generate datum ------------------------------ datum = self.rng.some_bytes(32 + self.rng.next_int16(32)) values.append(datum) # generate hash = bin_key ---------------------- if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: sha = hashlib.sha3_256() elif hashtype == HashTypes.BLAKE2B: sha = hashlib.blake2b(digest_size=32) else: raise NotImplementedError sha.update(datum) bin_key = sha.digest() hex_key = sha.hexdigest() hashes.append(bin_key) # write data file ----------------------------- file_name = 'value%04d' % count path_to_file = os.path.join(data_path, file_name) with open(path_to_file, 'wb') as file: # DEBUG # print("writing %s to %s" % (hex_key, path_to_file)) # END file.write(datum) # insert leaf into tree ----------------------- # path_from_top = os.path.join(top_name, file_name) leaf = NLHLeaf(file_name, bin_key, hashtype) tree.insert(leaf) # DEBUG # print(" inserting <%s %s>" % (leaf.name, leaf.hex_hash)) # END # write data into uDir ------------------------ u_dir.put_data(datum, hex_key) return values, hashes
def sendPacket(self, command, payload2): if len(command) >= 12: raise ValueError('command too long') type_ = getattr(self, 'message_' + command, None) if type_ is None: raise ValueError('invalid command') #print 'SEND', command, repr(payload2)[:500] payload = type_.pack(payload2) if len(payload) > self._max_payload_length: raise TooLong('payload too long') data = self._message_prefix + struct.pack('<12sI', command, len(payload)) + hashlib.sha3_256(payload).digest()[:4] + payload self.traffic_happened.happened('p2p/out', len(data)) self.transport.write(data)
def sha3_convert(function_name, param_types): data = function_name + "(" param_string = param_types[0] for i in range(1, len(param_types)): param_string += "," param_string += param_types[i] data += param_string data += ")" # Do conversion send first 8 characters [0:8] (+ 0x) s = hashlib.sha3_256() # alternative s.update(data) return s.hexdigest()[0:8]
def __init__(self, path, hashtype=HashTypes.SHA2, binding=False, tree=None, ex_re=None, # exclusions, which are Regular Expressions match_re=None): # matches, also Regular Expressions check_hashtype(hashtype) if path is None: raise RuntimeError("null MerkleDoc path") if tree: if not isinstance(tree, MerkleTree): raise RuntimeError('tree is not a MerkleTree') self._name = name = tree.name elif not binding: raise RuntimeError('null MerkleTree and not binding') else: raise RuntimeError("MerkleDoc binding not yet implemented") super().__init__(name, is_leaf=False, hashtype=hashtype) path = path.strip() if len(path) == 0: raise RuntimeError("empty path") if not path.endswith('/'): path += '/' self._path = path self._tree = tree if tree: # DEBUG #print("MerkleDoc.__init__: usingSHA = %s" % str(usingSHA)) # END # pylint:disable=redefined-variable-type if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: # pylint: disable=no-member sha = hashlib.sha3_256() sha.update(bytes(tree.bin_hash)) sha.update(path.encode('utf-8')) self._bin_hash = bytes(sha.digest()) # a binary value self._ex_re = ex_re self._match_re = match_re if binding: path_to_dir = os.path.join(path, tree.name) if not os.path.exists(path_to_dir): raise RuntimeError('no directory found at ' + path_to_dir) else: # XXX STUB: BIND THE TREE self._bound = True
def generate_unique_download_key(torrent_info_hash, user_download_key): if isinstance(torrent_info_hash, str): torrent_info_hash = a2b_hex(torrent_info_hash) if isinstance(user_download_key, UUID): user_download_key = user_download_key.bytes elif isinstance(user_download_key, str): user_download_key = a2b_hex(user_download_key.replace('-', '')) m = sha3_256() m.update(torrent_info_hash) m.update(user_download_key) return m.hexdigest()
def do_test_with_simple_tree(self, hashtype): """ XXX STUB: test simple tree with specific hash. """ if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: # pylint:disable=no-member sha = hashlib.sha3_256() elif hashtype == HashTypes.BLAKE2B: sha = hashlib.blake2b(digest_size=32) else: raise NotImplementedError assert sha # suppress warning
def verify_leaf_sha(self, node, path_to_file, hashtype): check_hashtype(hashtype) self.assertTrue(os.path.exists(path_to_file)) with open(path_to_file, "rb") as file: data = file.read() self.assertFalse(data is None) # pylint: disable=redefined-variable-type if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: # pylint: disable=no-member sha = hashlib.sha3_256() sha.update(data) hash_ = sha.digest() self.assertEqual(hash_, node.bin_hash)
def test_sha3(): sender = b'\x00\xb625+E\x06\x96\xbe\x10\x0e\xdc!58?\x00\x83\xa4\x99' nonce = b'' b = rlp.encode([sender, nonce]) assert b == b'\xd6\x94\x00\xb625+E\x06\x96\xbe\x10\x0e\xdc!58?\x00\x83\xa4\x99\x80' contract_id = hashlib.sha3_256(b).digest() assert contract_id == b'"Y[\xe7^\xe8\xba\r\xcc\xc2\xe5(\xe6\xc9\xed\xa9\x81w\x1a2\x17\xed\xa4\xf9?\x9c\xe3\xc3)\x16\x13\x99' contract_id = contract_id[12:] assert contract_id == b'\xe6\xc9\xed\xa9\x81w\x1a2\x17\xed\xa4\xf9?\x9c\xe3\xc3)\x16\x13\x99' contract_id = binascii.hexlify(contract_id).decode('ascii') assert contract_id == 'e6c9eda981771a3217eda4f93f9ce3c329161399' assert utils.contract_sha3(b) == 'e6c9eda981771a3217eda4f93f9ce3c329161399'
def make_leaf(self, names_so_far, hashtype): """ Build a leaf with random name and data using specific hash. """ while True: name = self.rng.next_file_name(8) if name not in names_so_far: names_so_far.add(name) break nnn = self.rng.some_bytes(8) # 8 quasi-random bytes if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: sha = hashlib.sha3_256() sha.update(nnn) return NLHLeaf(name, sha.digest(), hashtype)
def do_test_simple_constructor(self, hashtype): """ Test constructor for specific hash. """ check_hashtype(hashtype) if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: sha = hashlib.sha3_256() elif hashtype == HashTypes.BLAKE2B: sha = hashlib.blake2b(digest_size=32) else: raise NotImplementedError name = self.rng.next_file_name(8) nnn = self.rng.some_bytes(8) self.rng.next_bytes(nnn) sha.update(nnn) hash0 = sha.digest() leaf0 = NLHLeaf(name, hash0, hashtype) self.assertEqual(name, leaf0.name) self.assertEqual(hash0, leaf0.bin_hash) name2 = name while name2 == name: name2 = self.rng.next_file_name(8) nnn = self.rng.some_bytes(8) self.rng.next_bytes(nnn) sha.update(nnn) hash1 = sha.digest() leaf1 = NLHLeaf(name2, hash1, hashtype) self.assertEqual(name2, leaf1.name) self.assertEqual(hash1, leaf1.bin_hash) self.assertEqual(leaf0, leaf0) self.assertEqual(leaf1, leaf1) self.assertFalse(leaf0 == leaf1) leaf0c = leaf0.clone() self.assertEqual(leaf0c, leaf0) leaf1c = leaf1.clone() self.assertEqual(leaf1c, leaf1)
def get_engine(hashtype): """ Get hashlib engine from hash type. :param hashtype: Hash type. :type hashtype: str """ hashengines = {"md5": hashlib.md5(), "sha1": hashlib.sha1(), "sha224": hashlib.sha224(), "sha256": hashlib.sha256(), "sha384": hashlib.sha384(), "sha512": hashlib.sha512()} if utilities.new_enough(6): hashengines.update({"sha3224": hashlib.sha3_224(), "sha3256": hashlib.sha3_256(), "sha3384": hashlib.sha3_384(), "sha3512": hashlib.sha3_512()}) return hashengines[hashtype]
def genMeta(path, formdata,filename): start = timeit.default_timer() size = os.path.getsize(path) #filename = os.path.basename(path) dataid = str(uuid.uuid4()) checksum = hashlib.new("sha3_256") checksum = hashlib.sha3_256() with open(path, 'rb') as f: checksum.update(f.read()) f.close() if 'timestamp' in formdata.keys(): timestamp = formdata['timestamp'] else: timestamp = str(int(time.time())) if 'often' in formdata.keys(): often = 'true' else: often = 'false' if 'description' in formdata.keys(): description = formdata['description'] else: description = '' rowkey = formdata['sysid']+'-'+formdata['userid']+'-'+timestamp+'-'+dataid stop=timeit.default_timer() app.logger.debug('Time to genMeta is %f' % (stop-start)) return { 'sysid': formdata['sysid'], 'userid': formdata['userid'], 'timestamp': timestamp, 'dataid': dataid, 'filename': filename, 'size': size, 'checksum': checksum.hexdigest(), 'rowkey': rowkey, 'often': often, 'description': description, }
def make_committer_id(pubkey, hashtype=HashTypes.SHA2): """ Create a unique committer ID derived from the user's RSA public key using this SHA type. This implementation adds the current time to the hash. Returns a 40- or 64-character hex value. """ if hashtype == HashTypes.SHA1: sha = hashlib.sha1() elif hashtype == HashTypes.SHA2: sha = hashlib.sha256() elif hashtype == HashTypes.SHA3: sha = hashlib.sha3_256() elif hashtype == HashTypes.BLAKE2B: sha = hashlib.blake2b(digest_size=32) else: raise NotImplementedError sha.update(pubkey.exportKey()) # PEM format sha.update(str(time.time()).encode('utf-8')) return sha.hexdigest()
def GetHash(self): protobuf = infiniti_pb2.Identity() protobuf.version = self.Version() protobuf.fingerprint = self.Fingerprint() return hashlib.sha3_256(protobuf.SerializeToString()).digest()
def GetHash(self): tmp = self.Signature() self.protobuf.signature = '' h = hashlib.sha3_256(self.protobuf.SerializeToString()).digest() self.protobuf.signature = tmp return h
def hash(message): h = hashlib.sha3_256 () h.update ( message ) return h.hexdigest()
def set_token_and_expiration(self, expiration=60 * 60 * 1) -> None: self._expiration_timestamp = int(time.time() + expiration) self._token = hashlib.sha3_256( (uuid.uuid4().hex + self._user.user_id()).encode('utf-8')).hexdigest()
def hash(block): block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha3_256(block_string).hexdigest()
def addUserFromUrl(first_name, age, password): passhash = hashlib.sha3_256(password.encode('utf-8')).hexdigest() Db.session.add(User(first_name=first_name, age=age, passhash=passhash)) Db.session.commit() return redirect(url_for('index'))
def setup(self, arg): self.h = hashlib.sha3_256()
def get_filename(query): q_hash = hashlib.sha3_256(bytearray(query, encoding="UTF-8")).hexdigest() filename = join(constants.RESULT_DIR, q_hash) return filename
def main(): seed("entourage") # to obtain the same results balances = open( "AccountBalances.txt", "w" ) # will contain the balances of the all the accounts after every transaction chain = open( "LongestChain_UNIX-Linux.txt", "w" ) # will contain the bitcoin transactions as stated in the homework document accounts = initiate() # initiate the accounts listAccounts("Before Any Transaction", accounts, balances) # list accounts before any transaction prevHash = "First transaction" # 10 transactions in total for i in range(10): s = "*** Bitcoin transaction ***\n" # serial is a random 128-bit integer serial = randint(0, 2**128 - 1) s += "Serial number: " + str(serial) + "\n" # select a payer, payee and an amount, all randomly payer_index, payee_index = -1, -1 while payer_index == payee_index or accounts[payer_index][ "balance"] == 0: payer_index = randint(0, len(accounts) - 1) payee_index = randint(0, len(accounts) - 1) payer, payee, amount = accounts[payer_index]["name"], accounts[ payee_index]["name"], randint(1, accounts[payer_index]["balance"]) s += "Payer: " + str(payer) + "\n" s += "Payee: " + str(payee) + "\n" s += "Amount: " + str(amount) + " Satoshi" + "\n" s += "Previous hash in the chain: " + prevHash + "\n" # find a suitable nonce and compute proof of work while True: # nonce is obtained with a random 128-bit integer nonce = "Nonce: " + str(randint(0, 2**128 - 1)) + "\n" possible = s + nonce hashed = hashlib.sha3_256(possible).hexdigest() # check if it meets the criteria if hashed[:6] == "000000": break s = possible s += "Proof of Work: " + hashed + "\n" chain.write(s) # perform transaction accounts[payer_index]["balance"] -= amount accounts[payee_index]["balance"] += amount # list accounts after each transaction listAccounts("After Transaction #" + str(i + 1), accounts, balances) prevHash = hashed # list accounts after all transactions listAccounts("After All Transactions", accounts, balances) balances.close() chain.close()
if pk == b'': sys.exit("Error: Not registered on the smart contract, contact operator to register.") elif verbose: print("My assigned public key is:", pk) if verbose: print("My order is:", order_string) # generate random 32 byte nonce nonce = os.urandom(32) # append nonce and encode order string order_bytes = order_string.encode('utf-8') + nonce # encrypt order bytes order_ciphertext = encrypt(pk, order_bytes) # hash ciphertext order_hash = hashlib.sha3_256(order_ciphertext).digest() # send commitment # build transaction tx = darkPool.functions.commit_order(order_hash).buildTransaction({ 'from': addr, 'nonce': w3.eth.getTransactionCount(addr), 'gas': 6721975, # from truffle docs 'gasPrice': 100000000000 # from truffle docs }) # sign transaction sign_tx = w3.eth.account.signTransaction(tx, key) # send the transaction tx_hash = w3.eth.sendRawTransaction(sign_tx.rawTransaction) # wait for transaction receipt tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash, timeout=300)
def _sha3_256_clicked(self): self.hash_function = hashlib.sha3_256() self._update_label1("SHA3-256")
def sha3_256(cls, bytestr: bytes) -> bytes: return hashlib.sha3_256(bytestr).digest()
import binascii import hashlib text = 'Hello world!' data = text.encode('utf-8') sha256hash = hashlib.sha256(data).digest() print(f'SHA-256:\t{binascii.hexlify(sha256hash).decode()}') sha3_256 = hashlib.sha3_256(data).digest() print(f'SHA3-256:\t{binascii.hexlify(sha3_256).decode()}') blake2s = hashlib.new('blake2s', data).digest() print(f'BLAKE2s:\t{binascii.hexlify(blake2s).decode()}') ripemd160 = hashlib.new('ripemd160', data).digest() print(f'RIPEMD-160:\t{binascii.hexlify(ripemd160).decode()}')
input_username = argv[1] if input_username == "guest": enable_cli = control.read_record("enable_cli", "/etc/guest") if enable_cli == "Yes": ## Set variables ## user = "******" code = "*" ## Create info ## files.write("/proc/info/su", input_username) shell() sys.exit(0) else: colors.show(input_username, "fail", "user not found.") else: input_password = argv[2] hashname = hashlib.sha3_256(str(input_username).encode()).hexdigest() hashcode = hashlib.sha3_512(str(input_password).encode()).hexdigest() if files.isfile("/etc/users/" + input_username): username = control.read_record("username", "/etc/users/" + input_username) password = control.read_record("code", "/etc/users/" + input_username) if username == hashname and password == hashcode: ## Set variables ## user = input_username code = input_password ## Create info ## files.write("/proc/info/su", input_username) permissions.user = user permissions.code = code
def _get_hash(data): hasher = hashlib.sha3_256() hasher.update(data) # always returns string of len 1+64 return 'H' + hasher.hexdigest()
def SHA3(value): return sha3_256(value.encode('utf-8')).hexdigest()
# built-in hash lib import hashlib from cryptography.fernet import Fernet # print(hashlib.algorithms_available) hash_obj = hashlib.sha3_256() # b - byte string Hello hash_obj.update(b"Hello") print(hash_obj.hexdigest()) key = Fernet.generate_key() cipher = Fernet(key) print(cipher.encrypt(b"Hello")) # Message can be descrypted using the key
def valid_proof(last_proof, proof, last_hash): guess = f'{last_proof}{proof}{last_hash}'.encode() hashGuess = hashlib.sha3_256(guess).hexdigest() return hashGuess[0:4] == "0000"
def get_message_id( parsed_message: Message, options_use_checksum=False, options_use_id_in_checksum=False, ) -> Optional[str]: """ Normally, return the Message-ID header (or print a warning if it doesn't exist and return None). If options_use_checksum is specified, use md5 hash of several headers instead. For more safety, user should first do a dry run, reviewing them before deletion. Problems are extremely unlikely, but md5 is not collision-free. If options_use_id_in_checksum is specified, then the Message-ID will be included in the header checksum, otherwise it is excluded. """ try: if options_use_checksum: md5 = hashlib.md5() sha = hashlib.sha256() sha3 = hashlib.sha3_256() def update(x): md5.update(x) sha.update(x) sha3.update(x) update(("From:" + str_header(parsed_message, "From")).encode()) update(("To:" + str_header(parsed_message, "To")).encode()) update( ("Subject:" + str_header(parsed_message, "Subject")).encode()) update(("Date:" + str_header(parsed_message, "Date")).encode()) update(("Cc:" + str_header(parsed_message, "Cc")).encode()) update(("Bcc:" + str_header(parsed_message, "Bcc")).encode()) if options_use_id_in_checksum: update(("Message-ID:" + str_header(parsed_message, "Message-ID")).encode()) msg_id = md5.hexdigest() + "|" + sha.hexdigest( ) + "|" + sha3.hexdigest() # print(msg_id) else: msg_id = str_header(parsed_message, "Message-ID") if not msg_id: print(("Message '%s' dated '%s' has no Message-ID header." % ( str_header(parsed_message, "Subject"), str_header(parsed_message, "Date"), ))) print("You might want to use the -c option.") return None return msg_id.lstrip() except (ValueError, HeaderParseError): print( "WARNING: There was an exception trying to parse the headers of this message." ) print("It may be corrupt, and you might consider deleting it.") print(("Subject: %s\nFrom: %s\nDate: %s\n" % ( parsed_message["Subject"], parsed_message["From"], parsed_message["Date"], ))) print("Message skipped.") return None
def log_in(user, pas): global username, password global conn, sha, fo print("_______Login Database________") # Logging in to database username = user password = pas conn = sqlite3.connect('test.db') print("opened database successfully") sha = hashlib.sha3_256((username + password).encode( 'utf-8')).hexdigest() # Finding hash of entered username and password fo = open("hash.txt", "r") if sha == fo.read( ): # Comparing calculated hash with hash value stored in file print("Logged In successfully!") fo = open("iv", "rb") iv = fo.read( ) # Reading initialization vector for decrypting by using 3 DES fo.close() decrypt_file('privkey.enc', 'privkey.dec', 8192, pad(password), iv) # Decrypting private key by using 3 DES fo = open('privkey.dec', 'rb') privkey = fo.read() # Reading decrypted private key to variable fo.close() os.remove( "privkey.dec" ) # Deleting decrypted key file inorder to prevent key leakage privkey = RSA.importKey(privkey) # Importing key to algorithm cursor = conn.execute( "SELECT id, title, url, username, password FROM INTERNET") i = 0 for row in cursor: i += 1 print("ID = ", row[0]) print("Title = ", row[1]) print("URL= ", row[2]) print("Username = "******"Password = "******"\n") # Printing Decrypted password # pas_list.append(pas.decode('utf-8')) sql = (' UPDATE INTERNET\n' ' SET password = ?\n' ' WHERE id = ?') cur = conn.cursor() cur.execute(sql, ( pas, i, )) ############################################################################## cursor = conn.execute( "SELECT id, title, url, username, password FROM EMAILS") i = 0 for row in cursor: i += 1 print("ID = ", row[0]) print("Title = ", row[1]) print("URL= ", row[2]) print("Username = "******"Password = "******"\n") # Printing Decrypted password # pas_list.append(pas.decode('utf-8')) sql = (' UPDATE EMAILS\n' ' SET password = ?\n' ' WHERE id = ?') cur = conn.cursor() cur.execute(sql, ( pas, i, )) ############################################################################## cursor = conn.execute("SELECT id, title, url, password FROM PINS") i = 0 for row in cursor: i += 1 print("ID = ", row[0]) print("Title = ", row[1]) print("URL= ", row[2]) pas = row[3] # pas = privkey.decrypt(pas) # Decrypting password using RSA pas_tuple = ast.literal_eval( pas) # Converting encrypted string to tuple pas = privkey.decrypt(pas_tuple) # Decrypting password using RSA # pas = privkey.decrypt(pas) # Decrypting password using RSA pas = pas.decode('utf-8') print("Password = "******"\n") # Printing Decrypted password # pas_list.append(pas.decode('utf-8')) sql = (' UPDATE PINS\n' ' SET password = ?\n' ' WHERE id = ?') cur = conn.cursor() cur.execute(sql, ( pas, i, )) ############################################################################## cursor = conn.execute( "SELECT id, title, url, username, password FROM OTHERS") i = 0 for row in cursor: i += 1 print("ID = ", row[0]) print("Title = ", row[1]) print("URL= ", row[2]) print("Username = "******"Password = "******"\n") # Printing Decrypted password # pas_list.append(pas.decode('utf-8')) sql = (' UPDATE OTHERS\n' ' SET password = ?\n' ' WHERE id = ?') cur = conn.cursor() cur.execute(sql, ( pas, i, )) ############################################################################## conn.commit() conn.close() return 1 else: # If enteres password is wrong deny access by generating honeywords print("Access Denied") copyfile('test.db', 'fake.db') bstring = sha[0:30] adder = sha[30:57] hex_str = bstring hex_int = int(hex_str, 16) bstring2 = hex_int + 0x200 hex_str = adder hex_int = int(hex_str, 16) adder2 = hex_int + 0x200 conn = sqlite3.connect('fake.db') cursor = conn.execute("SELECT id, password FROM INTERNET") add = bstring2 i = 0 for row in cursor: i += 1 pas = gen_honey(add) add = add + adder2 sql = (' UPDATE INTERNET\n' ' SET password = ?\n' ' WHERE id = ?') cur = conn.cursor() cur.execute(sql, ( pas, i, )) #################################################################################### cursor = conn.execute("SELECT id, password FROM EMAILS") i = 0 for row in cursor: i += 1 pas = gen_honey(add) add = add + adder2 sql = (' UPDATE EMAILS\n' ' SET password = ?\n' ' WHERE id = ?') cur = conn.cursor() cur.execute(sql, ( pas, i, )) #################################################################################### cursor = conn.execute("SELECT id, password FROM PINS") i = 0 for row in cursor: i += 1 pas = gen_honey(add) add = add + adder2 sql = (' UPDATE PINS\n' ' SET password = ?\n' ' WHERE id = ?') cur = conn.cursor() cur.execute(sql, ( pas, i, )) #################################################################################### cursor = conn.execute("SELECT id,password FROM OTHERS") i = 0 for row in cursor: i += 1 pas = gen_honey(add) add = add + adder2 sql = (' UPDATE OTHERS\n' ' SET password = ?\n' ' WHERE id = ?') cur = conn.cursor() cur.execute(sql, ( pas, i, )) #################################################################################### conn.commit() conn.close() return 0
def sha3_256Hash(msg): hashBytes = hashlib.sha3_256(msg.encode("utf8")).digest() return int.from_bytes(hashBytes, byteorder="big")
with open(filename, 'w') as f: f.write(b''.join(vector).decode('utf-8').lstrip()) else: binpath = os.path.join("bin-host", binary) print("Running {}..".format(binpath)) filename = os.path.join('testvectors/', primitive, scheme, "host") os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, 'w') as f: subprocess.run([binpath], stdout=f, stderr=subprocess.DEVNULL) print(" .. wrote test vectors!") if not os.path.isdir('testvectors'): sys.exit(0) print("Testing if test vectors are consistent..") for primitive in os.listdir('testvectors'): for scheme in os.listdir(os.path.join('testvectors', primitive)): print(" .. {}: ".format(os.path.join(primitive, scheme)), end='') hashes = dict() for impl in os.listdir(os.path.join('testvectors', primitive, scheme)): path = os.path.join('testvectors', primitive, scheme, impl) with open(path, 'rb') as file: hashes[file.name] = hashlib.sha3_256(file.read()).hexdigest() if len(set(hashes.values())) <= 1: print("passed.") else: print("FAILED!") for file, checksum in hashes.items(): print((" {: <{width}} sha3:{}").format( file, checksum, width=max(len(file) for file in hashes)))
#!/usr/bin/env python3 """ @ Desc: @ Author: Byron @ Date: """ # import the library module import hashlib # initialize a string str = "www.MyTecBits.com" # encode the string encoded_str = str.encode() # create sha3 hash objects initialized with the encoded string obj_sha3_224 = hashlib.sha3_224(encoded_str) # SHA3-224 obj_sha3_256 = hashlib.sha3_256(encoded_str) # SHA3-256 obj_sha3_384 = hashlib.sha3_384(encoded_str) # SHA3-384 obj_sha3_512 = hashlib.sha3_512(encoded_str) # SHA3-512 # print in hexadecimal print("\nSHA3-224 Hash: ", obj_sha3_224.hexdigest()) print("\nSHA3-256 Hash: ", obj_sha3_256.hexdigest()) print("\nSHA3-384 Hash: ", obj_sha3_384.hexdigest()) print("\nSHA3-512 Hash: ", obj_sha3_512.hexdigest())
def test_get_utxoset_merkle_root_when_no_utxo(b): assert b.get_utxoset_merkle_root() == sha3_256(b'').hexdigest()
'range': range, 'repr': repr, 'reversed': reversed, 'round': round, 'sorted': sorted, 'zip': zip, # decimal 'Decimal': Decimal, # hash algorithm 'sha1': lambda *x: hashlib.sha1(*x).hexdigest(), 'sha224': lambda *x: hashlib.sha224(*x).hexdigest(), 'sha256': lambda *x: hashlib.sha256(*x).hexdigest(), 'sha384': lambda *x: hashlib.sha384(*x).hexdigest(), 'sha512': lambda *x: hashlib.sha512(*x).hexdigest(), 'sha3_224': lambda *x: hashlib.sha3_224(*x).hexdigest(), 'sha3_256': lambda *x: hashlib.sha3_256(*x).hexdigest(), 'sha3_384': lambda *x: hashlib.sha3_384(*x).hexdigest(), 'sha3_512': lambda *x: hashlib.sha3_512(*x).hexdigest(), 'md5': lambda *x: hashlib.md5(*x).hexdigest(), # datetime 'date': datetime.date, 'time': datetime.time, 'datetime': datetime.datetime, 'timedelta': datetime.timedelta, 'tzinfo': datetime.tzinfo, 'timezone': datetime.timezone, # module level injection 'functools': functools, 'itertools': itertools, 'math': math, 'operator': operator,
def GetHash(self): return hashlib.sha3_256(self.protobuf.SerializeToString()).digest()
def shell(): print() if user == "root": files.write("/proc/info/pwd", "/root") else: files.write("/proc/info/pwd", "/desk/" + user) select = files.readall("/proc/info/sel") # Change selected database while True: if not files.isfile("/proc/selected"): files.write("/proc/info/sel", "/proc/" + str(switch)) ## Write this controller ## Check the switched process ## process.check(switch) # Check the switched process files.write("/proc/info/sp", str(switch)) # Write switched process if files.isfile("/tmp/su.tmp"): files.remove("/tmp/su.tmp") ## User configure check ## files.write("/proc/info/su", user) # Write user name in info processor if not user == "guest": hashname = hashlib.sha3_256(str(user).encode()).hexdigest() username = control.read_record("username", "/etc/users/" + user) hashcode = hashlib.sha3_512(str(code).encode()).hexdigest() password = control.read_record("code", "/etc/users/" + user) if not (hostname == username) and not (password == hashcode): colors.show("shell", "fail-start", "") colors.show("kernel", "stop", "") sys.exit(0) ## PWD path setting up at all ## if not user == "root": if not files.isdir("/desk/" + user): files.mkdir("/desk/" + user) # Create home folder ## Prompt data base ## show_username = control.read_record("show_username", "/etc/prompt") show_hostname = control.read_record("show_hostname", "/etc/prompt") show_path = control.read_record("show_path", "/etc/prompt") root_symbol = control.read_record("root", "/etc/prompt") user_symbol = control.read_record("user", "/etc/prompt") ## Setting up prompt data base 2 ## color_uh = "" color_path = "" prompt_symbol = "" if user == "root": prompt_symbol = root_symbol color_uh = colors.get_colors() color_path = colors.get_colors() else: prompt_symbol = user_symbol color_uh = colors.get_ok() color_path = colors.get_path() ## Setting up space of prompt ## if show_username == "Yes": space_username = user else: space_username = "" if show_hostname == "Yes": space_hostname = hostname else: space_hostname = "" if show_path == "Yes": space_path = files.readall("/proc/info/pwd") else: space_path = "" if show_hostname == "Yes" and show_username == "Yes": space1 = "@" else: space1 = "" if (show_hostname == "Yes" or show_username == "Yes") and show_path == "Yes": space2 = ":" else: space2 = "" ## Shell prompt ## cmd = input(color_uh + space_username + space1 + space_hostname + colors.get_colors() + space2 + color_path + space_path + colors.get_colors() + prompt_symbol + " ") cmdln = cmd.split(" ") strcmdln = "" for i in cmdln: if str(i).startswith("$"): select = files.readall("/proc/info/sel") var = control.read_record(str(i).replace("$", ""), select) if var == None: strcmdln = strcmdln + " " + i else: strcmdln = strcmdln + " " + var else: strcmdln = strcmdln + " " + i ## Command line ## cmdln = strcmdln.split(" ") cmdln.remove('') ## All commands run in here ## ## New command ## if cmdln[0] == "new": files.create("/tmp/su.tmp") control.write_record("username", user, "/tmp/su.tmp") control.write_record("code", code, "/tmp/su.tmp") ## Other commands ## if (cmdln == [] or cmdln[0] == "" or cmdln[0] == " " or cmd.startswith("#") or cmd.startswith("//") or (cmd.startswith("/*") and cmd.endswith("*/")) or (cmd.startswith("\'\'\'") and cmd.endswith("\'\'\'")) or cmd.startswith(";")): continue else: ## Run commands ## # os.system('./'+kernel_file+" exec "+cmd)# Credit learned with https://pymotw.com/2/subprocess/ ## Prompt ## prompt = ['./' + kernel_file, 'exec', cmdln[0]] ## Arguments ## for i in cmdln[1:]: prompt.append(i) ## Call the kernel ## sub.call(prompt)
def address_from_pubkey(cls, pubkey: bytes): hash_pub = hashlib.sha3_256(pubkey[1:]).hexdigest() return f"hx{hash_pub[-40:]}"
import hashlib # -------------------------------------- # This script packages tablite for pypi # -------------------------------------- folder = Path(__file__).parent # Step 1. find the sha256 of the files used for this build. packages = [ folder / 'tablite' / "__init__.py", folder / 'LICENSE', folder / 'README.md', ] sha = hashlib.sha3_256() for package_path in packages: assert package_path.exists(), str(package_path) with open(str(package_path), mode='rb') as fi: data = fi.read() sha.update(data) current_build_tag = sha.hexdigest() # Step 2. get the sha256 of the existing build. setup = folder / "setup.py" build_tag_idx, version_idx = None, None with open(str(setup), encoding='utf-8') as f: lines = f.readlines() for idx, row in enumerate(lines): if "build_tag" in row:
import sys import hashlib from sha3 import sha3_256, sha3_512 import string mystring = raw_input ('Enter String to hash: ') hash_object1 = hashlib.sha1(mystring.encode()) hash_object2 = hashlib.sha256(mystring.encode()) hash_object3 = hashlib.sha512(mystring.encode()) hash_object4 = hashlib.sha3_256(mystring.encode()) hash_object5 = hashlib.sha3_512(mystring.encode()) print ("String entered: %s" % mystring) print ("SHA-1: " + hash_object1.hexdigest()) print ("SHA-256: " + hash_object2.hexdigest()) print ("SHA-512: " + hash_object3.hexdigest()) print ("SHA-3(256): " + hash_object4.hexdigest()) print ("SHA-3(512): " + hash_object5.hexdigest())
def test_crop(set_output_dir): output_dir = set_output_dir conn = { 'domain': os.getenv("HOST"), 'username': os.getenv("API_USER"), 'access_token': os.getenv("API_TOKEN"), } cutting_geom_osgbwkt = 'POLYGON((372400 213749, 372400 209750, 376487 209750, 376487 213749, 372400 213749))' eods_params = { 'output_dir': output_dir, 'title': 'keep_api_test_create_group', 'verify': False, } list_of_layers, df = eodslib.query_catalog(conn, **eods_params) wkt = df.loc[( df['alternate'] == list_of_layers[0])]['csw_wkt_geometry'].item() lower_left, upper_right = eodslib.get_bbox_corners_from_wkt(wkt, 27700) errors = [] list_of_results = [] config_wpsprocess = { 'template_xml': 'rascropcoverage_template.xml', 'xml_config': { 'template_layer_name': list_of_layers[0], 'template_mimetype': 'image/tiff', 'template_ll': str(lower_left.x) + ' ' + str(lower_left.y), 'template_ur': str(upper_right.x) + ' ' + str(upper_right.y), 'template_clip_geom': cutting_geom_osgbwkt }, 'dl_bool': True } execution_dict = eodslib.run_wps(conn, config_wpsprocess, output_dir=output_dir, verify=False) list_of_results.append(execution_dict) eodslib.output_log(list_of_results) os.rename(output_dir / 'wps-log.csv', output_dir / 'wps-log-gs-rcrop-test.csv') os.rename(output_dir / 'eods-query-all-results.csv', output_dir / 'eods-query-all-results-gs-rcrop-test.csv') os.rename(output_dir / 'keep_api_test_create_group.tiff', output_dir / 'keep_api_test_create_group_gs_rcrop.tiff') log_df = pd.read_csv(output_dir / 'wps-log-gs-rcrop-test.csv') if len(log_df.index) != 1: errors.append( f'Content Error: output log should contain only 1 row, got {len(log_df.index)} rows' ) if log_df.iloc[0]['layer_name'] != 'geonode:keep_api_test_create_group': errors.append( f"Content Error: 1st row of output log should have \'layer_name\' of \'geonode:keep_api_test_create_group\', it was \'{log_df.iloc[0]['layer_name']}\'" ) if log_df.iloc[0]['filename_stub'] != 'keep_api_test_create_group': errors.append( f"Content Error: 1st row of df should have \'filename_stub\' of \'keep_api_test_create_group\', it was \'{log_df.iloc[0]['filename_stub']}\'" ) hash = hashlib.sha3_256() with open(output_dir / 'keep_api_test_create_group_gs_rcrop.tiff', "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash.update(chunk) hash_out = hash.hexdigest() checksum = 'e62d562ca491d56c0b2a6c327a612f30390a3bbe103c8e72d9e874e6609651d4' if hash_out != checksum: errors.append("Checksum Error: Expected " + checksum + ", got " + hash_out) assert not errors