[PowerShell] 解碼 Base64 字串,並建立對應的二進位檔案
今天想要用 PowerShell 寫一個程式,
讓它在執行的時候,可以寫出一個二進位的檔案 (binary file)~
基本的想法是先將檔案的內容轉成 Base64 字串,在執行時再將這字串反轉成原本的二進位檔~
1. 取得檔案的 Base64 編碼字串
要取得檔案的 Base64 編碼字串有很多種方法,
像是可以直接利用 Base64 – Online Base64 decoder and encoder 網站,
把要編碼的二進位檔案上傳,選擇 Encode -> Convert the source data,
就能取得編碼後的 Base64 字串:
也可以用 PowerShell 或 Python 來取得,像下面是 Python 的例子:
>>> import binascii >>> print binascii.b2a_base64(open("edit.gif", "rb").read()) R0lGODlhDwAPAPMGAA4ODgCWANra2vLy8gC5AP/isf///wDcAP///////wAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFHgAIACwAAAAADwAPAAAIZQABCBxIUCCCgwAMKFzI0CCChAwjAhAA4KGBghgHSjxwAKKBAQIbciRAACLIhANHEggQQOBJhQBUsmz5MSSAAgdIzjRps0CBlSwJvrzpMyjDoUQLeFSIVGPEkwOiSp0qNaNVAAEBACH5BAQeAAAALAIABAALAAkAAAg7AA0IFAjgwAEAAwcWPECAAEIAEBc2DBAAoQGJBChWvFiAYUaKDwEUKPCxIkSOI0EmhDiygEWCEU8mDAgAIfkEBB4AAAAsAwAEAAsACQAACEEADQgUCODAAQAGBgw0UPAAAQIABgCY2PBhgAAIGRq0eBEhgAIOCVzEKPFjAZEdEzIswDKlyoksC2RMSJHiwgEBAQAh+QQEeAAAACwEAAQACgAJAAAIPQANCBQI4MABAAMGGih4gAABABAhGnQYIADBiQQqWgRQoGHGihELFPgYAOFCkQVAGkgIESUAgQMiRhw4ICAAOw==
2. 用 PowerShell 寫出 Base64 解碼後的二進位檔案
先用一個變數將剛剛的 Base64 字串存起來:
$Base64Content = "R0lGODlhDwAPAPMGAA4ODgCWANra2vLy8gC5AP/isf///wDcAP///////wAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFHgAIACwAAAAADwAPAAAIZQABCBxIUCCCgwAMKFzI0CCChAwjAhAA4KGBghgHSjxwAKKBAQIbciRAACLIhANHEggQQOBJhQBUsmz5MSSAAgdIzjRps0CBlSwJvrzpMyjDoUQLeFSIVGPEkwOiSp0qNaNVAAEBACH5BAQeAAAALAIABAALAAkAAAg7AA0IFAjgwAEAAwcWPECAAEIAEBc2DBAAoQGJBChWvFiAYUaKDwEUKPCxIkSOI0EmhDiygEWCEU8mDAgAIfkEBB4AAAAsAwAEAAsACQAACEEADQgUCODAAQAGBgw0UPAAAQIABgCY2PBhgAAIGRq0eBEhgAIOCVzEKPFjAZEdEzIswDKlyoksC2RMSJHiwgEBAQAh+QQEeAAAACwEAAQACgAJAAAIPQANCBQI4MABAAMGGih4gAABABAhGnQYIADBiQQqWgRQoGHGihELFPgYAOFCkQVAGkgIESUAgQMiRhw4ICAAOw=="
再將這字串依 Base64 解碼後,丟給 Set-Content 依據內容產生檔案:
[System.Convert]::FromBase64String($Base64Content) | Set-Content -Path "dropped_file.exe" -Encoding Byte
用這方法,就可以很容易的在 PowerShell script 裡面,夾帶任何需要的檔案囉~
參考資料:Embedding External Files in PowerShell Scripts
(本頁面已被瀏覽過 994 次)