When using base64 on a string of bytes I receive the error 'utf8' codec can not decode byte 0x86 in position 2: invalid start byte

1

I'm trying to encrypt a file through a web api that uses Flask.

First I read the bytes of the file, I put it in a json encoding with base64 and I send it in a post to the api:

with open('/root/Desktop/fichero.txt', 'rb') as outfile:
    datos = outfile.read()


headers = {'Content-type': 'application/json'}
r = requests.post("http://localhost:5000/api/encrypt", json={'file':base64.encode(datos),'alg':'aes256'}, headers=headers)

print r.content

Once in the api, I reverse the encoding process in base64 and encrypt it with the library PyCrypto . Finally, I try to return the encrypted file again in HTTP in% response%

from Crypto.Cipher import AES

@app.route('/api/encrypt_file', methods=['POST'])
def encrypt_file():

    data = request.json

    data['file'] = base64.b64decode(data['file'])    

    iv = Random.new().read(16)

    cipher = AES.new(key,AES.MODE_CBC,iv)#key es byte string de 32 bits
    fichero_enc= iv + cipher.encrypt(data['file']) 

    return jsonify({'file':base64.b64encode(fichero_enc)}) #aquí salta la excepción

The problem appears when I try to encode it again in base64 in order to create the JSON response, which throws me an exception of type JSON :

>> UnicodeDecodeError: 'utf8' codec can't decode byte 0x86 in position 2: invalid start byte

I do not understand why this happens if I never took any action with utf8, I do not really understand how the encoding / decoding works in python.

    
asked by Kurosh D. 29.11.2017 в 12:26
source

0 answers