Search code examples
pythonencryptionhashsha256hashlib

Hexify sha digest result without using hashlib


I've got digest value of data in string format, and I'd like to hexify it.

Here's the sample string '\xf0z\xd8[\xfc\x7f'

However, I cannot use hashlib since I don't have the original data from which the hash was created from.

trying .digesthex() on the string wouldn't work since str object don't have that method. Is there any alternative ?


Solution

  • For each character in the original string, use ord to obtain the numeric value of the character and then use a string format operation to express that numeric value as a string containing a pair of hex digit characters. Accumulate those two-digit strings into a single string.

        mystring = '\xf0z\xd8[\xfc\x7f'
        result = ''
        for ch in mystring:
            number = ord(ch)
            hexdigits = '{:02x}'.format(number)
            result += hexdigits
        print result   
    

    You can do all of that on one line by using a list comprehension to collect the pairs of hex digit strings into a list and then using the join method with an empty separator string to glue the hex digit strings together into a single string.

        mystring = '\xf0z\xd8[\xfc\x7f'
        result   = ''.join([ '{:02x}'.format(ord(ch)) for ch in mystring ])
        print result
    

    Or instead of a list comprehension you can use map with a lambda to build the list of hex digit pairs.

        mystring = '\xf0z\xd8[\xfc\x7f'
        result   = ''.join(map(lambda ch: '{:02x}'.format(ord(ch)), mystring))
        print result
    

    The map version is harder to read but it might run slightly faster.