[PYTHON] Base64 decode / encode

About Base64 decoding / encoding used in the world of the Web. It is also used in CTF (Capture The Flag), so I summarized it briefly.

UNIX commands

Encode

Use the base64 command.

$ echo -n 'base64 encode' | base64
YmFzZTY0IGVuY29kZQ==

Use the -i option to read a string from a file and encode it. Use the -o option to write the result to a file.

$ base64 -i input.txt -o output.txt

Contents of input.txt

base64 encode

Contents of output.txt

YmFzZTY0IGVuY29kZQ==

Decode

Add the -D option (for Mac). For Linux, it is -d (lowercase).

# Mac
$ echo 'YmFzZTY0IGVuY29kZQ==' | base64 -D
base64 encode

# Linux
$ echo 'YmFzZTY0IGVuY29kZQ==' | base64 -d
base64 encode

As with encoding, the -i and -o options are valid.

Python

Python2

Encode

>>> s = 'base64 encode'
>>> s.encode('base64')
'YmFzZTY0IGVuY29kZQ==\n'

Decode

>>> s = 'YmFzZTY0IGVuY29kZQ=='
>>> s.decode('base64')
'base64 encode'

Python3

Use the base64 module, which is the standard library.

Encode

Use the base64.b64encode () method.

>>> import base64
>>> s = 'base64 encode'
>>> base64.b64encode(s.encode('utf-8'))
b'YmFzZTY0IGVuY29kZQ=='

Decode

Use the base64.b64decode () method.

>>> import base64
>>> encoded = b'YmFzZTY0IGVuY29kZQ=='
>>> base64.b64decode(encoded)
b'base64 encode'

Note that both methods are byte objects for both arguments and return values.

Recommended Posts

Base64 decode / encode
Create a command to encode / decode Splunk base64
Python script for ldapsearch base64 decode
Python2 str / unicode and encode / decode
Experimented with unicode, decode and encode
Base number
Understand base64.