def seal(request): if request.method == 'POST': ballot = request.POST.get('ballot_input') ballot_byte = ballot.encode('utf-8') ballot_hash = SHA3_256.new(ballot_byte).hexdigest() # Puzzle requirement: '0' * n (n leading zeros) puzzle, pcount = settings.PUZZLE, settings.PLENGTH nonce = 0 # Try to solve puzzle start_time = time.time() # benchmark timestamp = datetime.datetime.now().timestamp( ) # mark the start of mining effort while True: block_hash = SHA3_256.new( ("{}{}{}".format(ballot, nonce, timestamp).encode('utf-8'))).hexdigest() print('\ntrial hash: {}\n'.format(block_hash)) if block_hash[:pcount] == puzzle: stop_time = time.time() # benchmark print("\nblock is sealed in {} seconds\n".format(stop_time - start_time)) break nonce += 1 context = { 'prev_hash': 'GENESIS', 'transaction_hash': ballot_hash, 'nonce': nonce, 'block_hash': block_hash, 'timestamp': timestamp, } return render(request, 'ballot/seal.html', context) return redirect('ballot:create')
def session_key_generation(sA_i, qBj_x, qBj_y): ''' print("qbjx type: ", type(qBj_x)) if(type(qBj_x) is int): qBj_x = hex(qBj_x) qBj_y = hex(qBj_y) print(qBj_x) print("qbjx type: ", type(qBj_x)) ''' qB_j = Point(qBj_x, qBj_y, curve) T = sA_i * qB_j U = str(T.x) + str(T.y) + "NoNeedToRunAndHide" U = bytes(U, 'utf-8') # Compute the session keys k_enc = SHA3_256.new(U) k_enc = k_enc.digest() k_mac = SHA3_256.new(k_enc) k_mac = k_mac.digest() return k_enc, k_mac
def AddBlock2Chain(PoWLen, TxCnt, block_candidate, PrevBlock): Transactions = [] for b in range(TxCnt): Transactions.append("".join(block_candidate[9 * b:9 * b + 9])) H_r = MerkleTree(Transactions) if PrevBlock != "": Transactions = [] for b in range(TxCnt): Transactions.append("".join(PrevBlock[9 * b:9 * b + 9])) Prev_H_r = MerkleTree(Transactions) PrevPow = PrevBlock[-2][len("Previous PoW: "):-1].encode('UTF-8') Nonce = int(PrevBlock[-1][7:-1]) PrevPow = SHA3_256.new(Prev_H_r + PrevPow + Nonce.to_bytes( (Nonce.bit_length() + 7) // 8, byteorder="big")).hexdigest() else: PrevPow = "00000000000000000000" # If PrevBlock = "" => it is assumed that Previous PoW is 00000000000000000000 HoldPrevPow = PrevPow PrevPow = PrevPow.encode('UTF-8') hash_val_hex = "" val = 2**1028 - 1 #257-1 while hash_val_hex[:PoWLen] != "0" * PoWLen: Nonce = random.randint(0, val) #Create random Nonce hash_val_hex = SHA3_256.new(H_r + PrevPow + Nonce.to_bytes( (Nonce.bit_length() + 7) // 8, byteorder="big")).hexdigest() NewBlock = ''.join(block_candidate[:TxCnt * 9]) NewBlock = NewBlock + "Previous PoW: " + PrevPow.decode( 'UTF-8') + '\n' + "Nonce: " + str(Nonce) + '\n' return NewBlock, HoldPrevPow
def verify(m, s, pk): h = int.from_bytes(SHA3_256.new().update(m).digest(), 'big') for i in range(256): b = (h >> i) & 1 if SHA3_256.new().update(s[i]).digest() != pk[i][b]: return False return True
def PoW(PoWLen, q, p, g, TxCnt, filename): with open(filename, 'r') as file: leaves = [] i = 0 transaction = '' for line in file: transaction += line i += 1 if i == 7: leaves.append(transaction.encode('UTF-8')) i = 0 transaction = '' # CALCULATE ROOT root = getRoot(leaves) nonce = random.getrandbits(128) digest = root + (str(nonce)).encode('UTF-8') h_obj = SHA3_256.new(digest) hexdigest = h_obj.hexdigest() while hexdigest[:PoWLen] != '0' * PoWLen: nonce = random.getrandbits(128) digest = root + (str(nonce)).encode('UTF-8') h_obj = SHA3_256.new(digest) hexdigest = h_obj.hexdigest() with open(filename, 'r') as file1: block = file1.read() block += 'Nonce: ' + str(nonce) return block
def AddBlock2Chain(PoWLen, TxCnt, block_candidate, PrevBlock): PrevPoW1 = "00000000000000000000\n" if PrevBlock == "": block_candidate.append("Previous PoW: " + "00000000000000000000\n") else: PrevPoW1 = CheckPow(PrevBlock) block_candidate.append("Previous PoW: " + PrevPoW1 + "\n") arr = [] for i in range(len(block_candidate) - 9): if i % 9 == 0: arr.append(''.join(block_candidate[i:i + 9])) PPOW = block_candidate[-1][14:] PPOW = PPOW.rstrip() hashedList = [SHA3_256.new(i.encode("utf-8")).digest() for i in arr] H_r = Root_of_merkle(hashedList) notfound = True while notfound: nonce = random.randint(2**16, 2**64) digest = H_r + PPOW.encode("utf-8") + nonce.to_bytes( (nonce.bit_length() + 7) // 8, byteorder='big') if SHA3_256.new(digest).hexdigest()[:PoWLen] == (PoWLen * "0"): notfound = False nonce = "Nonce: " + str(nonce) + "\n" block_candidate.append(nonce) return ''.join(block_candidate), PrevPoW1
def merkle_tree_build(filename, TxCnt): f = open(filename, "r") hash_arr = [] whole_file = f.readlines() f.close() for i in range(0, TxCnt): #first get hash of transactions to array hash_arr.append( SHA3_256.new("".join( whole_file[i * 7:(i + 1) * 7]).encode('UTF-8')).digest()) # digest not hex current_size = int(TxCnt / 2) while True: # then fill the values after arr[TxCnt] new_array = [] for i in range(current_size): #print(i) m = hash_arr[2 * i] + hash_arr[2 * i + 1] hash = SHA3_256.new(m).digest() new_array.append(hash) hash_arr = new_array current_size = current_size // 2 #print('c: ',current_size) if current_size == 1: break #print("In Merkle tree build") #print(new_array[-1]) return new_array[-1]
def decryptAndAuth_p2(msg, curve, eph_keys): # msg = msg["MSG"] # eph_keys is the list of all ephemeral keys. T = Point(msg["QBJ.X"], msg["QBJ.Y"], curve) * eph_keys[int(msg["KEYID"])] U = (str(T.x) + str(T.y) + "NoNeedToRunAndHide") # https://www.youtube.com/watch?v=W6oQUDFV2C0&ab_channel=MatthewF. K_enc = SHA3_256.new(U.encode("utf-8")) # enc. session key K_mac = SHA3_256.new(K_enc.digest()) # mac key # print(K_enc.digest()) # print(K_mac.digest()) # message as byte array byteMsg = msg["MSG"].to_bytes((msg["MSG"].bit_length() + 7) // 8, byteorder='big') # mac is the last 32 bytes of the message big_mac = byteMsg[len(byteMsg) - 32:] # yes, big_mac is mac of the message. cip = int.from_bytes( byteMsg[:len(byteMsg) - 32], byteorder='big') # cip is the ciphertext in number format dec_arr = decrypt(cip, AES.MODE_CTR, K_enc) #print(dec_arr) msg = byteMsg[8:len(byteMsg) - 32] # first 8 byte is nonce h = HMAC.new(K_mac.digest(), digestmod=SHA256) h.update(msg) try: # return the decrypted string if msg is authentic h.verify(big_mac) print("The message '%s' is authentic" % msg) return dec_arr except ValueError: # return none if auth. fails print("The message or the key is wrong")
def AddBlock2Chain(PoWLen, TxCnt, block_candidate, PrevBlock): hash_root = 0 zeros = "" NewBlock = "" previous = "" currPoW = "" # construct a checker for zeros for k in range(PoWLen): zeros += "0" hash_root = tree(TxCnt, block_candidate) # get Merkle root # for first chain if (PrevBlock == ""): previous = "00000000000000000000" while (currPoW[:PoWLen] != zeros): # calculate the current PoW nonce = random.getrandbits( 128) # choose nonce as a 128-bit random integer hashformat = hash_root + str.encode(previous) + nonce.to_bytes( (nonce.bit_length() + 7) // 8, byteorder='big') hashval = SHA3_256.new() hashval.update(hashformat) # convert hashval to the str format for PoW comparison currPoW = hashval.hexdigest() # now, current PoW is found... # construct NewBlock now... for x in range(len(block_candidate)): NewBlock += block_candidate[x] NewBlock += ("Previous PoW: " + str(previous) + "\n" + "Nonce: " + str(nonce) + "\n") Prev.prv = currPoW # connect the previous PoW with the current PoW return NewBlock, previous # if the previous block is not the first block else: previous = Prev.prv while (currPoW[:PoWLen] != zeros): # calculate the current PoW nonce = random.getrandbits( 128) # choose nonce as a 128-bit random integer hashformat = hash_root + str.encode(previous) + nonce.to_bytes( (nonce.bit_length() + 7) // 8, byteorder='big') hashval = SHA3_256.new() hashval.update(hashformat) # convert hashval to the str format for PoW comparison currPoW = hashval.hexdigest() # now, current PoW is found... # construct NewBlock now... for x in range(len(block_candidate)): NewBlock += block_candidate[x] NewBlock += ("Previous PoW: " + str(previous) + "\n" + "Nonce: " + str(nonce) + "\n") Prev.prv = currPoW # connect the previous PoW with the current PoW return NewBlock, previous
def calc_hash(password, salt): """Calculate and return hash of password with the provided salt result = SHA3(SHA3(password) + salt) """ password_hash = SHA3_256.new(password).digest() hash_obj = SHA3_256.new(password_hash) hash_obj.update(salt) return hash_obj.digest()
def change_password(self, oldPass, newPass): oldPass_hash = SHA3_256.new(data=oldPass.encode('utf-8')).hexdigest() if oldPass_hash == self.NOW_FILE['password_hash']: newPass_hash = SHA3_256.new( data=newPass.encode('utf-8')).hexdigest() self.NOW_FILE['password_hash'] = newPass_hash self.save() else: return False
def CheckPow(PoWLen, allLines): allBlocks = [] for i in range(len(allLines) - 9): if (i % 9 == 0): allBlocks.append(''.join(allLines[i:i + 9])) prevPow = allLines[-2][14:].rstrip() hashedList = [SHA3_256.new(i.encode("utf-8")).digest() for i in allBlocks] nonceValue = int(allLines[-1][7:].rstrip()) rootValue = recCallMerkle(hashedList) tobedigest = rootValue + prevPow.encode("utf-8") + nonceValue.to_bytes( (nonceValue.bit_length() + 7) // 8, byteorder='big') PoW = SHA3_256.new(tobedigest).hexdigest() return PoW
def MerkleTree(leafs): for it in range(len(leafs)): leafs[it] = SHA3_256.new(leafs[it].encode('utf-8')).digest() loopC = int(math.log2(len(leafs))) for i in range(loopC): for t in range(len(leafs) // 2): leafs[t] = SHA3_256.new( ((leafs[2 * t] + leafs[2 * t + 1]))).digest() leafs = leafs[:len(leafs) // 2] return leafs[0]
def getRoot(leaves): if len(leaves) == 1: h_obj = SHA3_256.new(leaves[0]) return h_obj.digest() newLeaves = [] for i in range(0, len(leaves), 2): left = leaves[i] right = leaves[i + 1] h_obj_left = SHA3_256.new(left) h_obj_right = SHA3_256.new(right) newDigest = h_obj_left.digest() + h_obj_right.digest() newLeaves.append(newDigest) return getRoot(newLeaves)
def CheckPow(p, q, g,PoWLen, TxCnt, filename): f = open ( filename,"r+" ) lineList = f.readlines() f.seek(0) list = [0] * TxCnt finalmessage = "" message = "" for i in range(TxCnt): message = "" for j in range(7): fileLine = f.readline() message = message + fileLine finalmessage = finalmessage + fileLine[:len(fileLine)-1] + "\n" list[i] = message #bir sonraki **** + bu buldugu transaction f.close() for k in range (len(list)): list[k] = SHA3_256.new(list[k].encode('utf-8')) i = TxCnt while(i != 1): newlist = [0] * int((i/2)) newcounter = 0 j = 0 while( j < len(list)): h1 = list[j].digest() h2 = list[j+1].digest() newlist[newcounter] = (SHA3_256.new(h1+h2)) #hash j = j + 2 newcounter = newcounter + 1 i = i/2 list = newlist Nonce = lineList[len(lineList)-1] Nonce = int(Nonce[7:]) root = newlist[0].digest() hashed = (SHA3_256.new(root+(str(Nonce)+'\n').encode('UTF-8'))).hexdigest() #hashed = hash with message+nonce hashedVal = str(hashed) for i in range(PoWLen): if(hashedVal[i] != "0"): return "" # while (hashedVal[:PoWLen] != "0"*PoWLen): # Noncee = random.randint(2, pow(2,32)) # hashedVal = SHA3_256.new((hashed + str(Noncee)).encode('utf-8')).hexdigest() # print(Noncee) # return hashedVal return hashedVal
def tree(TxCnt, Block): hashTree = [] for i in range(0, TxCnt): transaction = "".join(Block[i * 9:(i + 1) * 9]) hashTree.append(SHA3_256.new(transaction.encode('UTF-8')).digest()) t = TxCnt j = 0 while (t > 1): for i in range(j, j + t, 2): hashTree.append( SHA3_256.new(hashTree[i] + hashTree[i + 1]).digest()) j += t t = t >> 1 return hashTree[2 * TxCnt - 2]
def encrypt_eaa(key, in_filename, data=None, out_filename=None, chunksize=64 * 1024): if in_filename[-5:] != '.json': in_filename += '.json' if data: with open(in_filename, 'w') as fp: json.dump(data, fp) if not out_filename: out_filename = in_filename[:-5] + '.eaa' key = SHA3_256.new().update(key.encode()).digest() iv = Random.new().read(AES.block_size) encryptor = AES.new(key, AES.MODE_CBC, IV=iv) filesize = os.path.getsize(in_filename) with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: outfile.write(struct.pack('<Q', filesize)) outfile.write(iv) while True: chunk = infile.read(chunksize) if len(chunk) == 0: break elif len(chunk) % AES.block_size != 0: chunk += b' ' * (AES.block_size - len(chunk) % 16) outfile.write(encryptor.encrypt(chunk)) os.remove(in_filename)
def test_update_after_digest(self): msg=b("rrrrttt") # Normally, update() cannot be done after digest() h = SHA3.new(data=msg[:4]) dig1 = h.digest() self.assertRaises(TypeError, h.update, msg[4:]) dig2 = SHA3.new(data=msg).digest() # With the proper flag, it is allowed h = SHA3.new(data=msg[:4], update_after_digest=True) self.assertEquals(h.digest(), dig1) # ... and the subsequent digest applies to the entire message # up to that point h.update(msg[4:]) self.assertEquals(h.digest(), dig2)
def test_update_after_digest(self): msg = b("rrrrttt") # Normally, update() cannot be done after digest() h = SHA3.new(data=msg[:4]) dig1 = h.digest() self.assertRaises(TypeError, h.update, msg[4:]) dig2 = SHA3.new(data=msg).digest() # With the proper flag, it is allowed h = SHA3.new(data=msg[:4], update_after_digest=True) self.assertEquals(h.digest(), dig1) # ... and the subsequent digest applies to the entire message # up to that point h.update(msg[4:]) self.assertEquals(h.digest(), dig2)
def hash(self, previous_hash: bytes) -> bytes: """ :param previous_hash: Hash del bloque anterior :return: Hash que debería tener la cabezera del bloque """ return SHA3_256.new(previous_hash + self.content.hash() + (self.timestamp).to_bytes(8, "big")).digest()
def __init__(self, signatureFile, hashAlgorithm, keyLength, privateKeyE): self.signatureFile = open(signatureFile, "w") self.hashAlgorithmName = hashAlgorithm self.keyLength = keyLength self.privateKey = privateKeyE #tuple of (n, e, d) if hashAlgorithm == 'SHA-2-224': self.hashAlgorithm = SHA224.new() elif hashAlgorithm == 'SHA-2-256': self.hashAlgorithm = SHA256.new() elif hashAlgorithm == 'SHA-2-384': self.hashAlgorithm = SHA384.new() elif hashAlgorithm == 'SHA-2-512': self.hashAlgorithm = SHA512.new() elif hashAlgorithm == 'SHA-3-224': self.hashAlgorithm = SHA3_224.new() elif hashAlgorithm == 'SHA-3-256': self.hashAlgorithm = SHA3_256.new() elif hashAlgorithm == 'SHA-2-384': self.hashAlgorithm = SHA3_384.new() elif hashAlgorithm == 'SHA-2-256': self.hashAlgorithm = SHA3_512.new() else: raise Exception("Invalid hash function: " + hashAlgorithm)
def decrypt_eaa(key, in_filename, out_filename=None, chunksize=64 * 1024): if not out_filename: out_filename = os.path.splitext(in_filename)[0] key = SHA3_256.new().update(key.encode()).digest() with open(in_filename, 'rb') as infile: origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0] iv = infile.read(16) decryptor = AES.new(key, AES.MODE_CBC, IV=iv) with open(out_filename, 'wb') as outfile: while True: chunk = infile.read(chunksize) if len(chunk) == 0: break decd = decryptor.decrypt(chunk) n = len(decd) if origsize > n: outfile.write(decd) else: outfile.write(decd[:origsize]) origsize -= n with open(out_filename) as fp: data = json.load(fp) os.remove(out_filename) return data
def get_sha3_256(self): hash_obj = SHA3_256.new() hash_obj.update(self.value) return { "digest": hash_obj.digest(), "hexdigets": hash_obj.hexdigest() }
def SignVer(message, s, r, q, p, g, beta): message = message.decode("utf-8") h = SHA3_256.new(bytes(str(message), 'utf-8')) h = int(h.hexdigest(), 16) v = modinv(h, q) z1 = (s * v) % q z2 = (r * v) % q # For calculate -z1 power of g in mod p # g^-z1 is equal to g^-z1+q in mod p # because g^q = 1 mod p z1 = -z1 + q u1 = pow(g, z1, p) u2 = pow(beta, z2, p) u = ((u1 * u2) % p) % q if u == r: # Signature Accepted # print("Accepted") return 0 else: # Signature Rejected # print("Rejected") return 1
def findHR(TxCnt, filename): f = open(str(filename), "r") T = [] for i in range(0, TxCnt): msg1 = f.readline() msg2 = f.readline() msg3 = f.readline() msg4 = f.readline() msg5 = f.readline() msg6 = f.readline() msg7 = f.readline() m = ''.join([msg1, msg2, msg3, msg4, msg5, msg6, msg7]) shake = SHA3_256.new(m.encode("UTF-8")) T.append(shake.digest()) nonce = f.readline() nonce = nonce[7:len(nonce)] f.close() while (len(T) > 1): T = MerkleTreeHash(T) root = T[0] #print(rootHash) return root, nonce
def CheckPow(p, q, g, PoWLen, TxCnt, filename): #filename = block_sample.txt #yine hash tree hesapla en sondaki nonce ile kontrol et #print("Checkpoint1") merkle_tree_root = merkle_tree_build("transactions.txt", TxCnt) #print("merkle tree root in CheckPoW: ", merkle_tree_root) #print("Checkpoint2") f = open(filename, "r") for line in f: pass #nonce = map(int, re.findall(r'\d+', line)) s = ''.join(x for x in line if x.isdigit()) nonce = int(s) print("nonce", nonce) f.close() zeros = "" i = 0 while i < PoWLen: zeros += "0" i += 1 #print("zeros = ", zeros) #print("root hash = ", merkle_tree_root) val = merkle_tree_root + nonce.to_bytes( (nonce.bit_length() + 7) // 8, byteorder='big') final_hash = SHA3_256.new(val).hexdigest() #print("Checkpoint4") print("final_hash = ", final_hash) if final_hash[:PoWLen] != zeros: # if there are not enough zeros return "" return final_hash
def GetRootHash(Block, TxCnt): TxLen = 9 hashTree = [] transaction = '' for i in range(0,TxCnt): transaction = "".join(Block[i*TxLen:(i+1)*TxLen]) hashTree.append(SHA3_256.new(transaction.encode('UTF-8')).digest()) t = TxCnt j = 0 while(t>1): for i in range(j,j+t,2): hashTree.append(SHA3_256.new(hashTree[i]+hashTree[i+1]).digest()) j += t t = t >> 1 return hashTree[2*TxCnt-2]
def _keygen(self, key): if type(key) is str: key = key.encode('utf-8') key_256bit = SHA3_256.new() key_256bit.update(key) key = key_256bit.digest() return key
def MerkleTreeHash(Hash): newValues = [] for i in range(0, int(len(Hash) / 2)): Hash2 = (Hash[2 * i]) + (Hash[(2 * i) + 1]) hashed = SHA3_256.new(Hash2).digest() newValues.append(hashed) return newValues
def block_info(request): try: block = Block.objects.get(id=request.GET.get('id')) confirmed_by = (Block.objects.all().count() - block.id) + 1 votes = Vote.objects.filter(block_id=request.GET.get('id')) vote_hashes = [ SHA3_256.new((f'{vote.uuid}|{vote.vote_party_id}|{vote.timestamp}' ).encode('utf-8')).hexdigest() for vote in votes ] root = MerkleTools() root.add_leaf([ f'{vote.uuid}|{vote.vote_party_id}|{vote.timestamp}' for vote in votes ], True) root.make_tree() merkle_hash = root.get_merkle_root() tampered = block.merkle_hash != merkle_hash context = { 'this_block': block, 'confirmed_by': confirmed_by, 'votes': zip(votes, vote_hashes), 're_merkle_hash': merkle_hash, 'isTampered': tampered, } return render(request, 'block-info.html', context) except Exception as e: print(str(e)) return render(request, 'block-info.html')
def SignVer(m, s, r, q, p, g, beta): m = m.decode('utf-8') #print('after decode:',m) For debugging #print("======after decode========") #print('s:',s) #print('r:',r) #print('q:',q) #print('p:',p) #print('g:',g) #print('beta:',beta) hsh = SHA3_256.new() hsh.update(bytes((str(m)).encode('utf-8'))) h = int(hsh.hexdigest(), 16) % q v = modinv(h, q) z1 = (s * v) % q z2 = (r * v) % q beta_temp = pow(beta, z2, p) g_temp = modinv(g, p) g_temp2 = pow(g_temp, z1, p) u = ((beta_temp * g_temp2) % p) % q #print('u:',u) #print('r:',r) if (u == r): return 0 else: return -1
def newHash(key): sha3 = SHA3_256.new() sha3.update(bytes(key, "ascii")) return sha3.digest()