1

I am trying to decode my 128-bit AES key in byte format to string to store it in the database. I have tried using Python built-in decode() with ascii and utf-8 codecs but I get the following errors:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 1: ordinal not in range(128)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x94 in position 2: invalid start byte

I am using cryptography.io library for its implementation.

Hashir Sarwar
  • 1,115
  • 2
  • 14
  • 28
  • 2
    What format is the key in now? What do you mean by "it is not working"? Always include what it ***is doing*** and what you ***expect it to be doing***. – schroeder Jun 25 '20 at 09:07
  • @schroeder I have updated the post. – Hashir Sarwar Jun 25 '20 at 09:12
  • 2
    You can't decode bytes to a string when the bytes don't represent a string. Ideally you'd be storing the bytes in a binary column in the database. Alternatively, encode the bytes to something like base 64 to turn them into an ASCII-safe string. – deceze Jun 25 '20 at 09:37
  • 1
    Thanks for the edit. Now you can decompose your problem further: how can you convert a byte to a string? And that is an easy thing to look up: https://stackoverflow.com/questions/606191/convert-bytes-to-a-string – schroeder Jun 25 '20 at 09:53
  • 2
    My follow up question is why you want to convert to string in the first place? You can store byte objects in databases... – schroeder Jun 25 '20 at 09:58

1 Answers1

1

Binary is often encoded in hexadecimal or base64, in order for it to be handled as text. Python's binascii module can be used to do both types of encoding, as shown below:

import random
import binascii

keybinary=random.randrange(0, pow(2,128)).to_bytes(16, byteorder='big')
print('keybinary', keybinary)

keyhex=binascii.b2a_hex(keybinary).decode("utf-8").strip()
print('keyhex', keyhex)

keyb64=binascii.b2a_base64(keybinary).decode("utf-8").strip()
print('keyb64', keyb64)

This produces:

keybinary b'b3\xfd\xa9\xfe\x11\x86op\x10\x02\x0b\x1bE\x1f\x89'
keyhex 6233fda9fe11866f7010020b1b451f89
keyb64 YjP9qf4Rhm9wEAILG0UfiQ==
mti2935
  • 11,465
  • 3
  • 29
  • 33