I can't convert hex to string in Python

1.9k Views Asked by At

So I've done this code(this is just the part where it transforms the string into hex), and when I try to decrypt I get this message: Non-hexadecimal digit found

Here is string to hex code:

def password (pslen):
  alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+}{:|?><,./;'\[]"
  pw_length = pslen
  mypw = ""
  for i in range(pw_length):
    next_index = random.randrange(len(alphabet))
    mypw = mypw + alphabet[next_index]
  print ("Password: ",mypw) 
  parolaBin = bin(int.from_bytes(mypw.encode(), 'big'))
  parolaHex = hex(int(parolaBin, 2))
  return parolaHex

And here it is hex to string code

pw = binascii.unhexlify(pw)

The program reads pw from a file.

The program it's a lot bigger but this is the part that got me stuck and won't work.

The method that I used to convert string to hexadecimal worked but the hex to string didn't.

Can someone help me please?

1

There are 1 best solutions below

0
On BEST ANSWER

You are converting an integer to hex with the hex() function:

parolaHex = hex(int(parolaBin, 2))

This includes a 0x prefix, which is not a hexadecimal value. This is what binascii.unhexlify() is complaining about:

>>> import binascii
>>> binascii.unhexlify('0xff')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
binascii.Error: Non-hexadecimal digit found
>>> binascii.unhexlify('ff')
b'\xff'

Simply remove that prefix, or don't generate it in the first place by using format(integer, 'x') instead:

parolaHex = format(int(parolaBin, 2), 'x')

Your method of generating a random password in hexadecimal is... way too verbose. You could just generate random hex digits:

import string

return ''.join([random.choice(string.hexdigits) for _ in range(pwlen)])

and get the same result with less work. At any rate, converting an integer to binary notation first then converting it back to an integer:

parolaBin = bin(int.from_bytes(mypw.encode(), 'big'))
parolaHex = hex(int(parolaBin, 2))

is certainly doing nothing more than keeping your CPU warm at night. You could have gone straight to hex:

parolaHex = format(int.from_bytes(mypw.encode(), 'big'), 'x')