How can I create a simple python brute force function? - python-3.x

I am trying to create a function that will use brute force for an academic python project. The password can be limited I want to pass in the password and the function iterate through a set of characters(a-z,A-Z,0-9) trying combinations till the password is found. I know this will be inefficient so for testing lets assume the password is 4 characters long. Any help getting started on writing this function would be appreciated.

gen = itertools.combinations_with_replacement(characters,password_length) #1
for password in gen: #2
check_password(password) #3
here's how it works:
line 1: this creates a generator. it's like a function that remembers where it left off. Check this out for more info: http://getpython3.com/diveintopython3/generators.html. This particular generator goes through all possible combinations of the given characters of the given length.
line 2: for each iteration of the for loop next(gen) is called. This yields the next value
line 3: Do what you need to do
for example if characters = '01234567890' and password_length = 2 then the loop will run through the combinations: ('0','0'), ('0','1'), ('0','2')...('0','9'),('1','0'),('1','1')...('9','9').

For a pre-known length :
import random
a_z = "abcdefghijklmnopqrstuvwxyz_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while password != curtry:
currenttry = random.choice(a_z)+random.choice(a_z)+random.choice(a_z)+random.choice(a_z)
For a random length :
import random
a_z = "abcdefghijklmnopqrstuvwxyz_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while password != curtry:
leng = random.randint(4,12) #random int between 4 and 12
i = 0
curtry = "lol"
for i<leng:
curtry += random.choice(a_z)

Related

Python bitcoin miner not letting me define variable after mine

I have been trying to create a python bitcoin miner, that ACTUALLY puts the coins somewhere, so thats the first part of my quesiton, and the second part is how do I fix this error?
This is all of my code:
import hashlib
import time
max_nonce = 2 ** 32 # 4 billion
def proof_of_work(header, difficulty_bits):
# calculate the difficulty target
target = 2 ** (256-difficulty_bits)
for nonce in range(max_nonce):
hash_result = hashlib.sha256(str(header)+str(nonce)).hexdigest()
# check if this is a valid result, below the target
if int(hash_result, 16) < target:
print ("Success with nonce %d" % nonce)
print ("Hash is %s" % hash_result)
return (hash_result,nonce)
print ("Failed after %d (max_nonce) tries" % nonce)
return nonce
if __name__ == '__main__':
nonce = 0
hash_result = ''
# difficulty from 0 to 31 bits
for difficulty_bits in range(32):
difficulty = 2 ** difficulty_bits
print ("Difficulty: %ld (%d bits)" % (difficulty, difficulty_bits))
print ("Starting search...")
# checkpoint the current time
start_time = time.time()
# make a new block which includes the hash from the previous block
# we fake a block of transactions - just a string
new_block = 'test block with transactions' + hash_result
# find a valid nonce for the new block
(hash_result, nonce) = proof_of_work((new_block, difficulty_bits).hexdigest()
# checkpoint how long it took to find a result
end_time = time.time()
The line above this, The end_time seems to get an error, with no definition to what the error is. Please help.
Please note that I have tried a great deal of commenting out a bunch of things, changing code, and this is in python 3
I'm writing this as an answer because of the many issues.
First, hashllib requires byte strings. You would need
hash_result = hashlib.sha256((header+str(nonce)).encode('utf-8')).hexdigest()
Second, you're doing proof_of_work(...).hexdigest(), but that function isn't returning a hash object. You are already calling hexdigest. Your function either returns a 2-tuple, or a nonce. You want to remove the hexdigest call:
# find a valid nonce for the new block
(hash_result, nonce) = proof_of_work((new_block, difficulty_bits)
And, in the final line of proof_of_work change
return nonce
to
return (None, nonce)
Next, you are converting the nonce to decimal digits to tack it on to the block. That is completely wrong. The nonce needs to be a 4-byte value. Something like:
enonce = struct.pack('I', nonce)
hash_result = hashlib.sha256(header.encode('utf-8')+enonce).hexdigest()
Finally, this whole thing is silly. Have you timed that inner loop to see how long it takes? On my box, it takes about 500 microseconds per loop. To run that 4 billion times would require a month and a half. To repeat that for all 32 difficult values would make it take 4 years.

Beginner in Python - Password Generator with Condtionals not breaking while loop

I created a random password generator. With this generator is pulls from a variable of upper/lower case letters, numbers, and symbols and generates a random password.
The issue I'm having is I want to have a condition of 8 or more characters and if you don't request a long enough password it pops a message stating that it has to be at least 8 characters. The original creation of the generator would stop the code there and you would have to start all over. What I'm trying to do is use a while loop to ask the length again.
The issue I have come across is that my code is stuck in an infinite loop and will not break. When I do add a break I either get an error saying its out of a function or it just stops the code on input.
import random
chars ="AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890!##$%^&*"
length = input('How long would you like the password? ')
length = int(length)
if length < 8:
print('Password must be at least 8 characters')
while True:
length = input('How long would you like your password?')
length = int(length)
break
if length >= 8:
num = input('How many passwords do you want?')
num = int(num)
for p in range(number_of_pass):
password = 'Your password is: '
for c in range(length):
password += random.choice(chars)
print(password)

Stuck on Cryptopals Crypto Challenge 3 set 1

I'm failry new to cryptography and programming as a whole ( mabey a few months) and i started the cryptopal challenges. I got the first 2 done correctly with alot of reading into how to convert things in python.
I'm getting stuck on the code for the 3rd one, "Single-Byte XOR" where they give you a hex string and tell you to write a program to find the key they used to XOR the string.
I am aware of how i would go about doing this (without looking solutions):
1) convert the string to binary
2) loop through all character values XORing them individually with the given ciphertext
3) checking these XORd results to see which one looks "the most english"
I guess im just confused on the way bytes behave in python.
here is my code:
my_ciphertext = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
binary_rep_of_ciphertext = binascii.unhexlify(my_ciphertext)
array_of_ciphertext = bytearray(binary_rep_of_ciphertext)
def xor_string_and_char(my_char_value):
result = array_of_ciphertext ^ my_char_value
return '{:x}'.format(result) # convert back to hexadecimal
x = 0
assert x==0
while x in range(255):
my_plaintext = xor_string_and_char(x)
print('b' + my_plaintext)
x=x+1

