重複の可能性あり:
Python hashlib の問題「TypeError: Unicode オブジェクトはハッシュする前にエンコードする必要があります」
以下は、ソルト付きのパスワードを生成する Python 3 のコードです。
import hmac
import random
import string
import hashlib
def make_salt():
salt = ""
for i in range(5):
salt = salt + random.choice(string.ascii_letters)
return salt
def make_pw_hash(pw, salt = None):
if (salt == None):
salt = make_salt() #.encode('utf-8') - not working either
return hashlib.sha256(pw + salt).hexdigest()+","+ salt
pw = make_pw_hash('123')
print(pw)
表示されるエラーは次のとおりです:
Traceback (most recent call last):
File "C:\Users\german\test.py", line 20, in <module>
pw = make_pw_hash('123')
File "C:\Users\german\test.py", line 17, in make_pw_hash
return hashlib.sha256(pw + salt).hexdigest()+","+ salt
TypeError: Unicode-objects must be encoded before hashing
パスワードを生成するアルゴリズムを変更することは許可されていないため、おそらくメソッドを使用してエラーを修正したいだけですencode('utf-8')
。どうすればいいですか?
ベストアンサー1
pw
および文字列で既に説明したメソッドを呼び出すだけですsalt
。
pw_bytes = pw.encode('utf-8')
salt_bytes = salt.encode('utf-8')
return hashlib.sha256(pw_bytes + salt_bytes).hexdigest() + "," + salt