在Linux或macOS的bash對字串做base64編碼及解碼的方式如下。
使用核心命令工具coreutils的base64命令即可對字串進行base64的編碼及解碼。
Base64 Encode
目錄中有一文字檔hello.txt內容如下:
hello.txt
hello world
輸入base64 hello.txt對同目錄中的文字檔案hello.txt進行編碼,編碼後的文字為aGVsbG8gd29ybGQK。
$ base64 hello.txt
aGVsbG8gd29ybGQK
或搭配echo直接對字串編碼,輸入echo "hello world" | base64對字串hello world編碼。
$ echo 'hello world' | base64
aGVsbG8gd29ybGQK
或將編碼後的結果輸出到另一檔案,例如下面把編碼結果輸出到encoded.txt檔。
$ echo 'hello world' | base64
> encoded.txt
Base64 Decode
目錄中有一編碼檔encoded.txt內容如下:
encoded.txt
aGVsbG8gd29ybGQK
輸入base64 --decode encoded.txt對同目錄中的編碼檔案encoded.txt進行解碼,解碼後的文字為hello world。
$ base64 --decode encoded
hello world
或搭配echo直接對編碼進行解碼,輸入echo "aGVsbG8gd29ybGQK" | base64 --decode對編碼aGVsbG8gd29ybGQK做解碼。
$ echo 'aGVsbG8gd29ybGQK' | base64 --decode
hello world
或將解碼後的結果輸出到另一檔案,例如下面把解碼結果輸出到decoded.txt檔。
$ echo 'aGVsbG8gd29ybGQK' | base64 --decode > decoded.txt
decoded.txt
hello world
沒有留言:
張貼留言