うさぎ好きエンジニアの備忘録

うさぎたちに日々癒されているエンジニアが業務で直面したもの & 個人的な学習メモを残していきます。

base64備忘録

よく使うけど忘れがちなのでメモとして残しておきます。

エンコード

何かしらの文字列などをエンコードする場合にはbase64コマンドを使用。

$ echo -n 'this is test by kazono' | base64
dGhpcyBpcyB0ZXN0IGJ5IGthem9ubw==

ファイルから文字列を読み込んでエンコードする場合には-iオプションを利用すればOK。

# 適当なファイルの作成
$ echo -n 'this is test by kazono' > input.txt
$ cat input.txt
this is test by kazono

# base64エンコードの実行
$ base64 -i input.txt
dGhpcyBpcyB0ZXN0IGJ5IGthem9ubw==

ちなみにmacOSに標準でインストールされているbase64コマンドだと-oオプションを使うことで、エンコード結果をファイルとして出力可能。

$ base64 -i input.txt -o output.txt
$ cat output.txt
dGhpcyBpcyB0ZXN0IGJ5IGthem9ubw==

デコード

-dオプションをつけることでデコードできる。

ちなみにmacOSにインストールされているbase64コマンドだと-D(大文字)になるので注意が必要。

$ echo 'dGhpcyBpcyB0ZXN0IGJ5IGthem9ubw==' | base64 -d
this is test by kazono

Python3でbase64を使ってみる。

Python3でbase64モジュールを使ってみる。

今回試した環境はPython 3.7.0。

$ python --version
Python 3.7.0

エンコード

エンコードの際にはbase64.b64encode()を使う。

>>> import base64
>>> str = 'this is test by kazono'
>>> base64.b64encode(str.encode('utf-8'))
b'dGhpcyBpcyB0ZXN0IGJ5IGthem9ubw=='

デコード

デコードの際にはbase64.b64decode()を使う。

>>> import base64
>>> str = b'dGhpcyBpcyB0ZXN0IGJ5IGthem9ubw=='
>>> base64.b64decode(str)
b'this is test by kazono'