python salted hashes producing unexpected results using sha1 and md5 - python-3.x

I am trying to write a simple python script to hash a list of passwords and compare the resulting hashes against a list. I know that these 4 hashes match 4 of the listed passwords hashed with sha1 and salted with either md5(1), md5(2), md5(3), md5(4) or md5(5). My code prints 50 unique hashes however none of them match and I can't figure out why. Any help is appreciated.
import hashlib
possibleHashes = ["9537935389a343a4fbd831b621b00661b91a5172", "576b1b134cb89b0f8a6c4dd1698479a1151b0e63", "5d7196b530fdd24b8faaaecbaa6b08a29daa1304", "d6acda01abcfe8afd510b96c1d0a1645ea4c40b8"]
possiblePasswords = ["123456", "123456789", "qwerty", "password", "12345", "qwerty123", "1q2w3e", "12345678", "111111", "1234567890"]
hashesFound = 0
def hashPassword(saltNum, password):
password = password.encode('utf-8')
encryptedPassword = hashlib.sha1(hashlib.md5(int.to_bytes(saltNum)).digest() + password).hexdigest()
return encryptedPassword
i = 0
while (i < len(possiblePasswords)):
j = 0
print("I: ", i)
while (j < 5):
j += 1
print("J: ", j, " " + hashPassword(j, possiblePasswords[i]))
if (hashPassword(j, possiblePasswords[i]) in possibleHashes):
print(possiblePasswords[i], "\n" + hashPassword(j, possiblePasswords[i]))
i += 1
if i == 10:
print("\nHash Matches Found: ", hashesFound, "\n")
quit()
Edit:
I have tried making saltNum a string and encoding it before it's used in the md5 call however it has made no difference.

Related

Is there a way to adapt single-processed xor alghorithm to multiprocess?

def _internal_xor_operation(args):
key = args[0]
message = args[1]
key = bytes(key, "UTF-8")
repetitions = 1 + (len(message) // len(key))
key *= repetitions
key = key[:len(message)]
return bytes([b ^ k for b, k in zip(message, key)])
This is a alghorithm for XORing a message. Now, can I speed the process up bu using multiple threads?

I can't make multiple statement to check two statement

I am making a code in python to make password and save in the text file, if the user enters the same password in the file, the error code will appear. The problem is that although I made a two statement to check the password is valid and there is no same password in the text file, the statement of the one that will check text file to find same file. Can you tell me where I get mistake?
def InputString():
String = str(input("Enter your password. :"))
return String
def CheckPassword(Password):
##I declared "Index","Upper","Lower","Digit" and "Other" as Integer.
##In python, there is no data type for
##"char", so We use string instead.
##I use "variable" as boolean for checking password.
Upper = 0
Lower = 0
Digit = 0
Other = 0
variable = False
for index in range(len(Password)):
NextChar = (Password[index:index+1])
if NextChar >= "A" and NextChar <= "Z":
Upper = Upper + 1
elif NextChar >= "a" and NextChar <= "z":
Lower = Lower + 1
elif NextChar >= "0" and NextChar <= "9":
Digit = Digit + 1
else :
Other = Other + 1
if Upper > 1 and Lower >= 5 and (Digit - Other) > 0:
variable = True
else :
variable = False
return variable
def CheckThrough (Password):
FileP = open("Password.txt","r")
if FileP.mode == 'r':
contents = FileP.read()
if contents == Password:
usable = False
else :
usable = True
FileP.close()
return usable
###The main programs starts here###
print("Enter the password.")
print("You must add at least 1 upper character.")
print("5 lower character")
print("and the difference between numeric character and symbols must be more than 1.")
variable = False
usable = False
while variable == False and usable == False:
Password = InputString()
variable = CheckPassword(Password)
if variable == True:
usable = CheckThrough(Password)
if usable == True:
print("You can use the password.")
elif usable ==False :
print("The password you entered is already used.")
else :
print("The error is ocuured.")
else :
print("You can't use this password, try again.")
print("Your password is",Password)
FileP = open("Password.txt","a+")
FileP.write(Password)
FileP.write("\n")
FileP.close()
you need to add .strip() so it has no spaces e.g String = str(input("Enter your password. :").strip()). When you enter in the password there's a space but that doesn't get saved to the file thus it always reads it as a new password.
my input = Enter your password. :Kingdom1hearTs
The input into the program = " Kingdom1hearTs"
(used print to see what was being entered into the system)
and the if contents == Password: needs to be if Password in contents:otherwise your seeing if Password is the same as the whole txt file.
NextChar = (Password[index:index+1])
if NextChar >= "A" and NextChar <= "Z":
Upper = Upper + 1
elif NextChar >= "a" and NextChar <= "z": #had the wrong indentation
Lower = Lower + 1
elif NextChar >= "0" and NextChar <= "9":
Digit = Digit + 1
else :
Other = Other + 1

Decrypted image starts good but becomes gray

I am working on a personal project of mine and was wondering how I can fix my issue.
Here is a piece of code I am working on:
f = open('sample.jpeg','rb')
choice = int(input("-> "))
mutableBytes = bytearray(f.read())
f.close()
print(str(mutableBytes) + "SAMPLE")
if choice == 1:
for i in range(len(mutableBytes)):
if mutableBytes[i] < 255:
mutableBytes[i] = mutableBytes[i] + 1
f.close()
print(str(mutableBytes) + "ENCRYPTED")
f = open('samplecopy.jpeg','wb+')
f.write(mutableBytes)
else:
f = open('samplecopy.jpeg','rb')
mutableBytes = bytearray(f.read())
f.close()
for i in range(len(mutableBytes)):
if mutableBytes[i] > 0 and mutableBytes[i]<255:
mutableBytes[i] = mutableBytes[i] - 1
f = open('samplecopy.jpeg','wb+')
f.write(mutableBytes)
print(str(mutableBytes) + "Decrypted")
This should in theory get a picture and encrypt it, after decrypt it. I printed all the bytes and I looked for changes but it looks the same.
Here is the comparison: https://www.diffchecker.com/vTtzGe4O
And here is the image I get vs the original:
(the bottom one is the one I get after decrypting).

pywinauto.keyboard.KeySequenceError: `}` should be preceeded by `{`

Have the following code, it outputs the generated password to the command line (using the print command) but when I send the generated password to the password text box I get the error
pywinauto.keyboard.KeySequenceError: } should be preceeded by {
app = Application(backend="uia").connect(title = "SKF Insight Rail Manager")
app.top_window().set_focus()
password = random.choice(string.ascii_lowercase)
password += random.choice(string.punctuation)
password += random.choice(string.ascii_uppercase)
password += random.choice(string.digits)
for i in range(4):
randomSource = string.ascii_letters + string.digits + string.punctuation
password += random.choice(randomSource)
Curly brackets is a kind of escape sequence. You need to unescape them by wrapping with {}. In your case it should look so:
password = "{}}" # wrap by {} for send_keys
password += "{{}" # wrap by {} for send_keys
password += random.choice(string.digits)
password += random.choice(string.punctuation)
for i in range(4):
randomSource = string.ascii_letters + string.digits + string.punctuation
password += random.choice(randomSource)
# tricky replace is needed for human readable form of password
print("Generated password:" + password.replace('{}}', '}').replace('{{}', '{'))
time.sleep(1)
keyboard.send_keys(password)
The docs about send_keys: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html

Package functions on strings using GPU in Python - Generating addresses from private keys

Problem: I am trying to convert a very big list (many millions) of private keys (hexadecimal format, stored in a list of strings) to addresses. Can this be run on the GPU?
I have tried looking for resources on how to adapt my code to a GPU/CUDA-friendly version. However, I've found that most examples online are for pure math operations on a list of ints or floats. Also, the function where the 'processing' is defined is also entirely re-written, and does not use functions from packages (other than those already supported by numpy etc.).
Is there a way to make the [private key -> public key -> address] process GPU-friendly, and can string operations be carried out on a GPU in the first place?
The following is what I have for my serial CPU version for Python3.x:
import codecs
import hashlib
import ecdsa
def get_pub_keys(priv_key):
private_hex = codecs.decode(priv_key, 'hex')
key = ecdsa.SigningKey.from_string(private_hex, curve=ecdsa.SECP256k1).verifying_key
key_bytes = key.to_string()
key_hex = codecs.encode(key_bytes, 'hex')
public_key_uncompressed = b'04' + key_hex
key_string = key_hex.decode('utf-8')
last_byte = int(key_string[-1], 16)
half_len = len(key_hex) // 2
key_half = key_hex[:half_len]
bitcoin_byte = b'02' if last_byte % 2 == 0 else b'03'
public_key_compressed = bitcoin_byte + key_half
return public_key_uncompressed, public_key_compressed
def public_to_address(public_key):
public_key_bytes = codecs.decode(public_key, 'hex')
# Run SHA256 for the public key
sha256_bpk = hashlib.sha256(public_key_bytes)
sha256_bpk_digest = sha256_bpk.digest()
# Run ripemd160 for the SHA256
ripemd160_bpk = hashlib.new('ripemd160')
ripemd160_bpk.update(sha256_bpk_digest)
ripemd160_bpk_digest = ripemd160_bpk.digest()
ripemd160_bpk_hex = codecs.encode(ripemd160_bpk_digest, 'hex')
# Add network byte
network_byte = b'00'
network_bitcoin_public_key = network_byte + ripemd160_bpk_hex
network_bitcoin_public_key_bytes = codecs.decode(network_bitcoin_public_key, 'hex')
# Double SHA256 to get checksum
sha256_nbpk = hashlib.sha256(network_bitcoin_public_key_bytes)
sha256_nbpk_digest = sha256_nbpk.digest()
sha256_2_nbpk = hashlib.sha256(sha256_nbpk_digest)
sha256_2_nbpk_digest = sha256_2_nbpk.digest()
sha256_2_hex = codecs.encode(sha256_2_nbpk_digest, 'hex')
checksum = sha256_2_hex[:8]
# Concatenate public key and checksum to get the address
address_hex = (network_bitcoin_public_key + checksum).decode('utf-8')
wallet = base58(address_hex)
return wallet
def base58(address_hex):
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
b58_string = ''
# Get the number of leading zeros and convert hex to decimal
leading_zeros = len(address_hex) - len(address_hex.lstrip('0'))
# Convert hex to decimal
address_int = int(address_hex, 16)
# Append digits to the start of string
while address_int > 0:
digit = address_int % 58
digit_char = alphabet[digit]
b58_string = digit_char + b58_string
address_int //= 58
# Add '1' for each 2 leading zeros
ones = leading_zeros // 2
for one in range(ones):
b58_string = '1' + b58_string
return b58_string
def get_addresses(i):
key1,key2 = get_pub_keys(i)
add1 = public_to_address(key1)
add2 = public_to_address(key2)
return add1, add2
filename = 'bunchOfHexKeys.txt'
with open(filename, 'r') as f:
hexKeys = f.read().splitlines()
addresses = []
for i in hexKeys:
addresses.append(get_addresses(i))
As can be seen, I'm using many functions from the 3 imported packages. So far the only way I can see is to rewrite those. Is there another way?
The size of hexKeys isn't an issue for the GPU cache size, as I can just adjust the input list as needed.

Resources