I'm using an online md5 generator to get the hash value of 'football'. When Python converts my input "football" at the prompt it generates a different hash. It then generates another totally different hash from the word "football" thats in my list. So no match when it compares them. I have hashed the word "football" in different online md5 generators and get the same result. Only in Python do i keep getting different results. Thanks for any help.
import hashlib
def dictionary_attack(password_hash):
dictionary = ['letmein', 'password', '12345', 'football']
password_found = None
for dictionary_value in dictionary:
temp_value = hashlib.md5('dictionary_value'.encode('utf-8'))
hashed_value = temp_value.hexdigest()
if hashed_value == password_hash:
password_found = True
recovered_password = dictionary_value
if password_found == True:
print(f'Found match for hashed value: {password_hash}')
print(f'Password recovered: {recovered_password}')
else:
print(f'password not found')
def main():
objhash = input('Enter value: ')
hashobj = hashlib.md5('objhash'.encode('utf-8'))
password_hash = hashobj.hexdigest()
dictionary_attack(password_hash)
if __name__ == '__main__':
main()
You're not computing the hash of "football". You're computing the hash of the string "dictionary_value".
Change the line
temp_value = hashlib.md5('dictionary_value'.encode('utf-8'))
in dictionary_attack to
temp_value = hashlib.md5(dictionary_value.encode('utf-8'))
Likewise, in main, change
hashobj = hashlib.md5('objhash'.encode('utf-8'))
to
hashobj = hashlib.md5(objhash.encode('utf-8'))
Related
i have a stored hash password with bcrypt library so it always stores a different hash string in my db. How can i compare a string value with the store password if they are not the same?
#login.route('/log',methods=['POST'])
def login():
error = None
# get data from JSON
body = request.get_json()
# if data contains something
if body != error:
# Verification of POST method
if request.method == 'POST':
# bucle for empty values findings
validation = all(x != "" for x in body.values())
if validation:
username_mod = body['username']
password_mod = body['password_hash']
forced = b"valentina"
hashed = hashpw(password_mod.encode('utf-8'), gensalt())
userMatch = User.query.filter_by(username=username_mod).first()
store_password = userMatch.password_hash
if checkpw(forced, hashed):
print("it matches")
else:
print("they dont")
if userMatch:
if checkpw(hashed, store_password):
pswd_match = True
else:
pswd_match = False
if userMatch and pswd_match:
return msg_handler("user allowed", 200)
else:
return msg_handler("user denied", 400)
else:
return msg_handler("missing value in 1 or more parameters", 400)
else:
return msg_handler("Must be POST method", 400)
else:
return msg_handler("no data", 400)
im attaching my debug
It looks to me like you're generating a new salt every time you hash the password. The salt is a randomly-generated value that gets attached to the password before it gets hashed.
If you and I both choose abc123 as our passwords, then the hashes of our passwords will be the same too. If someone finds out my password is abc123, and they see that your hash is the same, then they'll know your password too. Now say that my password is abc123 but when it gets hashed, it sticks a few random bytes at the beginning, say 7c6. It then stores both my salt, 7c6, and the hash of 7c6abc123. You still use abc123 as your password, but it randomly generates 9er as the salt for you. It then stores 9er as your salt, and the hash of 9erabc123. Now our hashes look different, even though our passwords are the same.
Note that the salt is stored unencrypted. That's so you can enter your password, it can stick the salt on the front of it, then hash the salt + password combo. That hash is what needs to get compared to the stored hash. If you generate a new salt every time, the hash is going to be different every time.
So, this part:
hashed = hashpw(password_mod.encode('utf-8'), gensalt())
should not generate a new salt. It needs to re-use the salt that was used (and stored) previously.
i solve my problem using werkzeug.security
now my code is like this:
from werkzeug.security import generate_password_hash, check_password_hash
username_mod = body['username']
password_mod = body['password_hash']
userMatch = User.query.filter_by(username=username_mod).first()
store_password = userMatch.password_hash
if userMatch:
if check_password_hash(store_password, password_mod ):
pswd_match = True
else:
pswd_match = False
if userMatch and pswd_match:
return msg_handler("user allowed", 200)
else:
return msg_handler("user denied", 400)
I'm new to python, currently taking an IT as a master's degree. I'm working on decoding a password from a hash value.
This is how I'm currently set up. I know it's wrong and any help would be greatly appreciated.
import itertools
import time
from Crypto.Hash import SHA3_512
# Function to brute force the password
def tryPassword(passwordSet):
start = time.time()
# Allowed characters in the password
chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!##$%^&*()_-+=[{]}|:;'\",<.>/?"
attempts = 0
for value in range(1, 9):
# Build up a string to test against, character by character
for letter in itertools.product(chars, repeat=value):
attempts += 1
letter = ''.join(letter)
hash_object = SHA3_512.new()
hash_object.update((letter).encode("utf-8"))
tmp_hash = hash_object.hexdigest()
print(tmp_hash)
#if the string we are building matches the password given to us, return from the function
if tmp_hash == passwordSet:
end = time.time()
distance = end - start
return (attempts, distance)
password = input("Password >")
tries, timeAmount, = tryPassword(password)
print("The password %s was cracked in %s tries and %s seconds!" % (password, tries, timeAmount))
Since the purpose is to crack a hashed password, that's what should be the parameter to the function, not a plain-text password.
Then in the loop it needs to hash each candidate password, and compare the hash to the input.
import itertools
import time
from Crypto.Hash import SHA3_512
def hash_password(password):
hash_object = SHA3_512.new()
hash_object.update(password.encode("utf-8"))
return hash_object.hexdigest()
def tryPassword(hashed_pass):
start = time.time()
# Allowed characters in the password
chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!##$%^&*()_-+=[{]}|:;'\",<.>/?"
attempts = 0
for value in range(1, 9):
# Build up a string to test against, character by character
for letter in itertools.product(chars, repeat=value):
attempts += 1
candidate = ''.join(letter)
#if the string we are building matches the password given to us, return from the function
if hash_password(candidate) == hashed_pass:
end = time.time()
distance = end - start
return (attempts, distance, password)
password = input("Password > ")
tmp_hash = hash_password(password)
tries, timeAmount, found_password = tryPassword(tmp_hash)
print("The password %s was cracked in %s tries and %s seconds!" % (found_password, tries, timeAmount))
This is my code which and it asks a user to enter a password string and checks for any repeated elements.The thing is I didn't understand the code and why they set a unique_element to an empty string.And what does unique+=password[i] do,why is i in [] in this brackets?
def check_pass():
password= raw_input('Enter a password:')
unique_element = ''
for i in range (len(password)):
if len(unique_element) == 0:
unique_element += password [i]
else:
not_unique = True
for j in range (len(unique_element)):
if unique_element[j] == password[i]:
not_unique = False
if not_unique:
unique_element += password[i]
return unique_element == password
print check_pass()
Explaining the Code above may be a little tedious. Suffice it to say that if your intention is to check if a given String [password] contains any duplicate character, you might do that without the need for any loops - which (in this case) is likely unnecessary. Here's how:
def pass_has_unique_characters():
# CAPTURE THE ENTERED CHARACTERS
password = input('Enter a password:')
# SETS CANNOT HAVE DUPLICATES SO WE CAST THE STRING (password) TO A SET
st_password = set(password)
# NOW WE CHECK THE LENGTHS OF BOTH: password AND st_password
# IF BOTH HAVE THE SAME LENGTH, THEN THE PASS HAS UNIQUE CHARACTERS,
# RETURN [True] ... OTHERWISE RETURN [False]
return (True if len(st_password) == len(password) else False)
print(pass_has_unique_characters())
I'm working on a basic Python 3 authentication system with passwords and optional usernames. Here's the segment I have:
import hashlib
import os.path
from secure import BadCharacterError
def setLayers(filePath, passwords, usernames=None):
# sanity check
if os.path.exists(filePath): raise FileExistsError
if usernames is not None and len(usernames) != len(passwords): raise IndexError
for name in usernames:
if "|" in name: raise BadCharacterError("Username contained bad character '|'!")
# Hash the passwords
counter = 0
for password in passwords:
salt = ""
if usernames is not None: salt = hashlib.sha512(usernames[counter].encode()).hexdigest() # generate a salt
hashedPassword = hashlib.sha512(salt.encode() + password.encode()).hexdigest() # hash them together
passwords[counter] = hashedPassword # replace the list entry
counter += 1
# write them to a file
with open(filePath, "a+") as file:
counter = 0
for password in passwords:
if usernames is None:
file.write(password)
else:
file.write(password + "|" + usernames[counter] + "\n")
counter += 1
def checkLayer(filePath, password, username=None):
# sanity check
if not os.path.exists(filePath): raise FileNotFoundError
# find the password hash
salt = ""
if username is not None: salt = hashlib.sha512(username.encode()).hexdigest() # find the salt
hashedPassword = hashlib.sha512(salt.encode() + password.encode()).hexdigest() # hash them together
with open(filePath, "r") as file:
db = file.read().split("\n")
counter = 0
if username is not None:
for entry in db:
entry = entry.split("|")
dbPassword = entry[0]
dbUsername = entry[1]
if dbPassword == hashedPassword and dbUsername == username:
return counter
counter += 1
elif username is None:
for entry in db:
if hashedPassword == entry:
return counter
counter += 1
return False # we will only reach this point if all of the others were not matched
I have a test program that will run first setLayers() and then checkLayer with appropriate parameters that should cause a match in checkLayer(). However, it always returns False (instead of a number, which would happen if there was a match).
Debugging to find the comparisons being made shows this:
ae7d239aca090e393d5a70620130746ea3f8decc131318739df7097741f2b9ad9fe3679cc1f48a9bd1649f2c3e7c9c279adae116511e7397d0ec16ef59803ec9 User1
76a92b70d005bf3d7ae31e7506df098ca0bf00c0f701a54de84f23a11095ca9832b00cd9ae4ce02867600c8e5e2a144ecfce059c22e9ea2070bf80883c6616db User2
0838b3c1856b32c2b84c6ab1b1770935588d348123c8439d9546f0829a7cd52a8696f927fbf0ae5b1dbc4be0e15e1da3b3e240974db7b6954f30b87acadccc42 User2
76a92b70d005bf3d7ae31e7506df098ca0bf00c0f701a54de84f23a11095ca9832b00cd9ae4ce02867600c8e5e2a144ecfce059c22e9ea2070bf80883c6616db User2
703bce701812f2cd00476c455d9d56df21b1e8f7c3dab5cef2e50e407f6b06733f1d771a60162d4380320cc498e3dc6143dd94bec31377086c526d8fbd3ec9ac User3
76a92b70d005bf3d7ae31e7506df098ca0bf00c0f701a54de84f23a11095ca9832b00cd9ae4ce02867600c8e5e2a144ecfce059c22e9ea2070bf80883c6616db User2
Each group of two lines is separated by a line. The first line in the group is the stored password/username set, while the second is the one entered into checkLine(). The second group from the top should have matching hashes.
Why is this not the case, and how can I solve it?
Thanks.
I am trying to create a loop that compares strings from a list I have already created. The list is of passwords, and the same passwords hashed with md5. I have a function that does the hashing, and another that prints out the list of both passwords. The new function "findmd5" is supposed to compare each md5 encrypted value of the password list with the encrypted string that is passed in. "pass2check" is a predetermined string that I am trying to use in the loop, its md5 value should return the password "football". The code in my new function is very incomplete because I am lost on the next steps to take..
import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]
def makemd5(key_string):
new_key_string = key_string.encode('utf-8')
return (hashlib.md5 ( new_key_string ).hexdigest())
def createmd5list(passwordlist):
for passlist in passwordlist:
hashlist = makemd5(passlist)
print (passlist,",",hashlist)
def findmd5(pass2check):
for line in open(passwordlist + hashlist):
if pass2check in line:
print(True)
else:
print(False)
def main():
pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
main ()
you can try this ():
import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]
def listOfHashs():
return [hashlib.md5(item.encode('utf-8')).hexdigest() for item in passwordlist]
def main():
pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
index = listOfHashs().index(pass2check)
print(passwordlist[index] if index >= 0 else "Hash not found !")
main()
in this version i've tried to modify your code:
import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]
def makemd5(key_string):
new_key_string = key_string.encode('utf-8')
return (hashlib.md5 ( new_key_string ).hexdigest())
def createmd5list(passwordlist):
hashlist = []
for passlist in passwordlist:
hashlist += [makemd5(passlist)]
return hashlist
def findmd5(pass2check):
for index, line in enumerate(createmd5list(passwordlist)):
if pass2check in line:
return index
return -1
def main():
pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
index = findmd5(pass2check)
if index >= 0:
print passwordlist[index]
else:
print "Hash not found !"
main()
You do not need to create the list of hashed passwords. Instead, you build the digest and filter inside the list comprehension and the final list only contains the valid solutions.
Reworking your own code, it could look like
import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]
def findmd5(pass2check):
result = [password for password in passwordlist
if hashlib.md5(password).hexdigest() == pass2check
]
if len(result):
print("The answer is")
for password in result:
print(password)
else:
print("Password not found")
def main():
pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
findmd5(pass2check)
main ()
This will print all the valid solutions