Home > Software engineering >  Convert a byte string to hexadecimal string in python
Convert a byte string to hexadecimal string in python

Time:12-20

I'm working on a project with heavy usage of AWS Signature. Now my task is to find a way to send an SHA256-hashed byte "string" to a client via JSON. The given "string" looks like this:

b'\xd2\x99Q\xb5^\x89\x99\xc3\xa7\\\x98.\x00\x87\xaf`|E\xd2\xc9:B)\xc5\xfe\x869X\xd1\xc5K\xb4'

Yes, I am using python. That "string" is a product of encoding a byte string to utf-8, then hash it using SHA256. I don't even know how to call it, but I need to somehow convert it to a normal string, so I can dump it into JSON. After conversion it should look like this:

d7fd3471194dedeafcb7b5ca17daa05e01ffcafa41227fa7d3d82ec0bdeacc8f

Note that the above string is not the result of conversion, I just attached it so you guys can understand the issue better.

I have tried encoding it with base64, but I cannot decode it afterwards. To put things simply I am pretty stuck here. Any help is very much appreciated.

CodePudding user response:

What you are looking for is the .hex() method:

>>> s = b'\xd2\x99Q\xb5^\x89\x99\xc3\xa7\\\x98.\x00\x87\xaf`|E\xd2\xc9:B)\xc5\xfe\x869X\xd1\xc5K\xb4'
>>> s.hex()
'd29951b55e8999c3a75c982e0087af607c45d2c93a4229c5fe863958d1c54bb4'
  • Related