Prepend information in base64 encoding - python

Here is an answer which gives some information on how to base64 encode a file. However, I also want to pass in the filetype and mimetype. for the information in the base64 encoded string.
So far I have for my base64 string:
x=base64.b64encode(open('/Users/user/Desktop/img.PNG').read())
What is the correct information to prepend, and how would I do this?

It seems like the following is how I would get the base64 file information to pass to the server:
file = '/Users/user/Desktop/img.PNG'
prepend_info = 'data:%s;base64' % mimetypes.guess_type(file)[0]
base_64_data = open(file).read().encode('base64')
image_data_base64 = '%s,%s' % (prepend_info, base_64_data)
This then gives me:
data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wB...

Perhaps something along these lines:
from __future__ import print_function
import base64
import binascii
import os
def base64_encode_file(filename):
filetype = os.path.splitext(filename)[1][1:] # remove leading '.' from ext
with open(filename) as file:
data = file.read()
return base64.b64encode(','.join((filename, filetype, data))), data
filename = 'C:/Users/martin/Desktop/img.PNG'
#filename = '/Users/user/Desktop/img.PNG'
encoded, data = base64_encode_file(filename)
print('encoded: {} (hex file data: {})'.format(encoded, binascii.hexlify(data)))
decoded = base64.b64decode(encoded).split(',', 2)
print('decoded:', decoded[0], decoded[1], binascii.hexlify(decoded[2]))
Output:
encoded: QzovVXNlcnMvbWFydGluL0Rlc2t0b3AvaW1nLlBORyxQTkcsiVBORwo=
(hex file data: 89504e470a)
decoded: C:/Users/martin/Desktop/img.PNG PNG 89504e470a

Related

How to convert a Base64 file to bytes?

I am trying to pass a base64 to bytes. But I think I'm doing it wrong because I'm passing it to ascii. The file is much bigger but I didn't want to put it all. I hope you can support me.
def convert():
base64_message = 'JVBERi0xLjUKJeLjz9MKMSAwIG9iago8PC9DcmVhdG9yKFdyaXRlcikvc2l6ZV9oZWlnaHQoMTI1LjApL01vZERhdGUoRDoyMDIyMDIxNjE5MzQzOS0wNicwMCcpL2xhc3RQYWdlKDEpL0NyZWF0aW9uRGF0ZShEOjIwMjIwMjE2MTkzNDM3LTA2JzAwJykvc3BhY2VfYm94KDIwLjApL2Nvb3JkaW5hdGVzUGFn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mJUhdixlSdIK+wpCjMsHTsIqtvIOyrIRqI2EsObBLkiqmcd/zYwJrcmmx2I/SOMF7izpVh6v0ej5t7eodw3vUSS3+BuqhlL4RCgij9pSVVtB5CRSFuxtZyXwNpvJUemI5WsUP+p2aOCYR8C51Vl7XY/bj/vy+8la+jltcL+sLq66hiezb88Y7QujOqIs+IXSaOJLNOG1y2+jT+MaFIxh48GuSJbpNxseLiuL2+nkC7dEtI4O48Ir59txDBZYvwa/dGvmlAzF6fIE7EviVdZQNCybdIM+/AZ5HfaeIuYLaDyxeaN1K29ozI2dC7MFe95QWMFFr8r+5eOYl8QuOQQb3xS1LKxhkZGaadWPX4ZzMESLiWlE+9JeeMSpeRmYmhdr3rFOI607e9PRgZJajKmaCt/plY0O46JgzDPeEgZYkyckfysIhRG8KhoKlyIdWltWKto1yXuNP4O0NURWuV9o9kuk4h4jlMVvrMq3nXVuWNsWotMYnZ8wcoY8mh+C4IwtvwNtGQkYzVpIxJ1l10XxHEb2i0e7IrbIQ+zWEhZGFx1TZ/EXdvnV/dwMcA1Q24uFGWKrZ6xOOH8Bz2xgwNpk4WiEzdMvioOAN0KcBKb5pc0bi4='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
print(message)
you can find the following here:
import base64
base64_message = 'UHl0aG9uIGlzIGZ1bg=='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
print(message)
Source: https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/
just two line could solve this problem:
import base64
base64_code = "VER30QHI30JFOIAIO3020085723F" # this is just a example
img_data = base64_code.encode()
content = base64.b64decode(img_data)
with open('/path/to/your/image.jpg', 'wb') as fw:
fw.write(content)
print(content)
then you could check the image bytes.

remove \xa0 while writing csv file

