如何使用python中的数字对之间的短划线格式化MD5哈希?
例如,我可以生成这样的十六进制字符串:
from hashlib import md5
print md5("Testing123!").hexdigest()
这给出了这个输出:
b8f58c3067916bbfb50766aa8bddd42c
如何格式化输出:
B8-F5-8C-30-67-91-6B-BF-B5-07-66-AA-8B-DD-D4-2C
(注意:这是为了匹配ASP.NET成员资格提供程序用于在数据库中存储密码哈希的格式,因此我可以通过Python与它进行交互。)
答案 0 :(得分:4)
一个非常有趣的方法是:
>>> 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'
答案 1 :(得分:2)
使用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
答案 2 :(得分:0)
使用Split python string every nth character?中的答案,您可以执行类似
的操作hash = md5("Testing123!").hexdigest()
hash = "-".join([hash[i:i+2] for i in range(0,len(hash),2)])
答案 3 :(得分:-1)
这应该有效:
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)
产生输出:
python string.py
B8-F5-8C-30-67-91-6B-BF-B5-07-66-AA-8B-DD-D4-2C