I have the following code which helps to bruteforce hashes
The first if statement will run, the values are hash=wordlist.txt, args=abtfg, values=[0, "0,1", 0, wordlist.txt, true]
def bruteforce(hash, args, values):
if "." in hash:
files = open(values[args.find("f")]) # Open wordlist.txt
for xhsd in files.readlines():
hash = xhsd
alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet += alphabet.upper() + "0123456789!$%^&*(){}~#][;:'#/?.>,<"
if "b" in args: # It is
m = args.find("b")
m = values[m]
else:
m = "0,16"
# m is 0,10
start_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
l = 0
print("Cracking...")
attempts = 0
while l == 0:
password = ""
for x in range(random.randrange(int(m.split(",")[0])+1,int(m.split(",")[1])+1)): # range(random.randrange(0,10))
password += alphabet[random.randrange(0,len(alphabet)-1)]
num = hash_types[int(values[args.find("t")])] # num="md5"
htype = "hash2 = hashlib."+num+"(password).hexdigest()"
exec(htype) # hash2 = md5(password)
print hash2 + ":" + hash # Compares the hashes
if hash == hash2:
print password
l = 1
else:
print "Trying..."
The first item it tries, it cracks it almost instantly, printing:
0cc175b9c0f1b6a831c399e269772661:0cc175b9c0f1b6a831c399e269772661
(this is hash2 and hash). So we now know these two variables are equal. However, the if statement directly below it, doesn't run. This is the weirdest thing I've seen in Python, could anyone explain why this is? I've printed both variables and they're clearly the same...
Removing whitespace could help:
if hash.strip() == hash2.strip():
Related
So I'm making this code that uses strings to cipher a given phrase with a given key (I can't use the preset functions in python to do it). I believe I've got the idea of how to do it but I;m experiencing this error that I can't figure out how to fix. My code is the following.
def inputForChipher():
input1 = False
input2 = False
while input1 == False:
string = input('Enter the message: ')
input1 = verifyString(string)
while input2 == False:
key = input('Enter the key you want to use: ')
input2 = verifyString(key)
print(cipherWithKey(string, key))
def cipherWithKey(string, key):
string = string.lower()
key = key.lower()
letters = 'abcdefghijklmnopqrstuvwxyz'
count = 0
newCode = ''
for i in string:
if i == '':
count = 0
newCode += i
else:
if count > (len(key)-1):
count = 0
value1 = letters.index(i) + 1
value2 = letters.index(key[count]) + 1
num = value1 + value2
if num > 26:
num -= 26
newCode += letters[num-1]
count += 1
return newCode
And I'm getting the following error:
File "C:\Users\xxxxx\Desktop\funciones.py", line 29, in cipherWithKey
value1 = letters.index(i) + 1
ValueError: substring not found
I know what causes this error, but I'm not sure of why I'm getting it in this case.
well its clear , in your input 'tarea de' you are passing space in your input ( string varible) which is not in letters variable and it fails in that line.
you can add the possible characters to your letters variable like :
letters = 'abcdefghijklmnopqrstuvwxyz '
alternatively you can use string module to provide the full list of whitespaces
import string as st
letters = st.ascii_lowercase + st.whitespace
This is a script that is a simple proof of work and it's in md5 algo. Is there any way I can use it to transfer it to sha256?
# proof-of-work.py
import md5
string = "1"
complete = False
n = 0
while complete == False:
curr_string = string + str(n)
curr_hash = md5.new(curr_string).hexdigest()
n = n + 1
# slows performance drastically
## print curr_hash
if curr_hash.startswith('000000'):
print curr_hash
print curr_string
complete = True
from hashlib import sha256
string = "1"
complete = False
n = 0
while complete == False:
curr_string = string + str(n)
curr_hash = sha256(curr_string.encode()).hexdigest()
n = n + 1
print(curr_hash + ' ' + curr_hash[:4])
This outputs hashes and first 4 bytes like this:
c19df416e581278d028f20527b96c018f313e983f0a9bda4914679bb482d14f6 c19d
b5662892a57d57b6d904fa6243fae838c28aaebc190fc885ee2e20de6fbcaddb b566
a9c0a662c81abe40bca7d250e93965285e0aea74f2f3edde704015c11e98cdeb a9c0
635f19669b8b48cd78f05bfe52ccf4bfbdb55e544486d71404f5fa786d93e5be 635f
and never ends. Add your logic to exit the loop.
I'm currently making an encryption program for an assignment however I cannot decrypt. The cause of this is that the key is a string made from a randomly generated bitstring however when turning the key back into a bitstring I get a different bitstring. I realized this after checking and finding out that the bitstring after turning the key back to binary is shorter than the bitstring used to make the key.
##imports##################################################
from socket import *
import random
##functions################################################
def CCipher(message, k):
output = ""
for x in message:
i = ord(x)
i = (i+k)%128
output += chr(i)
return output
def toBinary(message):
output = ""
for x in message:
i = bin(ord(x))[2:]
output += i
return output
def XOR(bitstring1, bitstring2):
output = ""
if(len(bitstring1) != len(bitstring2)):
print("Use bitstrings of the same length")
return None
for x in range(len(bitstring1)):
if(bitstring1[x] == "1" and bitstring2[x] == "0"):
output += "1"
elif(bitstring1[x] == "0" and bitstring2[x] == "1"):
output += "1"
else:
output += "0"
return output
def randomBinary(k):
output = ""
for x in range(k):
i = random.randint(0,1)
output = output + str(i)
return output
def toString(message):
output = ""
i = ""
n = 0
for x in message:
n += 1
i += x
if(n == 7):
output += chr(int(i,2))
n = 0
i = ""
return output
##server stuff#########################################
serverName = "OmariPC"
serverPort = 12347
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
##files################################################
nowar = open("NoWar.dat",'r')
trump = open("Trump.dat","w")
##encryption###########################################
message = nowar.read()
mesBin = toBinary(message)
bkey = randomBinary(len(mesBin))
encrypted = XOR(mesBin, bkey)
encrypted = toString(encrypted)
key = toString(bkey)
trump.write(encrypted)
trump.close()
enKey = CCipher(key, 4)
##sending###############################################
clientSocket.send(enKey.encode())
print(len(enKey))
clientSocket.send(encrypted.encode())
print(len(encrypted))
##testing###############################################
if key == toString(bkey):
print(True)
else:
print(False)
if len(toBinary(key)) == len(bkey):
print(True)
else:
print(False)
output:
168
168
True
False
def toBinary(message):
output = ""
for x in message:
i = bin(ord(x))[2:]
output += i
return output
bin(ord(x)) generates strings of variable length. For example:
>>> bin(ord(' '))
0b100000
>>> bin(ord('a'))
0b1100001
You concatenate all of the results of bin() together, so there's no way to separate them later. Meanwhile, your toString() function reads exactly 7 "bits" at a time.
You could make bin() append chunks of a fixed-size instead:
# Pad the left with 0s to always generate a string of length 7.
# (Assumes that all input characters are ASCII.)
assert(ord(x) < 128)
bin(ord(x))[2:].rjust(7, '0')
Here is my code
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return str(code)
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(codeLength)
print("The code is " + code)
convCode = code[0] + code[1] + code[2] + code[3]
print(convCode)
So I basically want to generate a random string from the letters I have provided and then check if the user guesses a correct entry in that string (I'm trying to make mastermind). The issue I have is checking to see if the user's guess is in the code which is generated.
This is what my code outputs:
Why is my convCode variable printing ['E' and not EAFB?
If the code is returned as a list instead of a string, you can access the individual letters of the code in the manner you want to.
import random
codeLength=4
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(codeLength)
print("The code is " + str(code))
convCode = code[0] + code[1] + code[2] + code[3]
print(convCode)
In your gen_code function you convert the list to a string before you return it:
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
# This converts it to a string, rather than leaving it as a list
# which is presumably what you want.
return str(code)
So later in your code:
convCode = code[0] + code[1] + code[2] + code[3]
Gives you the first four characters of that string which are exactly ['E'
Try changing gen_code to this:
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
code is a list use slicing to get the required result which will give you flexibility as you need not write hardcoded list indices each time.
import random
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(5)
print("The code is " + str(code))
convCode =code[:4]
print(convCode)
So i wrote this code and it passes the first test case, and fails all the rest. However, I can't seem to find an input that breaks it. Maybe it's because I've been staring at the code too long, but i would appreciate any help.
The algorithm uses two priority queues for the smallest and largest halves of the current list. Here's the code:
#!/bin/python
import heapq
def fix(minset, maxset):
if len(maxset) > len(minset):
item = heapq.heappop(maxset)
heapq.heappush(minset, -item)
elif len(minset) > (len(maxset) + 1):
item = heapq.heappop(minset)
heapq.heappush(maxset, -item)
N = int(raw_input())
s = []
x = []
for i in range(0, N):
tmp = raw_input()
a, b = [xx for xx in tmp.split(' ')]
s.append(a)
x.append(int(b))
minset = []
maxset = []
for i in range(0, N):
wrong = False
if s[i] == "a":
if len(minset) == 0:
heapq.heappush(minset,-x[i])
else:
if x[i] > minset[0]:
heapq.heappush(maxset, x[i])
else:
heapq.heappush(minset, -x[i])
fix(minset, maxset)
elif s[i] == "r":
if -x[i] in minset:
minset.remove(-x[i])
heapq.heapify(minset)
elif x[i] in maxset:
maxset.remove(x[i])
heapq.heapify(maxset)
else:
wrong = True
fix(minset, maxset)
if len(minset) == 0 and len(maxset) == 0:
wrong = True
if wrong == False:
#Calculate median
if len(minset) > len(maxset):
item = - minset[0]
print int(item)
else:
item = ((-float(minset[0])) + float(maxset[0])) / 2
if item.is_integer():
print int(item)
continue
out = str(item)
out.rstrip('0')
print out
else:
print "Wrong!"
Your original was not so legible, so first I made it object-oriented:
MedianHeapq supports methods rebalance(), add(), remove(), size(), median(). We seriously want to hide the members minset,maxset from the client code, for all sorts of sensible reasons: prevent client from swapping them, modifying them etc. If client needs to see them you just write an accessor.
We also added a __str__() method which we will use to debug visually and make your life easier.
Also added legibility changes to avoid the indexing with [i] everywhere, rename s,x arrays to op,val, add prompts on the raw_input(), reject invalid ops at the input stage.
Your actual computation of the median confuses me (when do you want float and when integer? the rstrip('0') is a bit wack), so I rewrote it, change that if you want something else.
A discussion of the algorithm is here.
Now it is legible and self-contained. Also makes it testable.
You might be making sign errors in your code, I don't know, I'll look at that later.
Next we will want to automate it by writing some PyUnit testcases. doctest is also a possibility. TBC.
Ok I think I see a bug in the sloppiness about locating the median. Remember the minset and maxset can have a size mismatch of +/-1. So take more care about precisely where the median is located.
#!/bin/python
import heapq
class MedianHeapq(object):
def __init__(self):
self.minset = []
self.maxset = []
def rebalance(self):
size_imbalance = len(self.maxset) - len(self.minset)
if len(self.maxset) > len(self.minset):
#if size_imbalance > 0:
item = heapq.heappop(self.maxset)
heapq.heappush(self.minset, -item)
#elif size_imbalance < -1:
elif len(self.minset) > (len(self.maxset) + 1):
item = heapq.heappop(self.minset)
heapq.heappush(self.maxset, -item)
def add(self, value, verbose=False):
if len(self.minset) == 0:
heapq.heappush(self.minset,-value)
else:
if value > self.minset[0]:
heapq.heappush(self.maxset, value)
else:
heapq.heappush(self.minset, -value)
self.rebalance()
if verbose: print self.__str__()
return False
def remove(self,value,verbose=False):
wrong = False
if -value in self.minset:
minset.remove(-value)
heapq.heapify(self.minset)
elif value in maxset:
maxset.remove(value)
heapq.heapify(self.maxset)
else:
wrong = True
self.rebalance()
if verbose: print self.__str__()
return wrong
def size(self):
return len(self.minset)+len(self.maxset)
def median(self):
if len(self.minset) > len(self.maxset):
item = - self.minset[0]
return int(item)
else:
item = (-self.minset[0] + self.maxset[0]) / 2.0
# Can't understand the intent of your code here: int, string or float?
if item.is_integer():
return int(item)
# continue # intent???
else:
return item
# The intent of this vv seems to be round floats and return '%.1f' % item ??
#out = str(item)
#out.rstrip('0') # why can't you just int()? or // operator?
#return out
def __str__(self):
return 'Median: %s Minset:%s Maxset:%s' % (self.median(), self.minset,self.maxset)
# Read size and elements from stdin
N = int(raw_input('Size of heap? '))
op = []
val = []
while(len(val)<N):
tmp = raw_input('a/r value : ')
op_, val_ = tmp.split(' ')
if op_ not in ['a','r']: # reject invalid ops
print 'First argument (operation) must be a:Add or r:Remove! '
continue
op.append(op_)
val.append(int(val_))
mhq = MedianHeapq()
for op_,val_ in zip(op,val): # use zip to avoid indexing with [i] everywhere
wrong = False
if op_ == 'a':
wrong = mhq.add(val_)
elif op_ == 'r':
wrong = mhq.remove(val_)
assert (mhq.size()>0), 'Heap has zero size!'
assert (not wrong), 'Heap structure is wrong!'
if not wrong:
print mhq.__str__()