简体   繁体   中英

How to sha256 hash a variable in Python

I am having trouble using sha256 hash for a variable. Here is my code

var = 'password'
hashedWord = sha256(b var).hexdigest()
print(hashedWord)

I know it would be easier to do this

hashedWord = sha256(b'password').hexdigest()
print(hashedWord)

but I don't want to do it that way. Can anyone help?

You need to encode strings to bytes:

var = 'password'
hashedWord = sha256(var.encode('ascii')).hexdigest()

Pick an encoding that works for your text; UTF-8 can encode all of Unicode but that may not produce the hash signature you are looking for; this depends on what other systems think the signature is.

Martijn解决方案的替代方法是将字节字符串存储在var变量中。

var = b'password' hashedWord = sha256(var).hexdigest() print(hashedWord)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM