Convert Bytestring to "normal" String Python

140 Views Asked by At

I'm generating a argon2d hash and wanted to compare it with hashstring from my database.

For hashing I use this function:

    import argon2

    argon2Hasher = argon2.hash_password_raw(b"password", b"TESTTESTTESTTEST" ,time_cost=16, memory_cost=512, parallelism=1, hash_len=16,     type=argon2.Type.D) #argon2.low_level.Type.D)
    print(argon2Hasher)

And my output is:

b'\x0c\xd1\xe3\xf0\x0f\x03<\xa0\xa99\xee\x85I\xc8\xcb\xb0'

I tried to use argon2Hasher.decode(encoding="ascii") which resulted in: UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 1: ordinal not in range(128) And I also tried the same command with encoding="utf-8" but this resulted in UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 1: invalid continuation byte

How can I convert it into plaintext (normal String)?

I'm using Python 3.6.

1

There are 1 best solutions below

2
On

While there is no way to tell for sure what encoding to use, there are some encoding that do not have invalid values, like e.g. latin1, trying that on your data yields this:

s = b'\x0c\xd1\xe3\xf0\x0f\x03<\xa0\xa99\xee\x85I\xc8\xcb\xb0'
repr(s.decode('latin1'))
# "'\\x0cÑãð\\x0f\\x03<\\xa0©9î\\x85IÈË°'"

The documentation of the codecs package, provides you with a comprehensive list of what you can specify for encoding.


However, I think you are asking yourself the wrong question. If the bytes you show are meant to represent a hash, then a conversion to str is not really desireable since, as you are experimenting yourself, this must also include an encoding for this to be "interpreted". On the contrary, bytes is bytes and no extra encoding is needed. This is the same reason that also hashlib works primarily with bytes.