【问题标题】:TypeError: Unicode-objects must be encoded before hashing [closed]TypeError:Unicode对象必须在散列之前进行编码[关闭]
【发布时间】:2017-08-22 20:26:00
【问题描述】:

我试图从这个网站复制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 位)。请帮助并提前致谢。

【问题讨论】:

标签: python unicode hash encode


【解决方案1】:
import hashlib

message = 'whatever'.encode()

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

print(code)

【讨论】:

    【解决方案2】:

    消息很清楚:Unicode 对象必须使用encode 编码,然后才能散列它。它指的是什么 Unicode 对象?传入散列函数hashlib.sha256,即msg

    一旦你过去了,你会发现hexdigest() 的返回已经是一个不需要str 应用于它的字符串。无论如何,你拼写错误utf-8

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

    【讨论】:

    • 非常感谢。有用! @Mark Ransom
    猜你喜欢
    • 1970-01-01
    • 2019-08-21
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多