Looking to check if part of a user input can be in a range of integers

I'm fairly new to Python,
I'm trying to check if the user input can be checked in a range of integers
The following is the code I have already written
#LL DD LLL
#where L is a letter
#where D is a digit
#eg SG 61 ABC
area_codes = ["SG", "PV", "LJ", "EX"]
reg = input("Enter registration: ")
if reg[0:2] in area_codes:
print(reg[0:2])
if reg[2:3] in range(0,18):
print(reg[2:3])
else:
print("nope")
And this is the response I am given,
Enter registration: SG15
SG
nope
How do I check this properly?
I have tried a few things but I don't even know if this is possible.
Thank you in advance,
Donberry.
reg[2:3] is a slice of your input string. So it's a number, but stored as string.
When you do:
if reg[2:3] in range(0,18):
you're checking if the string in contained in the range object (python 3) or list object (python 2) which contains integers. So the test fails every time.
Had you done
if 0 <= reg[2:3] < 18:
you'd have gotten an explicit error in python 3. Besides, it avoids to build a range or list object just for the sake of testing. Chained comparison like this is way faster.
So I'm suggesting:
if 0 <= int(reg[2:3]) < 18:
You should convert the string to an integer before checking it's in the range. Also, (and I don't know if you did this), but you should verify that you want numbers between 0 and 17, which is what your code does.
That is, range(0, 18) - equivalent to range(18), by the way - generates the list of numbers starting at 0 and ending at 17, including both 0 and 17.
Anyway, you would check it like this:
if int(reg[2:3]) in range(0,18):
print(reg[2:3])

Brute Force Hacker Concept in Python 3

The code that i currently have will list all possible combinations
from itertools import product
password = "hr"
chars = 'abcdefghijklmnopqrstuvwxyz' #characters to look for, can have letters added
for length in range(1, 3): #only do lengths of 1 + 2 - namely from aa - zz not onto aaa
to_attempt = product(chars, repeat=length)
for attempt in to_attempt:
print(''.join(attempt))
What i need it to do is take each tried attempt and compare it with the variable "password", if it matches break out of the for loop else carry on, any ideas?
One thing you could do to solve this would be to move your whole for length in range code block into a function:
def brute_force(chars, password):
for length in range(1, 3): #only do lengths of 1 + 2 - namely from aa - zz not onto aaa
to_attempt = product(chars, repeat=length)
for attempt in to_attempt:
if ''.join(attempt) == password:
print("Found the password!")
return
The problem you're having is that you can only break out of a single loop. There's no built-in solution to say "break out of this loop, and its parent, and nothing else." I find that if you're unable to be using break or continue to move your control flow in the desired direction, just break it off into a function and use return.
This isn't really a problem, necessarily, but chars you're using right now will only ever be able to brute-force an all-letters, all-lower-case string, so it'll go through every single attempt and fail if the password is "Hr".

Resources