user3479683
user3479683

Reputation: 493

Using sha256 to 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?

Upvotes: 1

Views: 6937

Answers (2)

Ray
Ray

Reputation: 223

An alternative to Martijn's solution would be to store a byte string in the var variable.

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

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121186

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.

Upvotes: 4

Related Questions