Search code examples
pythonhashgenerate

Is the code correct to discover x while using the hash?


I am writing a basic code using python to find what x is with the given hash. However, it is not printing out x when I run it which I believe is because there is not a number in the range 000000-1000000 with the rest of the string to get the hash. I am already given half of the string along with the hash, and x is supposedly only containing integers and must be at least 6 characters long.

import hashlib
for x in range(000000, 1000000):
    line = "user,{x},200981".format(x=x)
    num = hashlib.sha256(line.encode()).hexdigest()
    if (num == "ba520f71e8f8f640423b1f1d4ecea68c81e6ec8c492c2273da348a48e4f407fa"):
        print(x)
        break

Is the way I am conducting the x to be a string incorrect or my result for num? I'm new to python so i'm still learning as I go!


Solution

  • The x you are looking for is apparently not in the range 000000 - 1000000.

    It is 18273349.

    >>> from itertools import count
    >>> for x in count():
    ...   line = "user,{x},200981".format(x=x)
    ...   num = hashlib.sha256(line.encode()).hexdigest()
    ...   if (num == "ba520f71e8f8f640423b1f1d4ecea68c81e6ec8c492c2273da348a48e4f407fa"):
    ...      print(x)
    ...      break
    ... 
    18273349
    
    

    Here, instead of a fixed range, I used itertools.count to count to infinity until x is found.

    >>> line = "user,{x},200981".format(x=18273349)
    >>> num = hashlib.sha256(line.encode()).hexdigest()
    >>> num
    'ba520f71e8f8f640423b1f1d4ecea68c81e6ec8c492c2273da348a48e4f407fa'