1

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.)

Daniel Fortunov
  • 43,309
  • 26
  • 81
  • 106

4 Answers4

5

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'
falsetru
  • 357,413
  • 63
  • 732
  • 636
Menno
  • 1,133
  • 9
  • 14
2

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
bgporter
  • 35,114
  • 8
  • 59
  • 65
1

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)])
Community
  • 1
  • 1
Khaelex
  • 742
  • 5
  • 15
-1

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
Steve
  • 1,423
  • 10
  • 13
  • did you actually read the question and other answers before you? – Lipis Mar 04 '14 at 14:27
  • Answered at same time. This produces proper output the OP requested so not sure why the -1? As seen in the above responses, they have a shorter code snippet which is helpful. python string.py B8-F5-8C-30-67-91-6B-BF-B5-07-66-AA-8B-DD-D4-2C – Steve Mar 04 '14 at 17:09
  • -1 because I believe that for what the OP asked you are doing way too much and as you've seen with other answers the same result can be achieved much easier.. – Lipis Mar 04 '14 at 17:33