Friday, December 30, 2016

Convert String to Base64 in Python

Code to convert string (from utf-8) to base64 encoding and base64 back to utf-8:

import base64

si = input('\nenter text:\n')
print('\nyou entered\n' + si)

b64 = base64.b64encode(bytes(si, 'utf-8'))
print('\nbase64 is\n' + str(b64))

b64_bs = bytearray(base64.b64encode(bytes(si, 'utf-8')))
print('\nbase64 byte stream is\n' + str(list(b64_bs)))

so = base64.b64decode(b64).decode('utf-8', 'ignore')
print('\nstring is\n' + so)

1 comment: