Question

How do I format an MD5 hash with dashes between pairs of digits in python?

For example, I can generate a hex string like this:

from hashlib import md5
print md5("Testing123!").hexdigest()

Which gives this output:

b8f58c3067916bbfb50766aa8bddd42c

How can I format the output like this:

B8-F5-8C-30-67-91-6B-BF-B5-07-66-AA-8B-DD-D4-2C

(Note: This is to match the format used by the ASP.NET Membership Provider to store password hashes in the database, so I can interface with it from Python.)

Was it helpful?

Solution

A really fun way would be to do this:

>>> x = 'b8f58c3067916bbfb50766aa8bddd42c' # your md5
>>> '-'.join(a + b for a, b in zip(x[0::2], x[1::2])).upper()
'B8-F5-8C-30-67-91-6B-BF-B5-07-66-AA-8B-DD-D4-2C'

OTHER TIPS

Use a generator:

>>> def two_chars(s):
...    while s:
...       head = s[:2]
...       s = s[2:]
...       yield head.upper()
...
>>> print "-".join(two_chars(s))
B8-F5-8C-30-67-91-6B-BF-B5-07-66-AA-8B-DD-D4-2C

Using the answer in Split python string every nth character? you could do something like

hash = md5("Testing123!").hexdigest()
hash = "-".join([hash[i:i+2] for i in range(0,len(hash),2)])

This should work:

from hashlib import md5

password = "Testing123!"

def passwordEncoder(password):
    """Return encoded password."""
    return list(md5(password).hexdigest())

def is_even(num):
    """Return whether the number num is even, skip first."""
    if not num == 0:
        return num % 2 == 0

def passwordFormatter(password):
    index = 0
    final_list = []
    while index < len(new_pass):
        letter = new_pass[index]
        if is_even(index):
            final_list.append("-")
        final_list.append(letter.upper())

        index += 1

    return "".join(final_list)

new_pass = passwordEncoder(password)
print passwordFormatter(new_pass)

Produces the output:

python string.py 
B8-F5-8C-30-67-91-6B-BF-B5-07-66-AA-8B-DD-D4-2C
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top