How to correctly do a double SHA256 hashing?

Viewed 304

This might be basic stuff, but am pretty new to coding in general.

How do you properly do a double sha256 code?

For example, for the string "abc" the correct output of the double hash should be: 4f8b42c22dd3729b519ba6f68d2da7cc5b2d606d05daed5ad5128cc03e6c6358

However, in the script I provide below, I get another output, altough I do not know where I went wrong. What am I missing in the code?

abc = 'abc'.encode("utf-8")

hashed_abc = hashlib.sha256(abc)

hashed_abc = hashlib.sha256(hashed_abc.hexdigest().encode('utf-8'))
print((hashed_abc.hexdigest()))

Thank you.

2 Answers
import hashlib
import binascii
 
def doubleSha256(hex): 
   bin = binascii.unhexlify(hex)
   hash = hashlib.sha256(bin).digest()
   hash2 = hashlib.sha256(hash).digest()
   print("Input Hex: "+str(hex,"ascii"))
   print("SHA256:\n   "+str(binascii.hexlify(hash),"ascii"))
   print("Double-SHA256:\n   "+str(binascii.hexlify(hash2),"ascii"))

You could use something like this and it works for me.

To add:

If you are having trouble passing in “abc” use this.

ascii = "abc"
hex = binascii.hexlify(bytes(ascii,"ascii"))
doubleSha256(hex)

Cryptographic hash functions are working on bytes and output bytes, too. The double SHA256 or written as SHA256D should work in this way, too.

import hashlib
import binascii
 
   
def SHA256D(data): 

   hash = hashlib.sha256(data).digest()

   #Uncomment me for testing
   #print(hashlib.sha256(data.encode('utf-8')).hexdigest() )
      
   return hashlib.sha256(hash).digest()
   
   
toHashB = "hello".encode('utf-8')

print(SHA256D(toHashB))

doublehashed = SHA256D(toHashB)

print( binascii.hexlify(doublehashed).decode('utf8'))

The double SHA256 hash of the string "hello" is given as an example on Bitcoin pages. This outputs

9595c9df90075148eb06860365df33584b75bff782a510c6cd4883a419833d50


Note that the other answer had two problems;

  1. There is an error on the string "hello" binascii.Error: Odd-length string
  2. The SHA256D executes the hex decoding and encoding. This should be outside of the SHA256D
Related