-2

In my quest for a single header encryption library for c++ I found this github repo that uses AES with CBC mode to encrypt a std::string into a vector of unsigned char in the example provided in the repo this

    const unsigned char iv[16] = {
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
        0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
    };

initialization vector was used, now the encrypted data is ready to be sent to the api with the endpoint /data that accepts data in JSON format

{"data":"encrypted-data"}

and decryptes it for later use

the server where the data is sent is written in python and uses the following lines to decrypt the data


obj2 = AES.new('EncryptionKey128'.encode("utf8"), AES.MODE_CBC, 'This is an IV456'.encode("utf8"))
result =  obj2.decrypt(phrase)
print (result)

how to convert the iv to a string to use on the server side

if tried looping over the items in

lst = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
        0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]
for item in lst:
   item = item.replace('0x','')
   bytes_object = bytes.fromhex(item)
   ascii_string = bytes_object.decode("utf-8")

but this create an iv that is larger than 16 chars

Goal behind this is to encrypt a string with AES and send it to a python server to be decrypted for the sake of this example both keys will be hardcoded in the server and the client

ahmad
  • 9
  • 5
  • 1
    the elements in the lst list are all hexadecimal values, then why do you remove 0x, comment out this line `item = item.replace('0x','')` – Anand Sowmithiran Dec 31 '21 at 11:46
  • 2
    _`item = item.replace('0x','')`_ I heavily doubt, this will work as intended. – πάντα ῥεῖ Dec 31 '21 at 11:47
  • You want to convert the unsigned char array iv into an UTF-8 string? And you want to do it in Python? The chr function creates an character out of a number. – Sebastian Dec 31 '21 at 11:49
  • @Sebastian yes i want to convert the iv array to a string – ahmad Dec 31 '21 at 11:55
  • @AnandSowmithiran I am using [this example](https://www.kite.com/python/answers/how-to-convert-a-string-from-hex-to-ascii-in-python) – ahmad Dec 31 '21 at 11:56
  • Does this answer your question? [How do I convert a list of ascii values to a string in python?](https://stackoverflow.com/questions/180606/how-do-i-convert-a-list-of-ascii-values-to-a-string-in-python) lots of ways to do it! – Sebastian Dec 31 '21 at 12:02
  • the values in your python lst are to be in single quote, without that the replace function errors out since it sees them as `int` – Anand Sowmithiran Dec 31 '21 at 12:12

1 Answers1

2

The usual approach for these cases is to convert those bytes to base64 before sending and sticking that resulting string in the JSON request. On the server side, your python code needs to decode the resulting base64 to convert it back to bytes.