Thread: Base64 encoding

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    23
    Rep Power
    0

    Base64 encoding


    Hi there,

    I'm using Python 3 and I wanted to play around with the codecs just to get a better understanding of how they work.

    I followed this example found on another website and it doesn't work:

    Code:
    str = "this is string example....wow!!!"
    print ("Encoded String: " + str.encode('base64','strict'))
    When I run this, I get:

    Traceback (most recent call last):
    File "C:\Python33\encoding.py", line 2, in <module>
    print ("Encoded String: " + str.encode('base64','strict'))
    LookupError: unknown encoding: base64


    I read some where that this syntax is no longer supported on Python 3, so then I tried:

    Code:
    str = "Let's try different symbols !@#$%^&*"
    strdec = base64.b64encode(str)
    print("Encoded string "+ strdec)
    and got the following:

    Traceback (most recent call last):
    File "C:\Python33\encoding.py", line 2, in <module>
    strdec = base64.b64encode(str)
    NameError: name 'base64' is not defined


    According to the example found on said website, I should be able to view the string in 64 codec, something like:

    Code:
    Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
    Can someone please confirm whether the first syntax used is no longer supported and why the 2nd one is not working either?

    I appreciate the help
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    4
    You have to import base64 to use the second version.

    Comments on this post

    • pgonzaleznet agrees : Thank you!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    23
    Rep Power
    0
    Thanks!

    I also read the following on another website:

    base64 encoding takes 8-bit binary byte data and encodes it using only the characters A-Z, a-z and 0-9, so it can be transmitted over channels that does not preserve all 8-bits of data, such as email.

    Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b'' syntax.

    If you remove the b, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit.


    Not sure if it's correct, but based on that I did the following:

    python Code:
    import base64
     
    str = "Let's try different symbols !@#$%^&*"
    strenc = str.encode("utf8")
    strdec = base64.b64encode(strenc)
    print(strdec)


    That worked just fine, so it seems that I indeed needed to import base 64 and also, convert to utf8 first.

    Thank you very much!

IMN logo majestic logo threadwatch logo seochat tools logo