def getEncryptedPassword(raw_password): print("Getting hashed password") try: password = raw_password.encode("utf-16") print(password, sha256(password).hexdigest()) return sha256(password).hexdigest() except Exception as e: print(e) raise Exception("e")
def decode(self, server, block_header, target, job_id = None, extranonce2 = None): if block_header: job = Object() binary_data = block_header.decode('hex') data0 = np.zeros(64, np.uint32) data0 = np.insert(data0, [0] * 16, unpack('IIIIIIIIIIIIIIII', binary_data[:64])) job.target = np.array(unpack('IIIIIIII', target.decode('hex')), dtype=np.uint32) job.header = binary_data[:68] job.merkle_end = np.uint32(unpack('I', binary_data[64:68])[0]) job.time = np.uint32(unpack('I', binary_data[68:72])[0]) job.difficulty = np.uint32(unpack('I', binary_data[72:76])[0]) job.state = sha256(STATE, data0) job.f = np.zeros(8, np.uint32) job.state2 = partial(job.state, job.merkle_end, job.time, job.difficulty, job.f) job.targetQ = 2**256 / int(''.join(list(chunks(target, 2))[::-1]), 16) job.job_id = job_id job.extranonce2 = extranonce2 job.server = server calculateF(job.state, job.merkle_end, job.time, job.difficulty, job.f, job.state2) if job.difficulty != self.difficulty: self.set_difficulty(job.difficulty) return job
def decode(self, server, block_header, target, job_id=None, extranonce2=None): if block_header: job = Object() binary_data = block_header.decode('hex') data0 = list(unpack('<16I', binary_data[:64])) + ([0] * 48) job.target = unpack('<8I', target.decode('hex')) job.header = binary_data[:68] job.merkle_end = uint32(unpack('<I', binary_data[64:68])[0]) job.time = uint32(unpack('<I', binary_data[68:72])[0]) job.difficulty = uint32(unpack('<I', binary_data[72:76])[0]) job.state = sha256(STATE, data0) job.targetQ = 2**256 / int(''.join(list(chunks(target, 2))[::-1]), 16) job.job_id = job_id job.extranonce2 = extranonce2 job.server = server if job.difficulty != self.difficulty: self.set_difficulty(job.difficulty) return job
def validate_solution(self, solution): # Validate solution parameters match loaded work if ( solution.merkle_lsw not in self._derived_works or self._derived_works[solution.merkle_lsw][0] != solution.midstate or self._bits != solution.bits or self._bits_comp != solution.bits_comp or (self._timestamp & 0xFFFFFFF0) != (solution.timestamp & 0xFFFFFFF0) ): return False # Form rest of block header block_header_rest = ( solution.merkle_lsw + solution.timestamp.to_bytes(4, "little") + solution.bits.to_bytes(4, "little") + solution.nonce.to_bytes(4, "little") ) # First SHA256 hash, starting from midstate h = sha256.sha256() h.state = (solution.midstate, 64) h.update(block_header_rest) block_header_hash1 = h.digest() # Second SHA256 hash block_header_hash2 = hashlib.sha256(block_header_hash1).digest() # Compare block header hash to target return block_header_hash2[::-1] < self._target_comp[::-1]
def validate_solution(self, solution): # Validate solution parameters match loaded work if ( solution.merkle_lsw not in self._derived_works or self._derived_works[solution.merkle_lsw][0] != solution.midstate or self._swirl_work_data.nbits != solution.bits or self._swirl_work_data.bits_pool != solution.bits_comp or (self._swirl_work_data.ntime & 0xFFFFFF00) != (solution.timestamp & 0xFFFFFF00) ): return False # Form rest of block header block_header_rest = ( solution.merkle_lsw + solution.timestamp.to_bytes(4, "little") + solution.bits.to_bytes(4, "little") + solution.nonce.to_bytes(4, "little") ) # First SHA256 hash, starting from midstate h = sha256.sha256() h.state = (solution.midstate, 64) h.update(block_header_rest) block_header_hash1 = h.digest() # Second SHA256 hash block_header_hash2 = hashlib.sha256(block_header_hash1).digest() logger.info( "[swirl_client] Validating solution for work_id 0x%x with enonce1 %s, enonce2 %s, solution %s", self._swirl_work_data.work_id, codecs.encode(self._enonce1, "hex_codec"), codecs.encode(self._derived_works[solution.merkle_lsw][1], "hex_codec"), str(solution), ) logger.info( "[swirl_client] coinbase dhash %s", codecs.encode( hashlib.sha256(hashlib.sha256(self._derived_works[solution.merkle_lsw][3]).digest()).digest(), "hex_codec", ), ) for node in self._swirl_work_data.merkle_edge: logger.info("[swirl_client] edge dhash %s", codecs.encode(node, "hex_codec")) logger.info("[swirl_client] Block header") logger.info("[swirl_client] version 0x%08x", self._swirl_work_data.version) logger.info( "[swirl_client] prev block hash %s", codecs.encode(self._swirl_work_data.prev_block_hash, "hex_codec") ) logger.info( "[swirl_client] merkle root %s", codecs.encode(self._derived_works[solution.merkle_lsw][2], "hex_codec") ) logger.info("[swirl_client] timestamp 0x%08x", solution.timestamp) logger.info("[swirl_client] bits 0x%08x", solution.bits) logger.info("[swirl_client] nonce 0x%08x", solution.nonce) logger.info("[swirl_client] Block header hash %s", codecs.encode(block_header_hash2, "hex_codec")) # Compare block header hash to target return block_header_hash2[::-1] < self._target_comp[::-1]
def derive_works(self, count): # Convert merkle_edge into bytes merkle_edge = [codecs.decode(node, "hex_codec") for node in self._stratum_work_data.merkle_edge] # Convert coinbase transaction parts into bytes coinb1 = codecs.decode(self._stratum_work_data.coinb1, "hex_codec") enonce1 = codecs.decode(self._enonce1, "hex_codec") coinb2 = codecs.decode(self._stratum_work_data.coinb2, "hex_codec") # Convert block header parts into bytes prev_block_hash = codecs.decode(self._stratum_work_data.prev_block_hash, "hex_codec") prev_block_hash = b"".join([prev_block_hash[i * 4 : (i + 1) * 4][::-1] for i in range(0, 8)]) # Insanity # ^ Whoever invented Stratum did not understand how to pack the block # header, and decided to assemble everything in 32-bit big endian # chunks and then reverse every four bytes of the block header. # Therefore, the prev_block_hash arrives over Stratum with every four # bytes pre-reversed, so the later reverse puts it into internal byte # order. version = codecs.decode(self._stratum_work_data.version, "hex_codec")[::-1] works = [] for _ in range(count): # Form enonce2 enonce2 = os.urandom(self._enonce2_size) # Generate coinbase transaction coinbase_transaction = coinb1 + enonce1 + enonce2 + coinb2 # Compute merkle root merkle_root = hashlib.sha256(hashlib.sha256(coinbase_transaction).digest()).digest() for node in merkle_edge: merkle_root = hashlib.sha256(hashlib.sha256(merkle_root + node).digest()).digest() merkle_lsw = merkle_root[28:32] # Form first 64 bytes of block header block_header_first = version + prev_block_hash + merkle_root[:28] # Calculate SHA256 midstate (midstate, _) = sha256.sha256(block_header_first).state work = minerhal.MinerSimpleWork( midstate=midstate, merkle_lsw=merkle_lsw, bits=self._bits, timestamp=self._timestamp, bits_comp=self._bits_comp, ) # Save the midstate under merkle_lsw for later validation, and # enonce2 for later share submission self._derived_works[merkle_lsw] = (midstate, enonce2) works.append(work) return works
def __init__(self, key, msg=None): self.outer = sha256('') self.inner = sha256('') self.digest_size = self.inner.digest_size self.block_size = self.inner.block_size if len(key) > self.block_size: key = sha256(key).digest() key = key.ljust(self.block_size, b'\0') print('key:', key) self.outer.update(key.translate(trans_5C)) self.inner.update(key.translate(trans_36)) self.update(msg)
def Authenticate(auth_challenge, password): salt = ''.join([chr(x) for x in auth_challenge['PasswordSalt']]) challenge = ''.join([chr(x) for x in auth_challenge['Challenge']]) combo = salt + password.encode('utf-8') h2 = sha256.sha256(combo) combo = challenge + h2.digest() h1 = sha256.sha256(combo) proof = h1.digest() byte_proof = struct.unpack('B'*32, proof) try: resp = Call('Authenticate', use_ssl=True, params=PackParams(auth_challenge['Challenge'], byte_proof)) except RpcError, e: logging.warning( 'Authentication failed code: %s and message: %s', e.code, e.message) return None
def __init__(self): # Object for calculating SHA256 hashes self.hasher = sha256() # Create ipad and opad strings self.ipad = BitArray() self.opad = BitArray() while (self.ipad.length < 512): self.ipad.append('0x36') while (self.opad.length < 512): self.opad.append('0x5c')
def _derive_simple_works(self, count): works = [] for _ in range(count): # Form enonce2 enonce2 = os.urandom(self._enonce2_size) # Generate coinbase transaction coinbase_transaction = self._swirl_work_data.coinb1 + self._enonce1 + enonce2 + self._swirl_work_data.coinb2 # Compute merkle root merkle_root = hashlib.sha256(hashlib.sha256(coinbase_transaction).digest()).digest() for node in self._swirl_work_data.merkle_edge: merkle_root = hashlib.sha256(hashlib.sha256(merkle_root + node).digest()).digest() merkle_lsw = merkle_root[28:32] # Form first 64 bytes of block header block_header_first = ( self._swirl_work_data.version.to_bytes(4, "little") + self._swirl_work_data.prev_block_hash + merkle_root[:28] ) # Calculate SHA256 midstate (midstate, _) = sha256.sha256(block_header_first).state work = minerhal.MinerSimpleWork( midstate=midstate, merkle_lsw=merkle_lsw, bits=self._swirl_work_data.nbits, timestamp=self._swirl_work_data.ntime, bits_comp=self._swirl_work_data.bits_pool, ) # Save the midstate under merkle_lsw for later validation, and # enonce2 for later share submission self._derived_works[merkle_lsw] = (midstate, enonce2, merkle_root, coinbase_transaction) # FIXME remove full merkle root and coinbase_transaction above when # logging is quieted. works.append(work) return works
def validate_solution(self, solution): # Validate solution parameters match loaded work for this worker if self._block_header.bits != solution.bits or (self._block_header.timestamp & 0xffffff00) != (solution.timestamp & 0xffffff00): return False # Form rest of block header block_header_rest = solution.merkle_lsw + solution.timestamp.to_bytes(4, 'little') + solution.bits.to_bytes(4, 'little') + solution.nonce.to_bytes(4, 'little') # First SHA256 hash, starting from midstate h = sha256.sha256() h.state = (solution.midstate, 64) h.update(block_header_rest) block_header_hash1 = h.digest() # Second SHA256 hash block_header_hash2 = hashlib.sha256(block_header_hash1).digest() # Compare block header hash to target return block_header_hash2[::-1] < self._target_comp[::-1]
def mine(nonce_iter, words, start, step, cmp): last_sync = time.time() - start * SYNC_INTERVAL nonce_iter = itertools.islice(nonce_iter, start, None, step) for nonce in nonce_iter: if time.time() - last_sync > SYNC_INTERVAL * step: last_sync = time.time() sys.stdout.write('\r{} '.format(to_str(nonce))) sys.stdout.flush() h = hashlib.sha256(nonce).digest() h1 = sha256.sha256(nonce).digest() assert h == h1, (h, h1) for word in words: if cmp(h, word): sys.stdout.write('\r{} => {} | {}\n'.format( to_str(nonce), to_str(word), to_str(binascii.hexlify(h)), )) sys.stdout.flush()
def main(): RN = random.randint(0, 54) fib = fibencrypt.fibgen(RN) # Start of main while True: user_choice = str(input("$ ")) # Encryption currently defaults to fibencrypt # Keys are entered upon decryption and optional for encryption if user_choice in ("Encrypt", "E"): enc_kind = str(input(""" What form of encryption? ~~~~~~~~~~~~~~~~~~~~~~~~ 1.) Fibonnacci Encryption 2.) SHA256""")) if enc_kind in ("Fib", "1", "Fibonnacci"): fibencrypt.encrypt() elif enc_kind in ("SHA254", "2", "sha"): sha256.encrypt() # Decryption if user_choice in ("Decrypt", "D"): dec_key = int(input("Enter Key: ")) print("Decrypting...") read_file = str(input("Filename for reading: ")) output_file = str(input("Filename for output: ") + ".txt") fibencrypt.decrypt(fib, dec_key, read_file, output_file) if user_choice in ("SHA256", "sha"): ustring = input("$: ") print(sha256.sha256(ustring)) if user_choice in ("caesar", "c"): ustring = input("$: ") print(caesar.caesar_Enc(5, ustring))
def _derive_simple_works(self, count): works = [] for _ in range(count): # Form enonce2 enonce2 = os.urandom(self._enonce2_size) # Generate coinbase transaction coinbase_transaction = self._swirl_work_data.coinb1 + self._enonce1 + enonce2 + self._swirl_work_data.coinb2 # Compute merkle root merkle_root = hashlib.sha256(hashlib.sha256(coinbase_transaction).digest()).digest() for node in self._swirl_work_data.merkle_edge: merkle_root = hashlib.sha256(hashlib.sha256(merkle_root + node).digest()).digest() merkle_lsw = merkle_root[28:32] # Form first 64 bytes of block header block_header_first = self._swirl_work_data.version.to_bytes(4, 'little') + self._swirl_work_data.prev_block_hash + merkle_root[:28] # Calculate SHA256 midstate (midstate, _) = sha256.sha256(block_header_first).state work = minerhal.MinerSimpleWork( midstate=midstate, merkle_lsw=merkle_lsw, bits=self._swirl_work_data.nbits, timestamp=self._swirl_work_data.ntime, bits_comp=self._swirl_work_data.bits_pool ) # Save the midstate under merkle_lsw for later validation, and # enonce2 for later share submission self._derived_works[merkle_lsw] = (midstate, enonce2, merkle_root, coinbase_transaction) # FIXME remove full merkle root and coinbase_transaction above when # logging is quieted. works.append(work) return works
def decode(self, server, block_header, target, job_id = None, extranonce2 = None): if block_header: job = Object() binary_data = block_header.decode('hex') data0 = list(unpack('<16I', binary_data[:64])) + ([0] * 48) job.target = unpack('<8I', target.decode('hex')) job.header = binary_data[:68] job.merkle_end = uint32(unpack('<I', binary_data[64:68])[0]) job.time = uint32(unpack('<I', binary_data[68:72])[0]) job.difficulty = uint32(unpack('<I', binary_data[72:76])[0]) job.state = sha256(STATE, data0) job.targetQ = 2**256 / int(''.join(list(chunks(target, 2))[::-1]), 16) job.job_id = job_id job.extranonce2 = extranonce2 job.server = server if job.difficulty != self.difficulty: self.set_difficulty(job.difficulty) return job
def validate_solution(self, solution): # Validate solution parameters match loaded work if solution.merkle_lsw not in self._derived_works \ or self._derived_works[solution.merkle_lsw][0] != solution.midstate \ or self._swirl_work_data.nbits != solution.bits \ or self._swirl_work_data.bits_pool != solution.bits_comp \ or (self._swirl_work_data.ntime & 0xffffff00) != (solution.timestamp & 0xffffff00): return False # Form rest of block header block_header_rest = solution.merkle_lsw + solution.timestamp.to_bytes(4, 'little') + solution.bits.to_bytes(4, 'little') + solution.nonce.to_bytes(4, 'little') # First SHA256 hash, starting from midstate h = sha256.sha256() h.state = (solution.midstate, 64) h.update(block_header_rest) block_header_hash1 = h.digest() # Second SHA256 hash block_header_hash2 = hashlib.sha256(block_header_hash1).digest() logger.info("[swirl_client] Validating solution for work_id 0x%x with enonce1 %s, enonce2 %s, solution %s", self._swirl_work_data.work_id, codecs.encode(self._enonce1, "hex_codec"), codecs.encode(self._derived_works[solution.merkle_lsw][1], "hex_codec"), str(solution)) logger.info("[swirl_client] coinbase dhash %s", codecs.encode(hashlib.sha256(hashlib.sha256(self._derived_works[solution.merkle_lsw][3]).digest()).digest(), "hex_codec")) for node in self._swirl_work_data.merkle_edge: logger.info("[swirl_client] edge dhash %s", codecs.encode(node, "hex_codec")) logger.info("[swirl_client] Block header") logger.info("[swirl_client] version 0x%08x", self._swirl_work_data.version) logger.info("[swirl_client] prev block hash %s", codecs.encode(self._swirl_work_data.prev_block_hash, "hex_codec")) logger.info("[swirl_client] merkle root %s", codecs.encode(self._derived_works[solution.merkle_lsw][2], "hex_codec")) logger.info("[swirl_client] timestamp 0x%08x", solution.timestamp) logger.info("[swirl_client] bits 0x%08x", solution.bits) logger.info("[swirl_client] nonce 0x%08x", solution.nonce) logger.info("[swirl_client] Block header hash %s", codecs.encode(block_header_hash2, "hex_codec")) # Compare block header hash to target return block_header_hash2[::-1] < self._target_comp[::-1]
def auth_check(to_check_socket): try: auth_header = to_check_socket.recv(HEADER_SIZE) if auth_header: auth_length = int(auth_header.decode('utf-8')) auth_data_encrypted = to_check_socket.recv(auth_length) auth_data_encrypted = pickle.loads(auth_data_encrypted) auth_data_decrypted = RC5_CBC_decryption(auth_data_encrypted[0], SERVER_KEY, auth_data_encrypted[1]) auth_data = pickle.loads(auth_data_decrypted) if auth_data['username'] in AUTH_VALID_DATA.keys() and AUTH_VALID_DATA[auth_data['username']] == sha256(auth_data['password']): return auth_data['username'] else: return False else: return False except socket.error as err: if err.errno == errno.WSAECONNRESET: print(f"could not complete authentication process with client {to_check_socket.getsockname()}") to_check_socket.close() return False
def _derive_bitshare_works(self, count): works = [] # Block header miner structure block_header = minerhal.MinerBitshareWork.BlockHeader( version=self._swirl_work_data.version, prev_block_hash=self._swirl_work_data.prev_block_hash, bits=self._swirl_work_data.nbits, timestamp=self._swirl_work_data.ntime, bits_comp=self._swirl_work_data.bits_pool ) # Merkle edge miner structure merkle_edge = minerhal.MinerBitshareWork.MerkleEdge( list(self._swirl_work_data.merkle_edge) ) for _ in range(count): # Form enonce2 enonce2 = os.urandom(self._enonce2_size) # Generate coinbase transaction coinbase_transaction = self._swirl_work_data.coinb1 + self._enonce1 + enonce2 + self._swirl_work_data.coinb2 # Check if coinbase transaction is 512-bit aligned before the bitshare output if ((len(coinbase_transaction) - SwirlWork._BITSHARE_OUTPUT_LEN) % 64) != 0: logger.warning("[swirl_client] Received improperly padded coinbase transaction of length %d", len(coinbase_transaction)) (coinbase_midstate, _) = sha256.sha256(coinbase_transaction[:-SwirlWork._BITSHARE_OUTPUT_LEN]).state # Coinbase miner structure coinbase = minerhal.MinerBitshareWork.Coinbase( midstate=coinbase_midstate, wallet_id=self._wallet_id, block_height=self._swirl_work_data.height, lock_time=int.from_bytes(coinbase_transaction[-4:], 'little'), data_length=8*len(coinbase_transaction) ) # Compute merkle root merkle_root = hashlib.sha256(hashlib.sha256(coinbase_transaction).digest()).digest() for node in self._swirl_work_data.merkle_edge: merkle_root = hashlib.sha256(hashlib.sha256(merkle_root + node).digest()).digest() merkle_lsw = merkle_root[28:32] # Form first 64 bytes of block header block_header_first = self._swirl_work_data.version.to_bytes(4, 'little') + self._swirl_work_data.prev_block_hash + merkle_root[:28] # Calculate SHA256 midstate (midstate, _) = sha256.sha256(block_header_first).state work = minerhal.MinerBitshareWork( block_header, merkle_edge, coinbase ) # Save the midstate under merkle_lsw for later validation, and # enonce2 for later share submission self._derived_works[merkle_lsw] = (midstate, enonce2, merkle_root, coinbase_transaction) # FIXME remove full merkle root and coinbase_transaction above when # logging is quieted. works.append(work) return works
def test_NSA_example_0_is_processed_correctly(self): """Ensure abc produces the same output as from the NSA paper""" input_message = NSA_EXAMPLE_2 output_digest = sha256.sha256(input_message) self.assertEqual(output_digest, NSA_EXAMPLE_2_DIGEST)
def checkPassword(raw_password, enc_password): print("Compare passwords") return sha256( raw_password.encode("utf-16")).hexdigest() == enc_password
def _sha256(x): #return hashlib.sha256(x).digest() return sha256.sha256(x).digest()
def hash(x): return sha256(x)
import bitstring as bs import sha256 as sh import header as hd import datetime if __name__ == '__main__': # Target max_value = 26959535291011309493156476344723991336010898738574164086137773096960 difficulty = 13008091666971.90 target = max_value / difficulty # Construction of block header # Block 600,000 is used as example version = '0x20000000' prev_hash = '0x00000000000000000003ecd827f336c6971f6f77a0b9fba362398dd867975645' merkle_root = '0x66b7c4a1926b41ceb2e617ddae0067e7bfea42db502017fde5b695a50384ed26' time = int(datetime.datetime(2019, 10, 18, 19, 4, 21).timestamp()) bits = 387294044 nonce = 1066642855 header = hd.header(version, prev_hash, merkle_root, time, bits, nonce) # Looking for nonce to be under target block_hash = bs.BitString(uint=sh.sha256(sh.sha256(header)).uintle, length=256) while block_hash.uint > int(target): nonce += 1 block_hash = bs.BitString(uint=sh.sha256(sh.sha256(header)).uintle, length=256) print('The nonce is: ' + str(nonce) + '\nThe hash is: ' + str(block_hash))
import sha256 as hash print("test d'appel fonction sha256 : ", hash.sha256("test de hash"))
def dspSHA256(): pygame.display.set_caption("MD5 Algorithm") # adding a caption display = pygame.display.set_mode((1280, 550), pygame.FULLSCREEN) effc = timeit.Timer(functools.partial(sha256.sha256, intro.secret)) efcTime = effc.timeit(15) effcSHA1 = timeit.Timer(functools.partial(sha1.sha1, intro.secret)) efcTimeSHA1 = effc.timeit(15) effcMDA = timeit.Timer(functools.partial(md5.md5, intro.secret)) efcTimeMDA = effc.timeit(15) m = max(efcTime, efcTimeMDA, efcTimeSHA1) efcMD5 = (efcTimeMDA / m) * 250 efcSHA2 = (efcTime / m) * 250 efcSHA1 = (efcTimeSHA1 / m) * 250 while True: # starting the game loop display.fill( (0, 0, 0) ) # pygame method to fill the screen, takes colours and a display object #display.blit(bg,(0,0)) # pygame method, iterates over the events in pygame to determine what we are doing with every event for event in pygame.event.get(): if event.type == pygame.QUIT: # this one quits pygame.quit() # putting the quit pygame method exit() # takes the user from GUI to the script for exiting if event.type == pygame.KEYUP: # Here is to tell the computer to recognise if a keybord key is pressed. if event.key == pygame.K_ESCAPE: # if that keyboard key is ESC exit() # call for the exit function. surface = pygame.display.get_surface() loc1, loc2 = surface.get_size() w, h = surface.get_size() w = (w / 2) - 60 h = (h / 2) - 200 hlp.AddText("Encrypted Text: " + intro.secret, (w - 150, h)) hlp.AddText( "Padded Text: " + str(md5.padding(intro.secret))[0:15] + "...", (w - 150, h + 30)) hlp.AddText("SHA256 Hashing: " + sha256.sha256(intro.secret), (w - 150, loc2 - 175)) hlp.AddText( str(round(float(efcTime), 4)) + " seconds passed to execute this algorithm", (w - 150, 5 * loc2 / 6)) hlp.Button("Exit", 350, 5, 100, 30, sys.exit) back = hlp.ButtonWithReturn("Back", 900, 5, 100, 30, 1) if back > 0: # if back has a value, which means it has been clicked, stop the bigger loop that we started, i.e. the game loop, and break the game loop break pygame.draw.line(display, line_colour, (400, 250), (400, 500), 2) # pygame method, takes display, colour, and positions of where the lines start and end pygame.draw.line(display, line_colour, (350, 500), (950, 500), 2) hlp.AddText("0s", (395, 505), hlp.white) hlp.AddText("SHA256", (465, 510), hlp.white) hlp.AddText("MD5", (615, 510), hlp.white) hlp.AddText("SHA1", (765, 510), hlp.white) hlp.AddText(str(round(float(efcTime), 5)), (460, 230), hlp.white) hlp.AddText(str(round(float(efcTimeMDA), 5)), (610, 230), hlp.white) hlp.AddText(str(round(float(efcTimeSHA1), 5)), (760, 230), hlp.white) bPos = 500 pygame.draw.rect(display, hlp.button_colour, (465, bPos - efcSHA2, 50, efcSHA2)) pygame.draw.rect(display, hlp.button_colour, (615, bPos - efcMD5, 50, efcMD5)) pygame.draw.rect(display, hlp.button_colour, (765, bPos - efcSHA1, 50, efcSHA1)) pygame.display.flip() # will not run more than 30 frames per second clock.tick(30) intro.Introduction2()
def _derive_bitshare_works(self, count): works = [] # Block header miner structure block_header = minerhal.MinerBitshareWork.BlockHeader( version=self._swirl_work_data.version, prev_block_hash=self._swirl_work_data.prev_block_hash, bits=self._swirl_work_data.nbits, timestamp=self._swirl_work_data.ntime, bits_comp=self._swirl_work_data.bits_pool, ) # Merkle edge miner structure merkle_edge = minerhal.MinerBitshareWork.MerkleEdge(list(self._swirl_work_data.merkle_edge)) for _ in range(count): # Form enonce2 enonce2 = os.urandom(self._enonce2_size) # Generate coinbase transaction coinbase_transaction = self._swirl_work_data.coinb1 + self._enonce1 + enonce2 + self._swirl_work_data.coinb2 # Check if coinbase transaction is 512-bit aligned before the bitshare output if ((len(coinbase_transaction) - SwirlWork._BITSHARE_OUTPUT_LEN) % 64) != 0: logger.warning( "[swirl_client] Received improperly padded coinbase transaction of length %d", len(coinbase_transaction), ) (coinbase_midstate, _) = sha256.sha256(coinbase_transaction[: -SwirlWork._BITSHARE_OUTPUT_LEN]).state # Coinbase miner structure coinbase = minerhal.MinerBitshareWork.Coinbase( midstate=coinbase_midstate, wallet_id=self._wallet_id, block_height=self._swirl_work_data.height, lock_time=int.from_bytes(coinbase_transaction[-4:], "little"), data_length=8 * len(coinbase_transaction), ) # Compute merkle root merkle_root = hashlib.sha256(hashlib.sha256(coinbase_transaction).digest()).digest() for node in self._swirl_work_data.merkle_edge: merkle_root = hashlib.sha256(hashlib.sha256(merkle_root + node).digest()).digest() merkle_lsw = merkle_root[28:32] # Form first 64 bytes of block header block_header_first = ( self._swirl_work_data.version.to_bytes(4, "little") + self._swirl_work_data.prev_block_hash + merkle_root[:28] ) # Calculate SHA256 midstate (midstate, _) = sha256.sha256(block_header_first).state work = minerhal.MinerBitshareWork(block_header, merkle_edge, coinbase) # Save the midstate under merkle_lsw for later validation, and # enonce2 for later share submission self._derived_works[merkle_lsw] = (midstate, enonce2, merkle_root, coinbase_transaction) # FIXME remove full merkle root and coinbase_transaction above when # logging is quieted. works.append(work) return works
# Not that secure, but generally useful for theory crafting # Future Features: # -More key security # -More sequence generations # -Create an actually secure message + key encryptor # -move to either Tkinter or argparse, CLI insecure # -maybe move to different language # Init parse parser = argparse.ArgumentParser(description='Encrypt a string') parser.add_argument("-S", "--string", help="show program version") args = parser.parse_args() print(sha256.sha256(args.string)) def main(): RN = random.randint(0, 54) fib = fibencrypt.fibgen(RN) # Start of main while True: user_choice = str(input("$ ")) # Encryption currently defaults to fibencrypt # Keys are entered upon decryption and optional for encryption
#!/usr/bin/python __author__ = 'Lloyd Jee-heon Oh' __license__ = 'MIT' ############################################################################ ## PROOF of free-start collision attack + circular hash attack for sha256 ############################################################################ ## input hash ad3381f1 8f9dae20 5419ec4e c0a9c019 839a030f e8bfad5a d308ae65 3a456ff1 ## input message block 5b4adf0bb6373803dae2f3a9a951f172ea5ca7b59ce5d74ace7a52a5b222cc78b69c9ed260685995c5bb23de1ffe6463a2c707daf76ac1c171858d71c94b58ad ## prints ['0xad3381f1L', '0x8f9dae20L', '0x5419ec4eL', '0xc0a9c019L', '0x839a030fL', '0xe8bfad5aL', '0xd308ae65L', '0x3a456ff1L'] ############################################################################ import sha256 q=sha256.sha256() q._h = (0xad3381f1, 0x8f9dae20, 0x5419ec4e, 0xc0a9c019, 0x839a030f, 0xe8bfad5a, 0xd308ae65, 0x3a456ff1) m='5b4adf0bb6373803dae2f3a9a951f172ea5ca7b59ce5d74ace7a52a5b222cc78b69c9ed260685995c5bb23de1ffe6463a2c707daf76ac1c171858d71c94b58ad'.decode('hex') q.update(m) print(map(hex,q._h))
def hashMac(): mac = getMac() hashObject = sha256.sha256(mac + salt) hash = hashObject.hexdigest() return hash
def register(request): if request.method == "GET": # display the registration form curdate = datetime.datetime.now() strcurdate = curdate.strftime("%Y-%m-%d %H:%M:%S") (username, password, password2, email, firstname, middlename, lastname, mobilenum) = ("", "", "", "", "", "", "", "") usertypes = MEMBERSHIP_TYPES.keys() tmpl = get_template("auth/regform.html") c = {'curdate' : strcurdate, 'login_url' : utils.gethosturl(request) + "/" + LOGIN_URL, 'hosturl' : utils.gethosturl(request),\ 'register_url' : utils.gethosturl(request) + "/" + REGISTER_URL,\ 'min_passwd_strength' : MIN_ALLOWABLE_PASSWD_STRENGTH, 'username' : username, 'password' : password, 'password2' : password2,\ 'email' : email, 'firstname' : firstname, 'middlename' : middlename, 'lastname' : lastname, 'mobilenum' : mobilenum, \ 'hosturl' : utils.gethosturl(request), 'profpicheight' : PROFILE_PHOTO_HEIGHT, 'profpicwidth' : PROFILE_PHOTO_WIDTH, 'availabilityURL' : utils.AVAILABILITY_URL, 'usertypes' : usertypes } c.update(csrf(request)) cxt = Context(c) registerhtml = tmpl.render(cxt) for htmlkey in HTML_ENTITIES_CHAR_MAP.keys(): registerhtml = registerhtml.replace( htmlkey, HTML_ENTITIES_CHAR_MAP[htmlkey]) return HttpResponse(registerhtml) elif request.method == "POST": # Process registration form data username = request.POST['username'] password = request.POST['password'] password2 = request.POST['password2'] email = request.POST['email'] firstname = request.POST['firstname'] middlename = request.POST['middlename'] lastname = request.POST['lastname'] sex = request.POST['sex'] mobilenum = request.POST['mobilenum'] profpic = "" csrftoken = request.POST['csrfmiddlewaretoken'] usertype = request.POST['usertype'] message = "" # Validate the collected data... if password != password2: message = error_msg('1011') elif MULTIPLE_WS_PATTERN.search(username): message = error_msg('1012') elif not EMAIL_PATTERN.search(email): message = error_msg('1013') elif mobilenum != "" and not PHONENUM_PATTERN.search(mobilenum): message = error_msg('1014') elif sex not in ('m', 'f', 'u'): message = error_msg('1015') elif not REALNAME_PATTERN.search( firstname) or not REALNAME_PATTERN.search( lastname) or not REALNAME_PATTERN.search(middlename): message = error_msg('1017') elif utils.check_password_strength( password) < MIN_ALLOWABLE_PASSWD_STRENGTH: message = error_msg('1019') if request.FILES.has_key('profpic'): fpath, message, profpic = utils.handleuploadedfile2( request.FILES['profpic'], settings.MEDIA_ROOT + os.path.sep + username + os.path.sep + "images") # User's images will be stored in "settings.MEDIA_ROOT/<Username>/images/". if message != "" and DEBUG: print message + "\n" if message != "": curdate = datetime.datetime.now() strcurdate = curdate.strftime("%Y-%m-%d %H:%M:%S") availabilityURL = utils.AVAILABILITY_URL tmpl = get_template("auth/regform.html") c = {'curdate' : strcurdate, 'msg' : "<font color='#FF0000'>%s</font>"%message, 'login_url' : utils.gethosturl(request) + "/" + LOGIN_URL,\ 'register_url' : utils.gethosturl(request) + "/" + REGISTER_URL, \ 'min_passwd_strength' : MIN_ALLOWABLE_PASSWD_STRENGTH, 'username' : username, 'password' : password, 'password2' : password2,\ 'email' : email, 'firstname' : firstname, 'middlename' : middlename, 'lastname' : lastname, 'mobilenum' : mobilenum, \ 'availabilityURL' : availabilityURL, 'hosturl' : utils.gethosturl(request), 'profpicheight' : PROFILE_PHOTO_HEIGHT, 'profpicwidth' : PROFILE_PHOTO_WIDTH } c.update(csrf(request)) cxt = Context(c) registerhtml = tmpl.render(cxt) for htmlkey in HTML_ENTITIES_CHAR_MAP.keys(): registerhtml = registerhtml.replace( htmlkey, HTML_ENTITIES_CHAR_MAP[htmlkey]) return HttpResponse(registerhtml) else: # Create the user and redirect to the dashboard page with a status message. db = utils.get_mongo_client() rec = {} rec['firstname'] = firstname rec['middlename'] = middlename rec['lastname'] = lastname rec['username'] = username rec['emailid'] = email rec['password'] = utils.make_password( password) # Store password as a hash. rec['mobileno'] = mobilenum rec['sex'] = sex rec['active'] = False # Will become active when user verifies email Id. rec['userimagepath'] = profpic usercode = '0' if usertype == 'SILVER': usercode = '1' elif usertype == 'GOLD': usercode = '2' elif usertype == 'PLATINUM': usercode = '3' else: pass rec['usertype'] = usercode userid = str(sha256.sha256(str(username)).hexdigest()) if DEBUG: print "type of userid is " + str(type(userid)) + "\n" rec['userid'] = userid rec["address"] = {} rec["address"]['country'] = "" rec['address']['State'] = "" rec['address']['block_sector'] = "" rec['address']['house_num'] = "" rec['address']['street_address'] = "" emailvalid = {} emailvalid['email'] = email emailvalid['vkey'] = utils.generate_random_string() r = db.users.find({'username': username}) e = db.emailvalidation.find({'email': email}) if r.count() > 0 or e.count() > 0: message = "Non unique email and/or username found." tmpl = get_template("auth/regerror.html") curdate = datetime.datetime.now() strcurdate = curdate.strftime("%Y-%m-%d %H:%M:%S") availabilityURL = utils.AVAILABILITY_URL c = {'curdate' : strcurdate, 'msg' : message, 'login_url' : utils.gethosturl(request) + "/" + LOGIN_URL,\ 'register_url' : utils.gethosturl(request) + "/" + REGISTER_URL, \ 'min_passwd_strength' : MIN_ALLOWABLE_PASSWD_STRENGTH, 'username' : username, 'password' : password, 'password2' : password2,\ 'email' : email, 'firstname' : firstname, 'middlename' : middlename, 'lastname' : lastname, 'mobilenum' : mobilenum, \ 'availabilityURL' : availabilityURL, 'hosturl' : utils.gethosturl(request), 'profpicheight' : PROFILE_PHOTO_HEIGHT, 'profpicwidth' : PROFILE_PHOTO_WIDTH } c.update(csrf(request)) cxt = Context(c) reghtml = tmpl.render(cxt) return HttpResponse(reghtml) try: db.users.insert_one(rec) db.emailvalidation.insert_one(emailvalid) except: message = sys.exc_info()[1].__str__() tmpl = get_template("auth/regform.html") availabilityURL = utils.AVAILABILITY_URL curdate = datetime.datetime.now() strcurdate = curdate.strftime("%Y-%m-%d %H:%M:%S") c = {'curdate' : strcurdate, 'msg' : "<font color='#FF0000'>%s</font>"%message, 'login_url' : utils.gethosturl(request) + "/" + LOGIN_URL,\ 'register_url' : utils.gethosturl(request) + "/" + REGISTER_URL, \ 'min_passwd_strength' : MIN_ALLOWABLE_PASSWD_STRENGTH, 'username' : username, 'password' : password, 'password2' : password2,\ 'email' : email, 'firstname' : firstname, 'middlename' : middlename, 'lastname' : lastname, 'mobilenum' : mobilenum, \ 'availabilityURL' : availabilityURL, 'hosturl' : utils.gethosturl(request), 'profpicheight' : PROFILE_PHOTO_HEIGHT, 'profpicwidth' : PROFILE_PHOTO_WIDTH } c.update(csrf(request)) cxt = Context(c) reghtml = tmpl.render(cxt) return HttpResponse(reghtml) subject = """ CryptoCurry Registration - Activate your account on CryptoCurry by verifying your email. """ message = """ Dear %s, Thanks for creating your account on CryptoCurry. In order to be able to login and use it, you need to verify this email address (which you have entered as an input during registration). You can do this by clicking on the hyperlink here: <a href='%s/%s?vkey=%s'>Verify My Account</a>. Once you have ver- ified your account, you would be able to use it. If you feel this email has been sent to you in error, please get back to us at the email address mentioned here: [email protected] Thanks and Regards, %s, CEO, CryptoCurry. """ % (username, utils.gethosturl(request), ACCTACTIVATION_URL, emailvalid['vkey'], MAILSENDER) fromaddr = "*****@*****.**" utils.sendemail(email, subject, message, fromaddr) # Print a success message and ask user to validate email. The current screen is # only a providential state where the user appears to be logged in but has no right # to perform any action. message = "<font color='#0000FF'>Hello %s, welcome on board CryptoCurry(™). We hope you will have a hassle-free association with us.<br /> \ In case of any issues, please feel free to drop us ([email protected]) an email regarding the matter. Our 24x7 <br />\ support center staff would only be too glad to help you out. Happy transacting at cyptocurry... </font>" % username tmpl = get_template("auth/profile.html") curdate = datetime.datetime.now() strcurdate = curdate.strftime("%Y-%m-%d %H:%M:%S") c = {'curdate' : strcurdate, 'msg' : message, 'login_url' : utils.gethosturl(request) + "/" + LOGIN_URL, \ 'csrftoken' : csrftoken, 'username' : username, 'password' : password, 'password2' : password2, 'email' : email, \ 'firstname' : firstname, 'middlename' : middlename, 'lastname' : lastname, 'mobilenum' : mobilenum, 'userid' : userid, 'active' : 0 } c.update(csrf(request)) cxt = Context(c) profile = tmpl.render(cxt) for htmlkey in HTML_ENTITIES_CHAR_MAP.keys(): profile = profile.replace(htmlkey, HTML_ENTITIES_CHAR_MAP[htmlkey]) return HttpResponse(profile) else: # Process this as erroneous request message = error_msg('1004') if DEBUG: print "Unhandled method call during registration.\n" return HttpResponseBadRequest( utils.gethosturl(request) + "/" + REGISTER_URL + "?msg=%s" % message)