将String转换为MD5

时间:2012-11-06 21:26:19

标签: python string python-3.x md5

好的我正在尝试将一个字符串的基本转换器编写为md5哈希码,但是当我运行我的程序时,我不断收到错误信息:

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

4 个答案:

答案 0 :(得分:21)

如错误所示,您的string必须是unicode,您必须对其进行编码。看看你的电话(从你的筹码追踪):

computeMD5hash("The quick brown fox jumps over the lazy dog")

看起来你必须运行Python 3,其中字符串是unicode对象。要编码为可由hashlib处理的字节表示,请更改此

m.update((string))

这个(如果utf-8是你要使用的合适编码 - 这取决于你将如何使用它):

m.update(string.encode('utf-8'))

如果这对你来说都是新闻,你应该阅读优秀的Python 3 Unicode HOWTO


此外,当我在这里时,您的代码还有其他一些问题

  • 一些不必要的位 - 不需要from hashlib import行或临时md5string
  • 从函数中导入模块是不好的形式,因此应将import hashlib移动到模块范围。
  • 该函数返回digest()这是原始二进制文件,并且从您的堆栈跟踪看起来您期望hexdigest()而不是表示为十六进制字符串的相同内容。

要修复并整理一切,请尝试以下方法:

import hashlib

def computeMD5hash(my_string):
    m = hashlib.md5()
    m.update(my_string.encode('utf-8'))
    return m.hexdigest()

答案 1 :(得分:11)

您应该对编码的字节序列进行哈希处理,而不是尝试对字符串进行哈希处理。而不是

>>> import hashlib
>>> hashlib.md5("fred")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Unicode-objects must be encoded before hashing

你应该对它进行编码,例如:

>>> "fred".encode("utf")
b'fred'
>>> hashlib.md5("fred".encode("utf")).hexdigest()
'570a90bfbf8c7eab5dc5d4e26832d5b1'

在Python 2中,你可以在不这样做的情况下逃脱,并且它导致了未被注意的错误。幸运的是,Python 3具有更好的unicode支持,并区分字节和字符串。

答案 2 :(得分:2)

似乎你必须在散列之前对字符串进行编码:

http://www.dreamincode.net/forums/topic/246026-generating-string-hash-issue/

答案 3 :(得分:-2)

!/ usr / bin / env python

编码= UTF-8

import sys,os,stat import pygtk,gtk 导入zbarpygtk 导入pycurl 从时间导入strftime,localtime 进口pango

class qrdat:

def __init__(self):

    """ VARIABLES DE CONFIGURACION """
    # Prefijo para el nombre de los archivos de registros 
    prefijo = 'Registro'

    # Lugar de almacenamiento de archivos de registros
    # Por defecto se guarda en la carpeta personal del usuario
    directorio = os.getenv('HOME')

    # Descomentar la siguiente linea y digitar la ruta de la carpeta
    # donde se guardaran los archivos

    #directorio = '/home/olpc/Escritorio'


    # Modo de reproduccion de sonido:
    # 1 : sonido enviado directamente a la tarjeta de sonido
    # 2 : sonido de alerta del sistema

    self.beep_mode = 1

    # No modificar abajo
    self.open_file = None
    self.video_device = '/dev/video0'
    self.fecha = strftime("%Y-%m-%d",localtime())
    self.filename = directorio+'/'+prefijo+'-'+self.fecha+'.csv'

    if len(sys.argv) > 1:
        self.video_device = sys.argv[1]

def decoded(self, zbar, data):
    """funcion invocada cuando un codigo es decodificado por el
    control zbar. 
    """
    datos = data.split(':')
    qrdata = datos[1]

    # guardar datos
    self.save(qrdata)        

    # sonido de recepcion
    self.beep(self.beep_mode)

    # mostrar datos
    buf = self.results.props.buffer
    end = buf.get_end_iter()
    buf.insert(end, self.hora()+' - '+qrdata+"\n")
    self.results.scroll_to_iter(end, 0)

def show(self):
    """Funcion que crea muestra la ventana principal """

    # threads *must* be properly initialized to use zbarpygtk
    gtk.gdk.threads_init()
    gtk.gdk.threads_enter()

    window = gtk.Window()
    window.set_title("Control de Asistencia QR")
    window.set_border_width(8)
    window.connect("destroy", gtk.main_quit)

    # zbar
    self.zbar = zbarpygtk.Gtk()
    self.zbar.connect("decoded-text", self.decoded)

    self.video_device = '/dev/video0'

    self.zbar.connect("notify::video-enabled", self.video_enabled)
    self.zbar.connect("notify::video-opened", self.video_opened)

    self.zbar.set_video_device(self.video_device)

    # combine combo box and buttons horizontally
    hbox = gtk.HBox(spacing=8)

    # text box for holding results
    self.results = gtk.TextView()
    self.results.set_size_request(320, 128)
    self.results.props.editable = self.results.props.cursor_visible = False
    self.results.modify_font(pango.FontDescription("monospace 12"))
    self.results.set_left_margin(4)

    # combine inputs, scanner, and results vertically
    vbox = gtk.VBox(spacing=8)
    vbox.pack_start(hbox, expand=False)
    vbox.pack_start(self.zbar)
    vbox.pack_start(self.results, expand=False)

    window.add(vbox)
    window.set_geometry_hints(self.zbar, min_width=320, min_height=240)
    window.show_all()


def run(self):
    """Funcion que inicia el funcionamiento de la ventana"""
    gtk.main()
    gtk.gdk.threads_leave()

def save(self,data):
    """ Funcion que guarda el archivo de registro """
    f = open(self.filename,'a')
    f.write(self.fecha+','+self.hora()+','+data+'\n')
    f.close()

def hora(self):
    """ Funcion que obtiene la hora local """
    return strftime("%H:%M:%S",localtime())

def beep(self, beep_mode):

    if os.access('/dev/audio', os.W_OK ) and beep_mode == 1:
        """ Genera un sonido enviado a la tarjeta de sonido"""
        frequency = 100
        amplitude = 200
        duration = 2
        sample = 8000
        half_period = int(sample/frequency/2)
        beep = chr(amplitude)*half_period+chr(0)*half_period
        beep *= int(duration*frequency)
        audio = file('/dev/audio', 'wb')
        audio.write(beep)
        audio.close()

    else:
        """ Reproduce sonido del propio sistema """
        f=open('/dev/tty','w')
        f.write(chr(7))
        f.close()


def video_enabled(self, zbar, param):
    """callback invoked when the zbar widget enables or disables
    video streaming.  updates the status button state to reflect the
    current video state
    """
    enabled = zbar.get_video_enabled()


def video_opened(self, zbar, param):
    """callback invoked when the zbar widget opens or closes a video
    device.  also called when a device is closed due to error.
    updates the status button state to reflect the current video state
    """
    opened = zbar.get_video_opened()

def video_changed(self, widget):
    """callback invoked when a new video device is selected from the
    drop-down list.  sets the new device for the zbar widget,
    which will eventually cause it to be opened and enabled
    """
    dev = self.video_list.get_active_text()
    if dev[0] == '<':
        dev = ''
    self.zbar.set_video_device(dev)

如果名称 ==&#34; 主要&#34;:

qr = qrdat()
qr.show()
qr.run()