I have below code to write a list items as csv file. But while doing that, I see special character  is occurring in the output csv file. For testing in the local, I have defined a list with character '\xao' included in the list items and tested various ways to remove that and replace with space. But, I still get the special character in the csv output. Can anyone help?
import csv
from flask import make_response
import StringIO
csv_list = [['hfhf\xa0 fsdg','dsf'],['fsdgs fsdfs','fsdfsd'],['dsf\xa0 sf','asfg']]
def download_csv_summary(csv_list):
si = StringIO.StringIO()
cw = csv.writer(si)
filename = 'Test'
cw.writerows(csv_list)
output = make_response(si.getvalue())
output.headers['Content-Disposition'] = \
'attachment; filename={filename}.csv'.format(filename=filename)
output.headers['Content-Type'] = 'text/csv'
return output
The writerows line needs to be changed to replace the \xa0s:
import csv
from flask import make_response
import StringIO
csv_list = [
['hfhf\xa0 fsdg','dsf'],
['fsdgs fsdfs','fsdfsd'],
['dsf\xa0 sf','asfg']
]
def download_csv_summary(csv_list):
si = StringIO.StringIO()
cw = csv.writer(si)
filename = 'Test'
cw.writerows([[str(x).replace('\xa0', '') for x in l] for l in csv_list])
output = make_response(si.getvalue())
output.headers['Content-Disposition'] = \
'attachment; filename={filename}.csv'.format(filename=filename)
output.headers['Content-Type'] = 'text/csv'
return output

string formatted as base64 to base64 object

From a post request, I receive a base64 in JSON. Problem is that I can't just change the file type from string to base64 since it's already formatted as base64. need the base64 to convert it back to an image.
json_data = request.get_json(force=True)
img = json_data['img']
print(img)
with open("imageToSave.png", "wb") as fh:
fh.write(base64.decodebytes(img))
In order to decode it, add the third line which decodes the string to base64
json_data = request.get_json(force=True)
img = json_data['img']
imgdata = base64.b64decode(img)
filename = 'upload/newimg.jpg' # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
f.write(imgdata)

How to get decode attachment filename with python email?

I use the following code to extract filename of the attachment:
import email.utils
msg = email.message_from_string(self.request.body) # http://docs.python.org/2/library/email.parser.html
for part in msg.walk():
ctype = part.get_content_type()
if ctype in ['image/jpeg', 'image/png']:
image_file = part.get_payload(decode=True)
image_file_name = part.get_filename()
It works well in many cases, but sometime as image_file_name I get values like =?KOI8-R?B?xsHTLTk2Mi5qcGc=?= or =?UTF-8?B?REkyeTFXMFNMNzAuanBn?=.
How should I handle such cases?
You can use decode_header function like this:
from email.header import decode_header
filename = part.get_filename()
if decode_header(filename)[0][1] is not None:
filename = str(decode_header(filename)[0][0]).decode(decode_header(filename)[0][1])
With Python 3:
from email.message import EmailMessage
from email.header import decode_header
def get_part_filename(msg: EmailMessage):
filename = msg.get_filename()
if decode_header(filename)[0][1] is not None:
filename = decode_header(filename)[0][0].decode(decode_header(filename)[0][1])
return filename
You should look at the three parts separated by '?', and use the first two as instructions for how to treat the third:
The first bit is the character-encoding (KO18-R and UTF-8 in your examples), and the second bit is a 'B' to indicate base64 encoding - Q in it's place would indicate quoted-printable, so you should prepare your code for that as well.
Elaborating on #Nikon's response:
from email.header import decode_header
filename = part.get_filename()
fname, charset = decode_header(filename)
if charset:
filename = fname.decode(charset)

Simple encryption and decryption of strings by using bz2 in Python

I am trying to create a file with encrypted username, password and computer name when the user logs in. And the same data I want to use again to authenticate the data but by decrypting them first. I am trying to use something that is built in python and simple.
import os
import bz2
os.chdir("D:/test")
encrypted_username = bz2.compress('username')
encrypted_password = bz2.compress('password')
computer_name = os.environ['COMPUTERNAME']
encrypted_computer_name = bz2.compress(computer_name)
f = open("Session.dat", "w")
f.write(encrypted_username + '\n')
f.write(encrypted_password + '\n')
f.write(encrypted_computer_name)
f.close()
f = open("Session.dat", "r")
data = f.read()
d_data = bz2.decompress(data)
f.close()
print(d_data)
But when I decrypt the data in the file and print it. I get the answer as below. Why am I not getting the password and computer name?? Thank you.
username
The code compressed the strings separately. You should read all lines and decompress them line by line as alecxe commented. But that is not practical because compressed data could contians newline(s).
Instead combine strings (In the following code, I used NULL byte \0 as separator), then compress the combined string.
Decompress: After decompress, split combined strings using the same separator.
import os
import bz2
#os.chdir("D:/test")
username = 'username'
password = 'password'
computer_name = os.environ['COMPUTERNAME']
compressed = bz2.compress(username + '\0' + password + '\0' + computer_name)
with open("Session.dat", "wb") as f:
f.write(compressed)
with open("Session.dat", "rb") as f:
d_data = bz2.decompress(f.read())
print(d_data.split('\0'))
BTW, you should use binary mode to read/write compressed data.

Categories