pythonhashcryptographypycryptononce

Finding hash with 5 leading zeros for a string


I'm doing a hashing puzzle to understand the sha256 mechanism. Perhaps someone can help me with the code.

1- I need to find a nonce that is small, and the first 4-5 digits are 0 in hexadecimal notations.

2- Code a function that takes your name and the number of leading zeroes in the hash it should find as input

3- It should have a nonce (counter) starting from zero, that will get appended to the string before each SHA256 hashing round

4- The loop should keep hashing and incrementing the nonce until the target hash is found At the end, print the hash, final pre-image, number of attempts it took to find the hash, and total execution time in seconds

Sample Output:

Finding hash with 5 zeros for string Omar (this is descriptive).

    Found hash 00000def2d1265b4f95f556f33b97b935016d7cd92fdfd7e9208cda1e887f6b4
    Number of attemts: 2743370 
    Execution time: 7.635315895080566 seconds
    Final pre-image: Omar2743370

In so far, this is what I've come up with

y = 1
found = 0
while found == 0:
    hh = hashlib.sha256(str(y).encode()).hexdigest()
    if hh[:4] == "0000":
        found = 1
    y +=1
print(hh)
print(y)

Solution

  • Here's one way to do it:

    from hashlib import sha256
    from time import perf_counter
    
    def main(name, lz):
        attempts = 1
        prefix = '0' * lz
        while not (hash_ := sha256(f'{name}{attempts}'.encode()).hexdigest()).startswith(prefix):
            attempts += 1
        return name, hash_, attempts
    
    for lz in 4, 5:
        start = perf_counter()
        name, hash_, attempts = main('Omar', lz)
        end = perf_counter()
        print(f'Found hash: {hash_}')
        print(f'Number of attempts: {attempts}')
        print(f'Execution time: {end-start:.15f} seconds')
        print(f'Final pre-image: {name}{attempts}\n')
    

    Output:

    Found hash: 00004b8def35c72c9313253e242cdef508151dda5213efbead0386202ca38959
    Number of attempts: 18102
    Execution time: 0.018010623003647 seconds
    Final pre-image: Omar18102
    
    Found hash: 000004a5f963f6dc40afded7e20d1471649764af87f700d6b01b3976dd7623f1
    Number of attempts: 986924
    Execution time: 0.952605198996025 seconds
    Final pre-image: Omar986924