TypeError:必须在散列之前对Unicode对象进行编码

时间:2017-08-22 20:26:00

标签: python unicode hash encode

我试图从这个网站复制python程序:http://ecomunsing.com/build-your-own-blockchain

Python程序如下:

import hashlib, json
import random

def hashMe(msg=''):
    if type(msg)!=str:
        msg = json.dumps(msg, sort_keys=True) 
    return str(hashlib.sha256(msg).hexdigest(), 'uft-8')

def makeTransaction(maxValue=3):
    sign= int(random.getrandbits(1))*2-1 
    amount = random.randint(1,maxValue)
    alicePays = sign*amount
    bobPays = -1*alicePays
    return {u'Alice':alicePays, u'Bob':bobPays}

txnBuffer = [makeTransaction() for i in range(30)]


def updateState(txn, state):
    state = state.copy() 
    for key in txn:  
        if key in state.key():
            state[key] += txn[key]
        else:
            state[key] = txn[key]
    return state

def isValidTxn(txn, state):
    if sum(txn.values()) is not 0:
        return False    
    for key in txn.keys():
        acctBalance = state[key]
    else:
        acctBalance = 0    
    if (acctBalance + txn[key]) <0:
        return False   
    return True

state = {u'Alice':50, u'Bob':50}
genesisBlockTxns = [state]
genesisBlockContents = {u'blockNumber':0,u'parentHash':None,u'txnCount':1,u'txns':genesisBlockTxns}
genesisHash = hashMe( genesisBlockContents )

错误消息是

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/simpleexample.py", line 186, in <module>
genesisHash = hashMe( genesisBlockContents )

  File "C:/simpleexample.py", line 45, in hashMe
return str(hashlib.sha256(msg).hexdigest(), 'uft-8')

TypeError: Unicode-objects must be encoded before hashing

我正在使用Python 3.6.0 | Windows 7中的Anaconda 4.3.1(32位)。请提前帮助并表示感谢。

2 个答案:

答案 0 :(得分:2)

import hashlib

message = 'whatever'.encode()

code = hashlib.sha256(message).hexdigest()

print(code)

答案 1 :(得分:2)

消息非常明确:必须先使用encode对Unicode对象进行编码,然后才能对其进行哈希处理。它指的是什么Unicode对象?传递给散列函数hashlib.sha256的那个,即msg

一旦结束,您就会发现hexdigest()的回复已经是一个不需要str的字符串。无论如何,你拼写错误utf-8

return hashlib.sha256(msg.encode('utf-8')).hexdigest()