Random hex string get 'none' when sha256 in python - python

Can you please help me to understand such a simple subject. I need to produce a serie of random hexadecimal strings for which I'm using:
import secrets
x = secrets.token_hex(32)
This gives me something like this:
d6d09acbe78c269147803b8c351214a6e5f39093ca315c47e1126360d0df5369
Which is totally fine. Now I need to pass it through a SHA256 hash for which I'm using:
h = hashlib.new('sha256')
print (h.update(x))
Getting the error:
TypeError: Unicode-objects must be encoded before hashing
I read I need to encode the string before passing the hash using .encode() obtaining a completelly weird:
b'd6d09acbe78c269147803b8c351214a6e5f39093ca315c47e1126360d0df5369'
, and a 'none' result as the hash.
Can you please tell me whats going on here.
Thanks a lot gentls.

You are trying to print the output of h.update(), which will be None as it doesnt return anything. Instead use
h.update(x.encode())
print(h.hexdigest())
to print out a hash string.

Related

Can you apply sha256 two times to a single string?

I have wrote out the function:
print(hashlib.sha256(hashlib.sha256(Encode(s))).hexdigest())
However, there seems to be the following error:
object supporting the buffer API required
I believe this is because when hashing the second time, the input is not a byte form because it has been already hashed.
How can I solve this problem and hash a single string two times?
How about this code (as suggested by james-k-polk)?
print(hashlib.sha256(hashlib.sha256(s.encode('ascii')).digest()).hexdigest())
This works if you want to do it in one line
from hashlib import sha256 as h
print(h(h("your_string".encode()).hexdigest().encode()).hexdigest())
# Gives: c94c01dafc045892773d67dabb3da8feb925e2c48e0373eab922da49f7fd269c
# Encrypted once: e10207f241d66a8c5f8202ed9fc22b94c031850dd54d8b03fdd40db4cbde5bfc

Sequential SHA 256 hashes give different outputs for the same input

I thought that this would be a fairly common and straightforward problem, but I searched and was not able to find it.
I am a novice Python user, mostly self-taught. I'm trying what I thought would be a fairly straightforward exercise: generating a hash value from an input phrase. Here is my code:
import hashlib
target = input("Give me a phrase: ").encode('utf-8')
hashed_target = hashlib.sha256(target)
print(hashed_target)
I execute this and get the prompt:
Give me a phrase:
I entered the phrase "Give me liberty or give me death!" and got the hash output 0x7f8ed43d6a80.
Just to test, I tried again with the same phrase, but got a different output: 0x7f1cc23bca80.
I thought that was strange, so I copied the original input and pasted it in, and got a third, different hash output: 0x7f358aabea80.
I'm sure there must be a simple explanation. I'm not getting any errors, and the code looks straightforward, but the hashes, while similar, are definitely different.
Can someone help?
You are directly printing an object, which returns a memory address in the __repr__ string. You need to use the hexdigest or digest methods to get the hash:
>>> import hashlib
>>> testing=hashlib.sha256(b"sha256 is much longer than 12 hex characters")
>>> testing
<sha256 HASH object # 0x7f31c1c64670>
>>> hashed_testing=testing.hexdigest()
>>> hashed_testing
'a0798cfd68c7463937acd7c08e5c157b7af29f3bbe9af3c30c9e62c10d388e80'
>>>

How to perform SHA-256 on binary values with Hashlib?

I’m using Python 2 and am attempting to performing sha256 on binary values using hashlib.
I’ve become a bit stuck as I’m quite new to it all but have cobbled together:
hashlib.sha256('0110100001100101011011000110110001101111’.decode('hex')).hexdigest()
I believe it interprets the string as hex based on substituting the hex value (‘68656c6c6f’) into the above and it returning
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
And comparing to this answer in which ‘hello’ or ‘68656c6c6f’ is used.
I think the answer lies with the decode component but I can’t find an example for binary only ‘hex’ or ‘utf-8’
Is anyone able to suggest what needs to be changed so that the function interprets as binary values instead of hex?
Here is code that does each of the data conversions you are looking for. These steps can all be combined, but are separated here so you can see each value.
import hashlib
import binascii
binstr = '0110100001100101011011000110110001101111'
hexstr = "{0:0>4X}".format(int(binstr,2)) # '68656C6C6F'
data = binascii.a2b_hex(hexstr) # 'hello'
output = hashlib.sha256(data).hexdigest()
print output
OUTPUT:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

Passing a encoded string through a decoder - Python 2.7

I have been given the string '3950716622786379081707106990440289649627095539059008641465751322761465613969175568136135330180128764700469690212693880571268104774', which has been encoded.
Also have been given a Python file which contains the function:
def bin2utf(bin_string):
utf_string = bin(bin_string)[2:]
utf_string = ('%x' % int(utf_string, 2)).decode('hex').decode('utf-8')
return utf_string
How would I go about passing the encoded string through this function in order to decode it? So far everything I have tried has not worked.
My last effort was:
from decoder import bin2utf
bin_string = ('3950716622786379081707106990440289649627095539059008641465751322761465613969175568136135330180128764700469690212693880571268104774')
bin2utf(int(bin_string))
Am assuming I've missed something, any ideas?

Python: String indices must be integers

I get this string from stdin.
{u'trades': [Custom(time=1418854520, sn=47998, timestamp=1418854517,
price=322, amount=0.269664, tid=48106793, type=u'ask',
start=1418847319, end=1418847320), Custom(time=1418854520, sn=47997,
timestamp=1418854517, price=322, amount=0.1, tid=48106794,
type=u'ask', start=1418847319, end=1418847320),
Custom(time=1418854520, sn=47996, timestamp=1418854517, price=321.596,
amount=0.011, tid=48106795, type=u'ask', start=1418847319,
end=1418847320)]}
My program fails when i try to access jsonload["trades"]. If i use jsonload[0] I only receive one character: {.
I checked it isn't a problem from get the text from stdin, but I don't know if it is a problem of format received (because i used Incursion library) or if it is a problem in my python code. I have tried many combinations about json.load/s and json.dump/s but without success.
inputdata = sys.stdin.read()
jsondump = json.dumps(inputdata)
jsonload = json.loads(jsondump)
print jsonload
print type(jsonload) # return me "<type 'unicode'>"
print repr(jsonload) # return me same but with u" ..same string.... "
for row in jsonload["trades"]: # error here: TypeError: string indices must be integers
You read input data into a string. This is then turned into a JSON encoded string by json.dumps. You then turn it back into a plain string using json.loads. You have not interpreted the original data as JSON at any point.
Try just converting the input data from json:
inputdata = sys.stdin.read()
jsonload = json.loads(inputdata)
However this will not work because you have not got valid JSON data in your snippet. It looks like serialized python code. You can check the input data using http://jsonlint.com
The use of u'trades' shows me that you have a unicode python string. The JSON equivalent would be "trades". To convert the python code you can eval it, but this is a dangerous operation if the data comes from an untrusted source.

Categories

Resources