Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to and from Base 64 [duplicate]

Tags:

I am trying to write two programs one that converts a string to base64 and then another that takes a base64 encoded string and converts it back to a string.
so far i cant get past the base64 encoding part as i keep getting the error

TypeError: expected bytes, not str

my code looks like this so far

def convertToBase64(stringToBeEncoded):
import base64
EncodedString= base64.b64encode(stringToBeEncoded)
return(EncodedString)
like image 481
spenman Avatar asked Nov 07 '12 01:11

spenman


People also ask

Why do Base64 strings end with ==?

Q Why does an = get appended at the end? A: As a short answer: The last character ( = sign) is added only as a complement (padding) in the final process of encoding a message with a special number of characters.

Is Base64 string always same?

Artjom B. Base64 is not encryption. But yes, different input strings will always encode to different Base64-encoded strings, and the same input string will always encode to the same Base64-encoded string. It's not a hash though, so small changes in the input will only result in small changes in the output.

What is toString Base64?

The first parameter is the data in Base64 and second parameter is "base64". Then you simply have to call "toString" on the buffer object but this time the parameter passed to the method will be "ascii" because this is the data type that you want your Base64 data to convert to.


1 Answers

A string is already 'decoded', thus the str class has no 'decode' function.Thus:

AttributeError: type object 'str' has no attribute 'decode'

If you want to decode a byte array and turn it into a string call:

the_thing.decode(encoding)

If you want to encode a string (turn it into a byte array) call:

the_string.encode(encoding)

In terms of the base 64 stuff: Using 'base64' as the value for encoding above yields the error:

LookupError: unknown encoding: base64

Open a console and type in the following:

import base64
help(base64)

You will see that base64 has two very handy functions, namely b64decode and b64encode. b64 decode returns a byte array and b64encode requires a bytes array.

To convert a string into it's base64 representation you first need to convert it to bytes. I like utf-8 but use whatever encoding you need...

import base64
def stringToBase64(s):
    return base64.b64encode(s.encode('utf-8'))

def base64ToString(b):
    return base64.b64decode(b).decode('utf-8')
like image 168
Sheena Avatar answered Sep 20 '22 06:09

Sheena