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)
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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With