Windows、LinuxおよびMacでのBase64のエンコードおよびデコード
ファイルを base64 でエンコードする必要がある緊急な場合に
Windows、Linux、MacでファイルをBase64でエンコードおよびデコードする方法の例を以下に示します。
WindowsでファイルをBase64に変換する
Windowsで通常のファイルをBase64に変換するには、以下の方法を使用できます。
Certutilを使用してコマンドプロンプトで変換する
-
コマンドプロンプトを開きます。
-
次のコマンドを実行します:
certutil -encode
をファイルのパスに、
を出力ファイル名(例:encoded.b64
)に置き換えてください。 -
一時ファイルに保存せずにBase64の内容を直接画面に表示したい場合は、次のように実行します:
certutil -encode tmp.b64 && findstr /v /c:- tmp.b64 && del tmp.b64
これにより、処理後に
tmp.b64
が削除され、一時ファイルが残らないようになります。
PowerShellを使用する
- PowerShellを開きます。
- 次のコマンドを実行します:
[Convert]::ToBase64String([System.IO.File]::ReadAllBytes("your_file_path"))
"your_file_path"
をファイルのフルパスに置き換えてください。これにより、Base64文字列がコンソールに直接出力されます。
カスタムスクリプトを使用する
より柔軟性が必要な場合は、ConvertTo-Base64.ps1
のようなスクリプトを使用できます。これにより、ファイルをBase64にエンコードし、出力ファイルに保存するか、JSON形式でフォーマットすることも可能です。
これらの方法により、追加のソフトウェアのインストールを必要とせずに、迅速かつ効率的にBase64エンコードが可能です。
LinuxでファイルをBase64に変換する
Linuxでは、バイナリファイルをBase64に変換するには、base64
コマンドを使用できます。これは、ほとんどのLinuxディストリビューションに事前にインストールされています。Windowsに比べてはるかに使いやすいです!
以下のように実行してください:
基本構文
base64 [OPTIONS] [FILE]
ファイルをエンコードする手順
-
テルミナルを開きます。
-
次のコマンドを実行します:
base64 input_file > output_file
input_file
をファイルのパスに、output_file
をBase64エンコードされた内容を保存したいファイル名に置き換えてください。例:
base64 myfile.txt > encoded.txt
-
エンコードされた内容を直接テルミナルに表示したい場合は、次のように実行します:
base64 input_file
オプションのフラグ
-w
: 指定された文字数ごとに改行します(デフォルトは76)。-w 0
を使用すると改行がされません。 例:base64 -w 0 input_file > output_file
Base64ファイルをデコードする
Base64エンコードされたファイルを元の形式に戻すには、次のように実行します:
base64 --decode encoded_file > decoded_file
この方法は効率的で、ほとんどのLinuxディストリビューションで追加のインストールを必要としません。
MacでBase64をエンコード/デコードする
Linuxに近いですが、いくつか異なる点があります。
macOSでは、組み込みの base64
コマンドを使用して、通常のファイルをBase64に変換できます。以下のように実行してください:
ファイルをエンコードする手順
-
テルミナルを開きます。
-
次のコマンドを実行します:
base64 -i input_file > output_file
input_file
をファイルのパスに、output_file
をBase64エンコードされた内容を保存したいファイル名に置き換えてください。例:
base64 -i myfile.txt > encoded.txt
-
Base64エンコードされた内容を直接テルミナルに表示したい場合は、次のように実行します:
base64 -i input_file
オプションのクリップボード統合
ファイルをエンコードし、結果を直接クリップボードにコピーするには、次のように実行します:
base64 -i input_file | pbcopy
Base64ファイルをデコードする
Base64エンコードされたファイルを元の形式に戻すには、次のように実行します:
base64 -D -i encoded_file > decoded_file
これらのコマンドは、macOS 10.7以降のすべての現代的なバージョンで動作します。
base64ツールのコマンドラインパラメータのフルリスト
$ base64 --help
Usage: base64 [OPTION]... [FILE]
Base64 encode or decode FILE, or standard input, to standard output.
With no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
-d, --decode decode data
-i, --ignore-garbage when decoding, ignore non-alphabet characters
-w, --wrap=COLS wrap encoded lines after COLS character (default 76).
Use 0 to disable line wrapping
--help display this help and exit
--version output version information and exit
The data are encoded as described for the base64 alphabet in RFC 4648.
When decoding, the input may contain newlines in addition to the bytes of
the formal base64 alphabet. Use --ignore-garbage to attempt to recover
from any other non-alphabet bytes in the encoded stream.
...