0

I'm using Django I want to convert text to hex and than base64

I tried to do like this:

# create text or number and convert them to integer #
txt = "ABC"
txt_to_int = int(txt,16)
print(txt_to_int)
>> 2748

# convert them to hex
txt_to_hex = hex(txt_to_int)
print(txt_to_hex)
>> 0xabc

# convert to base64
hex_encode = txt_to_hex.encode('utf-8')
hex_to_base64 = base64.b64encode(hex_encode)
base64_decode = hex_to_base64.decode("utf-8")
print(base64_decode)
>> MHhhYmM=

I am using Online Text To Hex Converter Tool I want result as:

https://string-functions.com/string-hex.aspx

after Converter : text to hex:

 (ABC) to hex (414243)

https://base64.guru/converter/encode/hex

after Converter : Hex to Base64

(414243) to base64 (QUJD)

I want to do them by django-python

any help I will appreciate

1 Answers1

0

I think it's due to hex codec and Python 3 version. You need to use .encode(). Check this out too: Python 3.1.1 string to hex

Updated:

After a few tries i was able to achieve it like this.

  • While encoding to hex, bytes like object is required so converted to bytes.
  • While encoding to base64 I had to decode it back from hex to get the correct base64 encoding.
converting to hex
txt = "ABC"
bytes_text = bytes(txt, encoding='ascii')
hex = codecs.encode(bytes_text, 'hex')
print(hex)
>> b'414243'
converting to base64
hex = codecs.decode(hex, 'hex')
base64 = codecs.encode(hex, 'base64')
print(base64)
>> b'QUJD\n'

You can read more about the codecs encode/decode here: https://docs.python.org/3/library/codecs.html?highlight=encode#codecs.Codec.encode

Faizan
  • 9
  • 4