将String转换为MD5 [英] convert String to MD5
问题描述
好吧,我试图将字符串的基本转换器编写为md5
哈希码,但是当我运行程序时,却不断收到错误消息,提示:
Ok I am trying to write a basic converter of a string to md5
hash code but when I run my program I keep getting an error that say's:
Traceback (most recent call last):
File "C:\Users\Shane\Documents\Amer CISC\lab4.py", line 30, in <module>
assertEqual (computeMD5hash("The quick brown fox jumps over the lazy dog"),("9e107d9d372bb6826bd81d3542a419d6"))
File "C:\Users\Shane\Documents\Amer CISC\lab4.py", line 27, in computeMD5hash
m.update(string)
TypeError: Unicode-objects must be encoded before hashing
我的代码如下:
def computeMD5hash(string):
import hashlib
from hashlib import md5
m = hashlib.md5()
m.update((string))
md5string=m.digest()
return md5string
推荐答案
错误提示,您的string
必须是unicode,并且必须对其进行编码.查看您所做的呼叫(从堆栈跟踪中):
As the error suggests, your string
must be unicode and you have to encode it. Looking at the call you make (from your stack trace):
computeMD5hash("The quick brown fox jumps over the lazy dog")
您似乎必须运行Python 3,其中字符串是unicode对象.要将其编码为可以由hashlib处理的字节表示形式,请更改此
it looks like you must be running Python 3 where strings are unicode objects. To encode to a byte representation which can then be processed by the hashlib, change this
m.update((string))
对此(如果utf-8是适合您使用的编码-这取决于您将如何使用此编码):
to this (if utf-8 is an appropriate encoding for you to use - it depends how you will be using this):
m.update(string.encode('utf-8'))
如果这一切对您来说都是新闻,那么您可能应该阅读优秀的 Python 3 Unicode HOWTO .
If this is all news to you, you should probably read the excellent Python 3 Unicode HOWTO.
此外,当我在这里时,您的代码还有其他一些问题
Also, while I'm here, your code has some other issues
- 一些不必要的位-不需要
from hashlib import
行或临时md5string
. - 从函数内部导入模块是一种不好的形式,因此
import hashlib
应移至模块范围. - 该函数返回
digest()
这是原始二进制文件,并且从堆栈跟踪中看起来就像您期望的
- some unecessary bits - no need for the
from hashlib import
line or the temporarymd5string
. - it's bad form to import modules from within a function, so
import hashlib
should be moved to module scope. - the function is returning the
digest()
which is raw binary, and from your stack trace it looks like you're expecting thehexdigest()
instead which is the same thing represented as a hexadecimal string.
要修复和整理所有内容,请尝试以下操作:
To fix and tidy it all up, try this:
import hashlib
def computeMD5hash(my_string):
m = hashlib.md5()
m.update(my_string.encode('utf-8'))
return m.hexdigest()
这篇关于将String转换为MD5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!