How to Base64 Encode a String in Batch Script
Base64 is a standard encoding scheme that transforms any data into a simple, text-only string. It is not encryption, but a way to safely transmit data in formats that only support plain text, such as in certain XML nodes, data URIs, or for basic HTTP authentication headers. Windows Batch does not have a native command to directly Base64 encode a string, which means we must use a workaround with a built-in utility.
This guide will teach you the standard method for Base64 encoding using the certutil command with temporary files. More importantly, it will demonstrate the vastly superior and simpler modern approach using a PowerShell one-liner, which is the recommended method for its reliability and efficiency.
The Challenge: No Native String Encoder
The main difficulty is that cmd.exe has no built-in function to perform Base64 encoding on a string in memory. To solve this, we must use a tool that operates on files. The certutil.exe utility, while designed for managing security certificates, has a powerful encoding function we can leverage. This requires writing our string to a temporary file first.
The Core Method: Using certutil with Temporary Files
The process involves three main steps:
- Write:
ECHOthe string you want to encode into a temporary input file. - Encode: Use
certutil -encodeto read the temporary input file and write a new, Base64-encoded output file. - Read: Read the content of the encoded output file into a variable.
- Cleanup: Delete both temporary files.
The Syntax: certutil -f -encode "inputFile.txt" "outputFile.b64"
The Superior Method (Recommended): Using PowerShell
For any modern Windows system, calling PowerShell is a far more elegant and efficient solution. It can perform the entire operation in memory without creating any temporary files.
The Syntax
This PowerShell command can be called directly from a batch script.
powershell -Command "[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes('Your String Here'))"
'Your String Here': The string to be encoded.GetBytes(...): Converts the string into a byte array using UTF-8 encoding.ToBase64String(...): Converts the byte array into its Base64 string representation.
This method is faster, cleaner, and avoids disk I/O.
Basic Example: Encoding "hello world"
Let's see both methods in action.
Method 1: certutil Script
@ECHO OFF
SET "INPUT_STRING=hello world"
SET "TEMP_IN=%TEMP%\in.txt"
SET "TEMP_OUT=%TEMP%\out.b64"
REM Step 1: Write string to temp file
ECHO|SET /P="=%INPUT_STRING%" > "%TEMP_IN%"
REM Step 2: Encode the file
certutil -f -encode "%TEMP_IN%" "%TEMP_OUT%" > NUL
REM Step 3: Read the encoded content (skipping the header)
FOR /F "skip=1 delims=" %%L IN ('TYPE "%TEMP_OUT%" ^| FINDSTR /V /C:"-----"') DO (
SET "ENCODED_STRING=%%L"
GOTO :DoneCertUtil
)
:DoneCertUtil
REM Step 4: Clean up
DEL "%TEMP_IN%" "%TEMP_OUT%"
ECHO certutil method: %ENCODED_STRING%
Output:
certutil method: aGVsbG8gd29ybGQ=
ECHO|SET /P=... is a trick to echo a string without a trailing newline.
Method 2: PowerShell Script
@ECHO OFF
SET "INPUT_STRING=hello world"
SET "ENCODED_STRING="
FOR /F "delims=" %%V IN (
'powershell -Command "[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes('%INPUT_STRING%'))"'
) DO (
SET "ENCODED_STRING=%%V"
)
ECHO PowerShell method: %ENCODED_STRING%
Output:
PowerShell method: aGVsbG8gd29ybGQ=
How the certutil Script Works
The certutil method is complex because its output file is not just the Base64 string. It writes a standard PEM-formatted file, which includes a header and footer.
-----BEGIN CERTIFICATE-----
aGVsbG8gd29ybGQ=
-----END CERTIFICATE-----
The FOR /F loop in the script is designed to parse this. skip=1 ignores the BEGIN line, and FINDSTR /V filters out the END line, leaving only the Base64 string itself.
Common Pitfalls and How to Solve Them
Problem: The certutil Output Includes Headers and Footers
As explained above, the certutil output file contains extra lines that are usually not wanted when you just need the raw Base64 string for an API or header.
Solution: The parsing logic in the example (FOR /F "skip=1 ... FINDSTR /V ...) is the correct way to strip these unwanted lines. The PowerShell method avoids this problem entirely, as it returns only the raw Base64 string.
Problem: The Process Creates Temporary Files
The certutil method creates clutter and can leave junk files behind if the script is interrupted or fails. It's also slower due to disk access.
Solution: There is no way to avoid this with certutil. This is the primary reason the PowerShell method is superior. It performs the entire operation in memory, making it cleaner and more efficient.
Practical Example: Creating an HTTP Basic Authentication Header
A classic use for Base64 is creating an Authorization header for an HTTP request. The format is Basic base64(username:password).
This script uses the robust PowerShell method to generate this value.
@ECHO OFF
SETLOCAL
SET "USERNAME=my-api-user"
SET "PASSWORD=S3cr3t!P@ssword"
SET "AUTH_STRING=%USERNAME%:%PASSWORD%"
SET "BASE64_AUTH="
ECHO --- Generating HTTP Auth Header ---
ECHO String to encode: "%AUTH_STRING%"
ECHO.
FOR /F "delims=" %%V IN (
'powershell -NoProfile -Command "[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes('%AUTH_STRING%'))"'
) DO (
SET "BASE64_AUTH=%%V"
)
ECHO The final HTTP header is:
ECHO Authorization: Basic %BASE64_AUTH%
ENDLOCAL
Output:
--- Generating HTTP Auth Header ---
String to encode: "my-api-user:S3cr3t!P@ssword"
The final HTTP header is:
Authorization: Basic bXktYXBpLXVzZXI6UzNjcjN0IVBAc3N3b3Jk
Conclusion
While batch scripting has no direct Base64 function, modern Windows provides two effective methods to accomplish the task.
- The
certutilmethod is the "pure" way to do it without explicitly calling PowerShell. However, it is clumsy, requires creating and deleting temporary files, and needs careful output parsing. - The PowerShell
[Convert]::ToBase64Stringmethod is the overwhelmingly recommended best practice. It is faster, cleaner, more reliable, and avoids all the pitfalls of thecertutilapproach.
For any script that requires Base64 encoding, leveraging the power of a PowerShell one-liner is the most professional and efficient solution.