def verify(self, s, signature): """ Check the signature of the string s :param s: String to check :type s: str :param signature: the signature to compare :type signature: str """ if isinstance(s, text_type): s = s.encode('utf8') r = False try: RSAkey = RSA.importKey(self.public) signature = long(signature) if SIGN_WITH_RSA: hashvalue = HashFunc.new(s).digest() r = RSAkey.verify(hashvalue, (signature,)) else: hashvalue = HashFunc.new(s) pkcs1_15.new(RSAkey).verify(hashvalue, signature) except Exception as _e: # pragma: no cover log.error("Failed to verify signature: {0!r}".format(s)) log.debug("{0!s}".format(traceback.format_exc())) return r
def got_data(self): while True: if len(self.recvbuf) < 4: return if self.recvbuf[:4] != "\xf9\xbe\xb4\xd9": raise ValueError("got garbage %s" % repr(self.recvbuf)) if len(self.recvbuf) < 4 + 12 + 4 + 4: return command = self.recvbuf[4:4+12].split("\x00", 1)[0] msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0] checksum = self.recvbuf[4+12+4:4+12+4+4] if len(self.recvbuf) < 4 + 12 + 4 + 4 + msglen: return msg = self.recvbuf[4+12+4+4:4+12+4+4+msglen] th = SHA256.new(msg).digest() h = SHA256.new(th).digest() if checksum != h[:4]: raise ValueError("got bad checksum %s" % repr(self.recvbuf)) self.recvbuf = self.recvbuf[4+12+4+4+msglen:] if command in self.messagemap: f = cStringIO.StringIO(msg) t = self.messagemap[command]() t.deserialize(f) self.got_message(t) else: print "UNKNOWN COMMAND", command, repr(msg)
def rename_directory(username, old_filename, new_filename): filelog = oldfilename + '.flog' with open(filelog, 'rb') as input: log = pickle.load(input) sig = pickle.load(input) block = log[username] key = RSA.importKey(open(username + '.pri').read()) cipher = PKCS1_OAEP.new(key, SHA256.new()) block.decrypt_permission_block(cipher) encrypted_new_filename = encrypt_filename(block.get_file_encryption_key(), new_filename) log['encrypted_name'] = encrypted_new_filename new_filelog = encrypted_new_filename + '.dlog' with open(new_filelog, 'wb') as outfile: pickle.dump(log) length = len(log) with open(new_filelog, 'rb') as infile: pickleload = infile.read(length) file_log_hash = SHA256.new() file_log_hash.update(picklelog) with open(username + '.dsa', 'rb') as infile: owner_msk = pickle.load(infile) k = random.StrongRandom().randint(1,owner_msk.q-1) sig = owner_msk.sign(file_log_hash.digest(), k) with open(new_filelog, 'a+b') as outfile: pickle.dump(sig, outfile, -1) return encrypted_new_filename
def is_valid(self, difficulty = None): # Calculate the Header Hash self.calc(difficulty) # Get Target target = get_target(self.nBits) # Check check_result, message = check_header_target(self.header, target) if not check_result: return False hashes = [] for tx in self.vtx: tx.sha256 = None if not tx.is_valid(): return False tx.calc_sha256() hashes.append(ser_uint256(tx.sha256)) while len(hashes) > 1: newhashes = [] for i in xrange(0, len(hashes), 2): i2 = min(i+1, len(hashes)-1) newhashes.append(SHA256.new(SHA256.new(hashes[i] + hashes[i2]).digest()).digest()) hashes = newhashes if uint256_from_str(hashes[0]) != self.hashMerkleRoot: return False return True
def chained_sha256(path='data/birthday.mp4', block_size=1024, renew=True, prepend=False): blocks = [] fp = open(path, 'rb') print 'Reading %s bytes from file %s' % (len(fp.read()), fp.name) fp.close() with open(path, 'rb') as fp: block = True while block: block = fp.read(block_size) if block: blocks += [block] print 'Read %s blocks of %s bytes each, and one last block of %s bytes for a total of %s bytes.' % ( len(blocks), block_size, len(blocks[-1]), sum(len(block) for block in blocks)) tag = b'' if not renew: sha = SHA256.new() for block in reversed(blocks): if renew: sha = SHA256.new() if prepend: sha.update(tag + block) else: sha.update(block + tag) tag = sha.digest() return tag.encode('hex')
def share_directory(other_username, dlog): with open(dlog, 'rb') as input: log = pickle.load(input) userList = log['users'] userList.append(other_username) owner_block = log[owner] owner = log['owner'] key = RSA.importKey(open(owner + '.pri').read()) cipher = PKCS1_OAEP.new(key, SHA256.new()) owner_block.decrypt_permission_block(cipher) file_aes_key = owner_block.get_file_encryption_key() file_dsa_key = None user_block = AccessBlock(file_aes_key, file_dsa_key) other_key = RSA.importKey(open(other_username + '.pub').read()) other_cipher = PKCS1_OAEP.new(other_key, SHA256.new()) user_block.encrypt_permission_block(other_cipher) log[other_username] = user_block file_log_hash = SHA256.new() with open(filelog, 'wb') as infile: pickle.dump(log, infile, -1) length = len(log) with open(filelog, 'rb') as outfile: picklelog = outfile.read(length) file_log_hash.update(picklelog) with open(owner + '.dsa', 'rb') as infile: owner_msk = pickle.load(infile) k = random.StrongRandom().randint(1,owner_msk.q-1) sig = owner_msk.sign(file_log_hash.digest(), k) with open(filelog, 'a+b') as outfile: pickle.dump(sig, outfile, -1)
def read_encrypted_logs(username, filelogs): names = [] my_key = RSA.importKey(open(username + '.pri').read()) cipher = PKCS1_OAEP.new(my_key, SHA256.new()) for log in filelogs: file_log_hash = SHA256.new() with open(log, 'rb') as input: dictlog = pickle.load(input) sig = pickle.load(input) owner = dictlog['owner'] with open(owner + '.dsapub', 'rb') as input: owner_msk = pickle.load(input) length = len(dictlog) with open(log, 'rb') as outfile: picklelog = outfile.read(length) file_log_hash.update(picklelog) if not owner_msk.verify(file_log_hash.digest(), sig): print('invalid file') if username in dictlog: block = dictlog[username] block.decrypt_permission_block(cipher) name = decrypt_filename(block.get_file_encryption_key(), log[0:-5]) names.append(name) return names
def unsalted_crack_combinitions(start, end): for i in range(start, end): curr_pass = passwords[i].strip("\n") print curr_pass for other in passwords: other = other.strip("\n") appended = curr_pass + other prepended = other + curr_pass a_sha256 = SHA256.new(appended) p_sha256 = SHA256.new(prepended) a_digest = a_sha256.hexdigest() p_digest = p_sha256.hexdigest() #print appended, a_digest #print prepended, p_digest if a_digest in hash_nosalt: r = open('result/'+ a_digest, 'w') result = a_digest + "\t" + appended r.write(result) r.close() print "Found!---> ", result if p_digest in hash_nosalt: r = open('result/'+ p_digest, 'w') result = p_digest + "\t" + prepended r.write(result) r.close() print "Found!---> ", result
def unsalted_crack_digits_ap(start,end): for i in range(start, end): curr_pass = passwords[i].strip("\n") for digit in range(0,10): a = curr_pass + str(digit) p = str(digit) + curr_pass a_sha256 = SHA256.new(a) p_sha256 = SHA256.new(p) a_digest = a_sha256.hexdigest() p_digest = p_sha256.hexdigest() if a_digest in hash_nosalt: r = open('result_crack_digits_ap/'+ a_digest, 'w') result = a_digest + "\t" + a + "\n" r.write(result) r.close() print "Found!---> ", result if p_digest in hash_nosalt: r = open('result_crack_digits_ap/'+ p_digest, 'w') result = p_digest + "\t" + p + "\n" r.write(result) r.close() print "Found!---> ", result
def solve_proof_of_work(self): """ solves the proof of work problem Starting with the random nonce, this thread will increment this value and hash the block with the nonce and test to see if the hash ends with the 'target' amount of zeros. If not, the nonce is incremented and a new hash is produced """ log.info('Mining started...') self.client.broadcast_info('Mining started') self.isMining = True hash = SHA256.new() #self.b.computeMerkleRoot() for t in self.transactions: self.b.add_transaction(t) # create an array of target-length bytes target = bytes(self.b.target) hash.update(self.b.pack()) digest = hash.digest() while not self.test_hash(digest, self.b.target): hash = SHA256.new() # update the nonce self.b.nonce += 1 hash.update(self.b.pack()) digest = hash.digest() if self.start_over: self.start_over = False return False return True
def is_valid(self): #self.calc_sha256() self.calc_scrypt() target = uint256_from_compact(self.nBits) #if self.sha256 > target: if self.scrypt > target: return False hashes = [] for tx in self.vtx: tx.sha256 = None if not tx.is_valid(): return False tx.calc_sha256() hashes.append(ser_uint256(tx.sha256)) while len(hashes) > 1: newhashes = [] for i in xrange(0, len(hashes), 2): i2 = min(i+1, len(hashes)-1) newhashes.append(SHA256.new(SHA256.new(hashes[i] + hashes[i2]).digest()).digest()) hashes = newhashes if uint256_from_str(hashes[0]) != self.hashMerkleRoot: return False return True
def send_message(self, message): if self.state == "closed": return if self.verbose: print "send %s" % repr(message) if hasattr(message, 'serialize'): # msg_ object command = message.command data = message.serialize() else: # JSON string or dictionary with JSON-encoded values in it: if not isinstance(message, dict): # JSON { "message" : [ fields ] } message = json.loads(message) command = message.keys()[0] obj = self.messagemap[command]() obj.from_array(message[command], self.replace_magic_constants) data = obj.serialize() tmsg = self.message_header tmsg += bytes(command) tmsg += b"\x00" * (12 - len(command)) tmsg += struct.pack("<I", len(data)) if self.ver_recv >= 209: th = SHA256.new(data).digest() h = SHA256.new(th).digest() tmsg += h[:4] tmsg += data self.sendbuf += tmsg
def decrypt_email(self, enc_email): salt = enc_email['From'][:32] enc_email.replace_header('From', enc_email['From'][33:]) plain_email = MIMEMultipart() for header in self.TOKENIZE_HEADER_PART: IV = SHA256.new(salt+ header).digest()[:16] if header == 'Subject': plain_email[header] = self.decrypt(IV, enc_email[header][ 66:enc_email[header].find('.', 99)+1]) else: if enc_email[header] != None: plain_email[header] = self.decrypt(IV, enc_email[header]) for part in enc_email.walk(): if (part.get_content_maintype() == 'multipart') and ( part.get_content_subtype() != 'plain'): continue body = part.get_payload() if body == None or body == '': return plain_email IV = SHA256.new(salt + 'Body').digest()[:16] plain_body = self.decrypt(IV, body[98:body.find('.', 131)+1]) plain_email.attach(MIMEText(plain_body)) return plain_email
def hash_160_to_bc_address(h160): if not have_crypto: return '' vh160 = "\x00"+h160 # \x00 is version 0 h3=SHA256.new(SHA256.new(vh160).digest()).digest() addr=vh160+h3[0:4] return b58encode(addr)
def post(self): otp = Otp() otp.learning_association = ndb.Key(urlsafe=self.request.POST.get('sf')) otp_token = SHA256.new(str(otp.learning_association.id()) + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(30))).hexdigest() otp.token = SHA256.new(otp_token).hexdigest() learning_association = otp.learning_association.get() if learning_association: otp.put() mail.send_mail(sender="Voksenopplæringsforbundet <*****@*****.**>", to="%s <%s>" % (learning_association.name, learning_association.email), subject="Engangspassord til reisestipendsøknader", body=""" Hei For å logge inn til reisestipendsøknadene, bruk denne lenken: %sotp/%s Lenken er gyldig i en time. Hilsen Voksenopplæringsforbundet """ % (myapp.APPLICATION_URL, otp_token)) template_values = { 'application_year': myapp.APPLICATION_YEAR, 'learning_association': learning_association } template = JINJA_ENVIRONMENT.get_template('login_sent.html') self.response.write(template.render(template_values)) else: self.abort(400)
def computeTag(fileName): #hash = SHA256.new() blocks = [] file = open(fileName, "rb") with file: while True: chunk = file.read(1024) if chunk: blocks.append(chunk) else: break print len(blocks) numBlocks = len(blocks) i = numBlocks-1 while i>0: hash = SHA256.new() hash.update(blocks[i]) blocks[i-1] = blocks[i-1] + hash.digest() i = i-1 #print blocks[numBlocks-1].encode('hex') #print blocks[0].encode('hex') hash = SHA256.new() hash.update(blocks[0]) tag = hash.hexdigest() print tag
def main(): parser = OptionParser() parser.add_option("--testnet", help="generate testnet addresses", dest="testnet", action="store_true", default=False) parser.add_option("--wif", help="specify a WIF address on the command line instead of generating it", dest="wif", action="store_true", default=False) (options, args) = parser.parse_args() if options.testnet: pywallet.addrtype = 111 if options.wif: sec_mini = None sec_raw = pywallet.DecodeBase58Check(args[0])[1:] elif args: sec_mini = args[0] if not valid_mini(sec_mini): print >>sys.stderr, "not a valid mini key" sys.exit(1) sec_raw = SHA256.new(sec_mini).digest() else: sec_mini = generate_mini_private_key() sec_raw = SHA256.new(sec_mini).digest() sec_hex = sec_raw.encode('hex').upper() sec_wallet = pywallet.EncodeBase58Check("\x80" + sec_raw) # wallet import format pkey = pywallet.regenerate_key(pywallet.SecretToASecret(sec_raw)) assert sec_raw == pywallet.GetSecret(pkey) priv_key = pywallet.GetPrivKey(pkey) pub_key = pywallet.GetPubKey(pkey) pub_addr = pywallet.public_key_to_bc_address(pub_key) print "Address: %s" % (pub_addr,) print "Privkey: %s" % (sec_wallet,) print "Privkey (hex): %s" % (sec_hex,) print "Privkey (mini): %s" % (sec_mini,)
def hash(self, first, second): """ Snapchats hashing function :param first: :param second: :return: """ first = self.SECRET + first second = second + self.SECRET hash = SHA256.new() hash.update(first) hash1 = hash.hexdigest() hash = SHA256.new() hash.update(second) hash2 = hash.hexdigest() result = '' for i in range(len(self.HASH_PATTERN)): if int(self.HASH_PATTERN[i]): result += hash2[i] else: result += hash1[i] return result
def _recomputeDigest(self): """ Digest the fields and set self._digest to the hex digest. """ sha256 = SHA256.new() number = bytearray(4) # Debug: sync-state.proto defines seq and session as uint64, but # the original ChronoChat-js only digests 32 bits. self._int32ToLittleEndian(self._sessionNo, number) sha256.update(number) self._int32ToLittleEndian(self._sequenceNo, number) sha256.update(number) sequenceDigest = sha256.digest() sha256 = SHA256.new() # Use Blob to convert a string to UTF-8 if needed. sha256.update(Blob(self._dataPrefix).toBuffer()); nameDigest = sha256.digest() sha256 = SHA256.new() sha256.update(nameDigest) sha256.update(sequenceDigest) nodeDigest = sha256.digest() # Use Blob to convert a str (Python 2) or bytes (Python 3) to hex. self._digest = Blob(nodeDigest).toHex()
def makeKey(self, password, salt): salt_hash = SHA256.new() salt_hash.update(salt) pass_hash = SHA256.new() pass_hash.update(salt_hash.hexdigest().encode('utf8')) pass_hash.update(password.encode('utf8')) return pass_hash.digest()
def main(): file_name = 'v1.mp4' block_size = 1024 statinfo = os.stat(file_name) file_size = statinfo.st_size print 'File name: ' + file_name print 'File size: ' + repr(file_size) last_block_size = file_size % block_size with open(file_name, 'rb') as f: block = bytearray() hash_block = bytearray() if last_block_size != 0: pos = (-1)*last_block_size f.seek(pos, 2) # offset relative to the end block = f.read(last_block_size) # read to the end h = SHA256.new(data=block) hash_block = h.digest() last_block_size = 0 print 'last block hash: ' + h.hexdigest() + ' pos: ' + repr(f.tell()) for i in range(file_size/block_size,0,-1): pos = pos - block_size f.seek(pos, 2) block = f.read(block_size) block = block + hash_block h = SHA256.new(data=block) hash_block = h.digest() print 'block ' + repr(i) + ' hash: ' + h.hexdigest() + ' pos: ' + repr(f.tell()) print 'Hash: ' + repr(h.hexdigest())
def decrypt_model(self, in_model, uniqid): if not isinstance(in_model, Secret): raise RuntimeException('in_model is not an instance of Secret') #generate the input for our key derivation formula hasher = SHA256.new() hasher.update('{}{}'.format(uniqid, in_model.Nonce)) keyhash = hasher.digest() #derive our AES key (aes256 wants 32bytes) aeskey = PBKDF2( password=keyhash, salt=in_model.Salt, dkLen=32, count=10000, ) #derive our Iv from the UniqID (16 bytes) hasher = SHA256.new() hasher.update('{}{}'.format(uniqid, aeskey)) aesiv = hasher.digest()[:16] #unpad from http://stackoverflow.com/a/12525165/274549 ## s[:-ord(s[len(s)-1:])] BS = 16 unpad = lambda s : s[0:-ord(s[-1])] #encrypt it w/ padding cipher = AES.new(aeskey, AES.MODE_CBC, aesiv) return unpad(cipher.decrypt(in_model.CipherText))
def decrypt(in_file, out_file, password, key_length=32, read_blocks=1024): """ Decrypt data stream using password as the seed to decryption key. Calculate checksums for both the ciphertext data and the plaintext data during the decryption. """ ciphertext_checksum = SHA256.new() plaintext_checksum = SHA256.new() block_size = AES.block_size salt = in_file.read(block_size) ciphertext_checksum.update(salt) key, iv = derive_key_and_iv(str(password), salt, key_length, block_size) cipher = AES.new(key, AES.MODE_CBC, iv) next_chunk = "" finished = False while not finished: encrypted_chunk = in_file.read(read_blocks * block_size) ciphertext_checksum.update(encrypted_chunk) chunk, next_chunk = next_chunk, cipher.decrypt(encrypted_chunk) if len(next_chunk) == 0: padding_length = ord(chunk[-1]) chunk = chunk[:-padding_length] finished = True out_file.write(chunk) plaintext_checksum.update(chunk) return ciphertext_checksum.hexdigest(), plaintext_checksum.hexdigest()
def hash_160_to_bc_address(h160, version="\x00"): if not have_crypto: return "" vh160 = version + h160 h3 = SHA256.new(SHA256.new(vh160).digest()).digest() addr = vh160 + h3[0:4] return b58encode(addr)
def encrypt(in_file, out_file, password, key_length=32, read_blocks=1024): """ Encrypt data stream using password as the seed to encryption key. Calculate checksums for both the plaintext data and the ciphertext data during the encryption. """ plaintext_checksum = SHA256.new() ciphertext_checksum = SHA256.new() block_size = AES.block_size salt = Random.new().read(block_size) key, iv = derive_key_and_iv(str(password), salt, key_length, block_size) cipher = AES.new(key, AES.MODE_CBC, iv) out_file.write(salt) ciphertext_checksum.update(salt) finished = False while not finished: chunk = in_file.read(read_blocks * block_size) plaintext_checksum.update(chunk) if len(chunk) == 0 or len(chunk) % block_size != 0: padding_length = ((block_size - len(chunk) % block_size) or block_size) chunk += padding_length * chr(padding_length) finished = True encrypted_chunk = cipher.encrypt(chunk) out_file.write(encrypted_chunk) ciphertext_checksum.update(encrypted_chunk) return plaintext_checksum.hexdigest(), ciphertext_checksum.hexdigest()
def shasha(*args): h= SHA256.new() for x in args: h.update(x) h2= SHA256.new() h2.update(h.digest()) return h2.digest()
def post(self): if self.get_secure_cookie('email'): email=self.get_secure_cookie('email') users_coll=self.application.db.users user = yield users_coll.find_one({'email':email}) if user: hide = self.get_argument('hide') oldpass = self.get_argument('oldpas') newpass = self.get_argument ('newpas') if not oldpass=="1": if hide == email and user["password"] == SHA256.new(oldpass).hexdigest() and not newpass=="1": user["email"] = self.get_argument('email') user["name"] = self.get_argument('name') user["password"] = SHA256.new(newpass).hexdigest() yield users_coll.save(user) self.redirect("/profile") else: self.redirect("/") else: user["email"] = self.get_argument('email') user["name"] = self.get_argument('name') yield users_coll.save(user) self.redirect("/profile") else: self.redirect("/")
def decrypt(self, buff): md = SHA256.new(buff[:-0x100]) verifier = PKCS1_v1_5.new(self._static_pubkey) if verifier.verify(md, buff[-0x100:]) == False: raise ValueError('Invalid signature in footer.') if self._pubkey is not None: md = SHA256.new(buff[:-0x200]) verifier = PKCS1_v1_5.new(self._pubkey) if verifier.verify(md, buff[-0x200:-0x100]) == False: raise ValueError('Invalid signature in footer.') buff = buff[:-0x200] nonce = array.array('I', buff[-4:]) nonce.byteswap() length = len(buff) - 4 buff = array.array('I', buff[:-4] + b'\x00' * (8 - length % 8)) buff.byteswap() counter = Counter.new(32, prefix=nonce.tostring(), initial_value=0, little_endian=True) cipher = Blowfish.new(self._key, Blowfish.MODE_CTR, counter=counter) buff = array.array('I', cipher.decrypt(buff.tostring())) buff.byteswap() buff = buff.tostring()[:length] md = buff[-20:] buff = buff[:-20] if md != hashlib.sha1(buff).digest(): raise ValueError('Invalid SHA1 hash in footer.') return buff
def verify_file(f, signature): # Verify the file was sent by the bot master # TODO: For Part 2, you'll use public key crypto here # Naive verification by ensuring the first line has the "passkey" # Split message up by line breaks into an array split_f = f.split(b"\n") # Check for a private key if len(split_f) < 27: return False # Decrypt the message using the private key message, dsize = decrypt_message(split_f) # Verify encryption digest = SHA256.new(message[:-dsize]).digest() if digest == message[-dsize:]: # Remove digest from message message = message[:-dsize] # Hash message for verification hashed_m = SHA256.new(message) # Verify signature using the public key pukey = RSA.importKey(open(os.path.join("pastebot.net", "publickey"), "rb").read()) verifier = PKCS1_v1_5.new(pukey) return verifier.verify(hashed_m, signature)
def buildTransactionInput(inputParameters, rawTransaction, hashtype): # Sequence is set to UNIT_MAX = "FFFFFFFF" because this will permanently lock this transaction # - Sequence is intended to work with Replacements, but Replacement is currently disabled inputSequence = "ffffffff" (previousTransactionHash, previousTransactionOutputIndex, previousTransactionOutputPublicAddress, privateKey ) = inputParameters reversePreviousTransactionHash = previousTransactionHash.decode("hex")[::-1].encode("hex") previousTransactionOutputIndexHex = struct.pack('<L', previousTransactionOutputIndex).encode('hex') singleSHA256_RawTransaction = SHA256.new(rawTransaction.decode("hex")).hexdigest() doubleSHA256_RawTransaction = SHA256.new(singleSHA256_RawTransaction.decode("hex")).digest() scriptSig = buildScriptSig(privateKey, doubleSHA256_RawTransaction, hashtype) scriptSigLength = "%02x" % len(scriptSig.decode("hex")) transactionInput = (reversePreviousTransactionHash + previousTransactionOutputIndexHex + scriptSigLength + scriptSig + inputSequence) # print transactionInput return transactionInput
def change_password(new_pass, client_socket, server_socket): clients[client_socket].password = SHA256.new(new_pass.encode()) print(clients[client_socket].password) send_to_client("[SERVER] Password changed!\n", client_socket, server_socket)
data, address = client.recvfrom(1024) port = address[1] if str(port) == str(PORT): leaderdata = data RECV = True unpickled = pickle.loads(data) messages.append(unpickled[0].decode()) signs.append(unpickled[1]) print(messages) if len(messages) >= 3: if len(set(messages)) == 1: print("committed: ", messages[0]) else: sender = [] for i in range(len(signs)): digest = SHA256.new() digest.update(messages[i].encode()) sender.append(verifier.verify(digest, signs[i])) if all(flag == True for flag in sender) == True: print("no commit") else: signed_messages = [messages[m] for m in range(len(sender)) if sender[m] == True] if len(set(signed_messages)) == 1: print("committed: ", signed_messages[0]) else: print("no commit") STAGE = 'DONE' if not (inputready or outputready or exceptrdy): if NEW_MESSAGE: NEW_MESSAGE = False
def generateKey(iv, base_string): key = iv + '\x00' * 16 for i in range(8192): key = SHA256.new(key + base_string).digest() return key
def check_password(clear_password, password_hash): return SHA256.new(clear_password).hexdigest() == password_hash
def buildFirm(args): if not (len(args.section_data) == len(args.section_copy_methods)): raise ValueError("number of sections not matching") elif len(args.section_addresses) > 4 or len(args.section_data) > 4 or len( args.section_copy_methods) > 4: raise ValueError("too many sections") if (not args.signature) and args.type: args.signature = args.type addrpos = 0 firmObj = Firm(args.signature) if args.signature else Firm() firmObj.arm9Entrypoint = args.arm9_entrypoint firmObj.arm11Entrypoint = args.arm11_entrypoint arm11Flags = 0 if args.suggest_screen_init: arm11Flags |= 1 if args.suggest_skipping_bootrom_lockout: arm11Flags |= 2 firmObj.reserved = unhexlify( "{0:02x}".format(arm11Flags)) + firmObj.reserved[1:] for i in range(len(args.section_copy_methods)): magic = args.section_data[i].read(4) args.section_data[i].seek(0) if len(magic) == 4 and magic == b"\x7FELF": entry, firmObj.sections[i].address, data = extractElf( args.section_data[i]) firmObj.sections[i].copyMethod = ("NDMA", "XDMA", "memcpy").index( args.section_copy_methods[i]) firmObj.arm9Entrypoint = entry if firmObj.arm9Entrypoint == 0 and args.section_copy_methods[ i] == "NDMA" else firmObj.arm9Entrypoint firmObj.arm11Entrypoint = entry if firmObj.arm11Entrypoint == 0 and args.section_copy_methods[ i] == "XDMA" else firmObj.arm11Entrypoint firmObj.setSectionData(i, data) else: if addrpos >= len(args.section_addresses): raise argparse.ArgumentError("missing section addresses") firmObj.sections[i].address = args.section_addresses[addrpos] firmObj.sections[i].copyMethod = ("NDMA", "XDMA", "memcpy").index( args.section_copy_methods[i]) firmObj.setSectionData(i, args.section_data[i].read()) addrpos += 1 firmObj.check() if not firmObj.arm9EntrypointFound: raise ValueError("invalid or missing Arm9 entrypoint") if not (firmObj.arm11Entrypoint == 0 or firmObj.arm11EntrypointFound ): # bootrom / FIRM won't boot firms with a NULL arm11 ep, though raise ValueError("invalid or missing Arm11 entrypoint") if args.signature: firmObj.signature = unhexlify(perfectSignatures["firm-" + args.signature]) data = firmObj.build() args.outfile.write(data) if args.generate_hash: with open(args.outfile.name + ".sha", "wb+") as f: f.write(SHA256.new(data).digest())
def rsaSign(data,private_key): key = RSA.importKey(private_key) hash_obj = SHA256.new(data.encode()) signer = PKCS1_v1_5.new(key) d = b64encode(signer.sign(hash_obj)) return d
def rsaVerify(data,public_key,sign): _logger.info(public_key) rsakey = RSA.importKey(public_key) res = SHA256.new(data) verifier = PKCS1_v1_5.new(rsakey) return verifier.verify(res,b64decode(sign))
def sign_message(my_private_key, data): key = RSA.import_key(my_private_key) h = SHA256.new(data) return pkcs1_15.new(key).sign(h)
def getKey(password): hasher = SHA256.new(password.encode('utf-8')) return hasher.digest()
mode = sys.argv[1].lower() if mode == 'hash': with open(sys.argv[2], 'rb') as f: # read the file from the end to the begining f.seek(0, os.SEEK_END) size = f.tell() # size of the last block pos = f.tell() % BLOCK_SIZE h = None while pos <= size: f.seek(-pos, os.SEEK_END) block = f.read(BLOCK_SIZE) h = SHA256.new(data=b"".join([block, (h.digest() if h else b"")])) pos += BLOCK_SIZE print(h.hexdigest()) elif mode == 'verify': verh = bytes.fromhex(sys.argv[2]) # read a block and it's hash while True: block = sys.stdin.buffer.read(BLOCK_SIZE + 32) if len(block) < (BLOCK_SIZE + 32): # last block break calch = SHA256.new(data=block).digest() if calch != verh: # FIXME: timing attacks
def valid(self): plaintext = str(self.amount) + key_to_string( self.sender) + key_to_string(self.recipient) Hash = SHA256.new(plaintext.encode()).digest() return verify_message(self.sign, Hash, self.sender)
def hash_message(plain_text): return SHA256.new(data=plain_text.encode("utf-8"))
def get_hashed_passwd(self): hash = SHA256.new(self.__shaKey) return hash.hexdigest()
from Crypto.Cipher import AES from Crypto.Hash import SHA256 from Crypto import Random import hashlib # travis encrypt PASSWORD=password -a -x sha = SHA256.new() sha.update(raw_input('Password:'******'emails.txt', 'rb').read() iv = text[:AES.block_size] cipher = text[AES.block_size:] aes = AES.new(key, AES.MODE_CBC, iv) plain = aes.decrypt(cipher).strip() print 'Decrypted: "' + plain + '"' plain += ',' + raw_input('Append data:') plain += ' ' * (AES.block_size - len(plain) % AES.block_size) iv = Random.new().read(AES.block_size) aes = AES.new(key, AES.MODE_CBC, iv) cipher = aes.encrypt(plain) open('emails.txt', 'wb').write(iv + cipher)
def sign_message(private_key, message): h = SHA256.new(message) signer = PKCS1_PSS.new(private_key) signature = signer.sign(h) return signature
def get_hash(field): hash = SHA256.new(field.encode('utf-8')) return hash.hexdigest()
def main(): from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA from Crypto.Util.number import ceil_div import base64 import logging import os import struct logging.basicConfig() logger = logging.getLogger(os.path.basename(__file__)) args = get_args(logger) with open(args.key, 'rb') as f: key = RSA.importKey(f.read()) with open(args.inf, 'rb') as f: img = f.read() h = SHA256.new() digest_len = h.digest_size try: # This works in pycrypto sig_len = ceil_div(key.size() + 1, 8) except NotImplementedError: # ... and this one - in pycryptodome sig_len = key.size_in_bytes() img_size = len(img) hdr_version = args.ta_version # struct shdr_bootstrap_ta::ta_version magic = 0x4f545348 # SHDR_MAGIC img_type = 1 # SHDR_BOOTSTRAP_TA algo = 0x70004830 # TEE_ALG_RSASSA_PKCS1_V1_5_SHA256 shdr = struct.pack('<IIIIHH', magic, img_type, img_size, algo, digest_len, sig_len) shdr_uuid = args.uuid.bytes shdr_version = struct.pack('<I', hdr_version) h.update(shdr) h.update(shdr_uuid) h.update(shdr_version) h.update(img) img_digest = h.digest() def write_image_with_signature(sig): with open(args.outf, 'wb') as f: f.write(shdr) f.write(img_digest) f.write(sig) f.write(shdr_uuid) f.write(shdr_version) f.write(img) def sign_ta(): if not key.has_private(): logger.error('Provided key cannot be used for signing, ' + 'please use offline-signing mode.') sys.exit(1) else: signer = PKCS1_v1_5.new(key) sig = signer.sign(h) if len(sig) != sig_len: raise Exception( ("Actual signature length is not equal to ", "the computed one: {} != {}").format(len(sig), sig_len)) write_image_with_signature(sig) logger.info('Successfully signed application.') def generate_digest(): with open(args.digf, 'wb+') as digfile: digfile.write(base64.b64encode(img_digest)) def stitch_ta(): try: with open(args.sigf, 'r') as sigfile: sig = base64.b64decode(sigfile.read()) except IOError: if not os.path.exists(args.digf): generate_digest() logger.error( 'No signature file found. Please sign\n %s\n' + 'offline and place the signature at \n %s\n' + 'or pass a different location ' + 'using the --sig argument.\n', args.digf, args.sigf) sys.exit(1) else: verifier = PKCS1_v1_5.new(key) if verifier.verify(h, sig): write_image_with_signature(sig) logger.info('Successfully applied signature.') else: logger.error('Verification failed, ignoring given signature.') sys.exit(1) # dispatch command { 'sign': sign_ta, 'digest': generate_digest, 'generate-digest': generate_digest, 'stitch': stitch_ta, 'stitch-ta': stitch_ta }.get(args.command, 'sign_ta')()
def __init__(self, master_pass): password = master_pass.encode('utf-8') self.__shaKey = SHA256.new(password)
def sha256(s): return SHA256.new(s).digest()
data = connection.recv(2000) data_hex = data.decode("utf-8") c_t = data_hex.split(",")[0] c_id = data_hex.split(",")[1] sign_CT = bytes.fromhex(data_hex.split(",")[2]) with open('clients_id_pk.csv', 'r') as f: reader = csv.reader(f, delimiter=',') data = list(reader) public_key_n = int(data[int(c_id)][1]) public_key_e = int(data[int(c_id)][2]) data_key = [public_key_n, public_key_e] public_key = RSA.construct(data_key) verify_signature(public_key, sign_CT, SHA256.new(c_t.encode("utf-8"))) print("C_T obtained", c_t) print("Written to Server") c_i_entry = [c_t] myFile = open('cipher_text.csv', 'w', newline='') with myFile: writer = csv.writer(myFile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) writer.writerow(c_i_entry) finally: # Clean up the connection connection.close()
def decrypt_file(in_filename, file_offset, private_key, public_key, nofilename, outputdir, verbose): if verbose: print 'decrypting ' + in_filename print 'RSA key ' + private_key BLOCK_SIZE = AES.block_size MODE = AES.MODE_CBC CHUNK_SIZE = BLOCK_SIZE * 1024 f = open(private_key, 'r') privatersa_key = RSA.importKey(f.read()) cipher = PKCS1_OAEP.new(privatersa_key) with open(in_filename, 'rb') as infile: infile.seek(file_offset) file_sha256_checksum = SHA256.new() signature_bin = infile.read(512) enc_pass = infile.read(512) enc_salt = infile.read(512) if not nofilename: enc_filename = infile.read(512) file_sha256_checksum.update(enc_pass) file_sha256_checksum.update(enc_salt) if not nofilename: file_sha256_checksum.update(enc_filename) while True: chunk = infile.read(CHUNK_SIZE) if len(chunk) == 0: break file_sha256_checksum.update(chunk) infile.close() sha256sum = file_sha256_checksum.hexdigest() if verbose: print 'sha256 sum of enc file ' + sha256sum f = open(public_key, 'r') publicrsa_key = RSA.importKey(f.read()) if not verify_file_signature(file_sha256_checksum, signature_bin, publicrsa_key): print 'Signature verification failed' return False password = cipher.decrypt(enc_pass) salt_header = cipher.decrypt(enc_salt) salt = salt_header[len('Salted__'):] key, iv = derive_key_iv(password, salt) if outputdir == None: outputdir = os.path.dirname(in_filename) if not nofilename: try: filename = cipher.decrypt(enc_filename) except: print 'Error getting filename try with -n option' return False out_filename = os.path.join(outputdir, filename) if nofilename: out_filename = os.path.join( outputdir, os.path.splitext(os.path.basename())[0] + '.tgz') print out_filename with open(in_filename, 'rb') as infile: if not nofilename: infile.seek(2048 + file_offset) if nofilename: infile.seek(1536 + file_offset) decryptor = AES.new(key, MODE, iv) with open(out_filename, 'wb') as outfile: next_chunk = '' finished = False while not finished: chunk, next_chunk = next_chunk, decryptor.decrypt( infile.read(CHUNK_SIZE)) if len(next_chunk) == 0: padding_length = ord(chunk[-1]) chunk = chunk[:-padding_length] finished = True outfile.write(chunk) outfile.close() infile.close() return True
def pubkey_to_hash(pubkey): return RIPEMD160.new(SHA256.new(pubkey).digest()).digest()
def main(): parser = argparse.ArgumentParser() parser.add_argument('mode') parser.add_argument('-d') parser.add_argument('-p') parser.add_argument('-r') parser.add_argument('-vk') args = parser.parse_args() mode = args.mode tD = args.d if args.p != None: aPK = open(args.p, 'r') lines = aPK.readlines() aPK.close() bits = int(lines[0]) aPubN = int(lines[1]) aPubE = int(lines[2]) if args.r != None: aSK = open(args.r, 'r') lines = aSK.readlines() aSK.close() aPriN = int(lines[1]) aPriD = int(lines[2]) if args.vk != None: vPK = open(args.vk, 'r') lines = vPK.readlines() vPK.close() vPubN = int(lines[1]) vPubE = int(lines[2]) if mode == "lock": sigFile = args.p + "-casig" sF = open(sigFile, 'r') line = sF.readline() sF.close() sig = int(line) hF = open(args.p, 'r') buf = hF.read() buf = buf.encode('utf-8') h = SHA256.new() h.update(buf) h = h.hexdigest() if SL.rsaVal(h, sig, vPubN, vPubE) == False: print("unlocking public key invalid, abort") return else: print(True) key = symKey(aPubN, aPubE, aPriN, aPriD, bits, tD) encryptDir(tD, key) delFiles(tD) macFile(tD, key) if mode == "unlock": sigFile = args.p + "-casig" sF = open(sigFile, 'r') line = sF.readline() sF.close() sig = int(line) hF = open(args.p, 'r') buf = hF.read() buf = buf.encode('utf-8') h = SHA256.new() h.update(buf) h = h.hexdigest() if SL.rsaVal(h, sig, vPubN, vPubE) == False: print("locking public key invalid, abort") else: print(True) if not cleanup(tD, aPubN, aPubE): print("error") return key = findKey(aPriN, aPriD, bits, tD) valid = valMacs(tD, key) if valid == False: print("A tag did not match the file, abort") decryptDir(tD, key) return
import time import Crypto from Crypto.Hash import SHA256 from Crypto.Cipher import AES from Crypto.Util import number from Crypto.Random import get_random_bytes temps0 = time.perf_counter() # Question 1 print("Question 1") m = SHA256.new() n = 0 while not m.hexdigest().endswith("4c4f4c"): m.update(b"bahia") n += 1 print("n = " + str(n) + " \nhexdigest = " + m.hexdigest()) temps1 = time.perf_counter() print('Question 1 time :', temps1 - temps0, 'seconds') e = SHA256.new(n * b"bahia") print("Verification:" + str(e.digest()))
#!/usr/bin/python import sys from Crypto.Hash import SHA256 input_text1 = open(sys.argv[1]).read() input_text2 = open(sys.argv[2]).read() hs = SHA256.new() hs.update(input_text1) output_text1 = hs.digest() hs = SHA256.new() hs.update(input_text2) output_text2 = hs.digest() hamming_dist = 0 for i in range(len(output_text1)): if output_text1[i] != output_text2[i]: hamming_dist += 1 with open(sys.argv[3], 'a+') as f: f.write(hex(hamming_dist)) # print hex(hamming_dist)
def digest(algorithm=_DEFAULT_HASH_ALGORITHM, hash_library=_DEFAULT_HASH_LIBRARY): """ <Purpose> Provide the caller with the ability to create digest objects without having to worry about hash library availability or which library to use. The caller also has the option of specifying which hash algorithm and/or library to use. # Creation of a digest object using defaults # or by specifying hash algorithm and library. digest_object = ssl_crypto.hash.digest() digest_object = ssl_crypto.hash.digest('sha384') digest_object = ssl_crypto.hash.digest('pycrypto') # The expected interface for digest objects. digest_object.digest_size digest_object.hexdigest() digest_object.update('data') digest_object.digest() # Added hash routines by this module. digest_object = ssl_crypto.hash.digest_fileobject(file_object) digest_object = ssl_crypto.hash.digest_filename(filename) <Arguments> algorithm: The hash algorithm (e.g., md5, sha1, sha256). hash_library: The library providing the hash algorithms (e.g., pycrypto, hashlib). <Exceptions> ssl_commons__exceptions.UnsupportedAlgorithmError ssl_commons__exceptions.UnsupportedLibraryError <Side Effects> None. <Returns> Digest object (e.g., hashlib.new(algorithm) or algorithm.new() # pycrypto). """ # Was a hashlib digest object requested and is it supported? # If so, return the digest object. if hash_library == 'hashlib' and hash_library in _supported_libraries: try: return hashlib.new(algorithm) except ValueError: raise ssl_commons__exceptions.UnsupportedAlgorithmError(algorithm) # Was a pycrypto digest object requested and is it supported? elif hash_library == 'pycrypto' and hash_library in _supported_libraries: # Pycrypto does not offer a comparable hashlib.new(hashname). # Let's first check the 'algorithm' argument before returning # the correct pycrypto digest object using pycrypto's object construction. if algorithm == 'md5': return MD5.new() elif algorithm == 'sha1': return SHA.new() elif algorithm == 'sha224': return SHA224.new() elif algorithm == 'sha256': return SHA256.new() elif algorithm == 'sha384': return SHA384.new() elif algorithm == 'sha512': return SHA512.new() else: raise ssl_commons__exceptions.UnsupportedAlgorithmError(algorithm) # The requested hash library is not supported. else: raise ssl_commons__exceptions.UnsupportedLibraryError('Unsupported library requested. ' 'Supported hash libraries: '+str(_SUPPORTED_LIB_LIST))
def applyCertificateChain(self, message, public_key, signature): hash_message = SHA256.new(message); verified = PKCS1_v1_5.new(public_key).verify(hash_message, signature) if verified == True: return self.generateCertiChain(public_key);
from Crypto.PublicKey import RSA from Crypto import Random from Crypto.Hash import SHA256 import random random_generator=Random.new().read key=RSA.generate(1024,random_generator) public_key=key.publickey().exportKey('OpenSSH') pubkey=RSA.importKey(public_key) mes="jello" hash=SHA256.new(mes).digest() signature=key.sign(hash, '') sig=signature[0] if pubkey.verify(hash,(sig,"")): print "The signature is authentic" else: print "The signature is not authentic"
def applyToRootCA(self, message, intermedia): hash_message = SHA256.new(message); signature = PKCS1_v1_5.new(self.key).sign(hash_message) return intermedia.applyCertificateChain(message, self.publicKey, signature)
def applyCertificateChain(self, message, PKI_object): hash_message = SHA256.new(message) signature = PKCS1_v1_5.new(self.key).sign(hash_message) return PKI_object.applyCertificateChain(message, self.publicKey, signature)