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.
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==
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
>>> s = 'base64 encode'
>>> s.encode('base64')
'YmFzZTY0IGVuY29kZQ==\n'
>>> s = 'YmFzZTY0IGVuY29kZQ=='
>>> s.decode('base64')
'base64 encode'
Python3
Use the base64 module, which is the standard library.
Use the base64.b64encode ()
method.
>>> import base64
>>> s = 'base64 encode'
>>> base64.b64encode(s.encode('utf-8'))
b'YmFzZTY0IGVuY29kZQ=='
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.