Base64 编码“字符串” - 命令行 Windows?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37046771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Base64 Encode "string" - command-line Windows?
提问by Taapo
I have found numerous ways to base64 encode whole files using the command-line on Windows, but I can't seem to find a simple way to batch encode just a "string" using a command-line utility.
我已经找到了多种在 Windows 上使用命令行对整个文件进行 base64 编码的方法,但我似乎找不到一种简单的方法来使用命令行实用程序对“字符串”进行批量编码。
How does one do this, for use in a batch file for example?
如何做到这一点,例如在批处理文件中使用?
回答by rojo
Here's a PowerShell one-liner you can run from a cmd console that'll Base64 encode a string.
这是一个 PowerShell 单行程序,您可以从 cmd 控制台运行,该控制台将对字符串进行 Base64 编码。
powershell "[convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(\"Hello world!\"))"
It's probably not as fast as npocmaka's solution, but you could set a console macro with it.
它可能不如 npocmaka 的解决方案快,但您可以使用它设置控制台宏。
doskey btoa=powershell "[convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(\"$*\"))"
doskey atob=powershell "[Text.Encoding]::UTF8.GetString([convert]::FromBase64String(\"$*\"))"
btoa Hello world!
btoa This is fun.
btoa wheeeeee!
atob SGVsbG8gd29ybGQh
Be advised that doskey
doesn't work in batch scripts -- only the console. If you want do use this in a batch script, make a function.
请注意,这doskey
不适用于批处理脚本——仅适用于控制台。如果您想在批处理脚本中使用它,请创建一个函数。
@echo off
setlocal
call :btoa b64[0] "Hello world!"
call :btoa b64[1] "This is fun."
call :btoa b64[2] "wheeeeee!"
call :atob b64[3] SGVsbG8gd29ybGQh
set b64
goto :EOF
:btoa <var_to_set> <str>
for /f "delims=" %%I in (
'powershell "[convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(\"%~2\"))"'
) do set "%~1=%%I"
goto :EOF
:atob <var_to_set> <str>
for /f "delims=" %%I in (
'powershell "[Text.Encoding]::UTF8.GetString([convert]::FromBase64String(\"%~2\"))"'
) do set "%~1=%%I"
goto :EOF
Or if you'd prefer a batch + JScript hybrid:
或者,如果您更喜欢批处理 + JScript 混合:
@if (@CodeSection==@Batch) @then
@echo off & setlocal
call :btoa b64[0] "Hello world!"
call :btoa b64[1] "This is fun."
call :btoa b64[2] "wheeeeee!"
call :atob b64[3] SGVsbG8gd29ybGQh
set b64
goto :EOF
:btoa <var_to_set> <str>
:atob <var_to_set> <str>
for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" %0 "%~2"') do set "%~1=%%I"
goto :EOF
@end // end batch / begin JScript hybrid code
var htmlfile = WSH.CreateObject('htmlfile');
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=10" />');
WSH.Echo(htmlfile.parentWindow[WSH.Arguments(0).substr(1)](WSH.Arguments(1)));
Edit: batch + VBScript hybrid for @Hackoo:
编辑:@Hackoo 的批处理 + VBScript 混合:
<!-- : batch portion
@echo off & setlocal
call :btoa b64[0] "Hello world!"
call :btoa b64[1] "This is fun."
call :btoa b64[2] "wheeeeee!"
call :atob b64[3] SGVsbG8gd29ybGQh
set b64
goto :EOF
:btoa <var_to_set> <str>
:atob <var_to_set> <str>
for /f "delims=" %%I in ('cscript /nologo "%~f0?.wsf" %0 "%~2"') do set "%~1=%%I"
goto :EOF
: VBScript -->
<job>
<script language="VBScript">
Set htmlfile = WSH.CreateObject("htmlfile")
htmlfile.write("<meta http-equiv='x-ua-compatible' content='IE=10' />")
if WSH.Arguments(0) = ":btoa" then
WScript.Echo htmlfile.parentWindow.btoa(WSH.Arguments(1))
else
WScript.Echo htmlfile.parentWindow.atob(WSH.Arguments(1))
end if
</script>
</job>
回答by Zac Thompson
According to the comments on the question, you can use certutil. e.g.,
根据对该问题的评论,您可以使用certutil。例如,
certutil -encode raw.txt encoded.txt
or
或者
certutil -f -encode raw.txt encoded.txt
The -f
means "force overwrite". Otherwise you will get an error if the output file (encoded.txt above) already exists.
该-f
手段“强行覆盖”。否则,如果输出文件(上面的encoded.txt)已经存在,您将收到错误消息。
However, this will format the output into the encoded.txt file as if it were a certificate PEM file, complete with BEGIN and END lines, and split lines at the character max. So you would need to do further processing in a batch scenario, and a bit of extra work if the strings are long at all.
但是,这会将输出格式化为encoded.txt 文件,就好像它是证书PEM 文件一样,包含BEGIN 和END 行,并在最大字符处拆分行。所以你需要在批处理场景中做进一步的处理,如果字符串很长,还需要做一些额外的工作。
回答by npocmaka
This scriptcan decode/encode base64 strings on every machine from XP and above without requiring installed .net or internet explorer 10/11.It even can handle special javascript escaped symbols:
此脚本可以在 XP 及以上版本的每台机器上解码/编码 base64 字符串,而无需安装 .net 或 Internet Explorer 10/11。它甚至可以处理特殊的 javascript 转义符号:
// result is IkhlbGxvIg==
base64.bat -encode "\u0022Hello\u0022" -eval yes
// result is SGVsbG8=
base64.bat -encode "Hello"
This one accepts a single argument - the string you want to encode to base 64 and prints the result (but requires at least internet explorer 10 installed):
这个接受一个参数 - 您想要编码为 base 64 的字符串并打印结果(但至少需要安装 Internet Explorer 10):
@echo off
setlocal
set "string=%~1"
::echo %string%^|mshta.exe "%~f0"
for /f "delims=" %%# in ('echo %string%^|mshta.exe "%~f0"') do (
set b64=%%#
)
set b64
endlocal&exit /b %errorlevel%
<HTA:Application
ShowInTaskbar = no
WindowsState=Minimize
SysMenu=No
ShowInTaskbar=No
Caption=No
Border=Thin
>
<meta http-equiv="x-ua-compatible" content="ie=10" />
<script language="javascript" type="text/javascript">
window.visible=false;
window.resizeTo(1,1);
var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
var fso2= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(0);
var string=fso2.ReadLine();
var encodedString = btoa(string);
fso.Write(encodedString);
window.close();
</script>
回答by samgak
If you have OpenSSL for Windows installed you can use this to encode the string "Hello":
如果您安装了 Windows 版 OpenSSL,您可以使用它来对字符串“Hello”进行编码:
echo | set /p="Hello" | openssl base64
The | set /p=
is to suppress the newline that echo usually outputs.
这| set /p=
是为了抑制 echo 通常输出的换行符。
This will produce the same result as the following in bash:
这将在 bash 中产生与以下相同的结果:
echo -n 'Hello' | openssl base64
Output:
输出:
SGVsbG8=
回答by T3RR0R
This can (technically) be done entirely within Batch, By Creating an encryption\decryption VBS script from within batch that can be called with the name of the Variable whose Data you wish to encrypt\decrypt.
这可以(技术上)完全在批处理中完成,通过从批处理中创建加密\解密 VBS 脚本,该脚本可以使用您希望对其数据进行加密\解密的变量的名称进行调用。
Note: The below scipt is an Independant Subprogram.
注意:下面的scipt是一个独立的子程序。
Hybrid Batch Vbs Encrypter / Decrypter for passwords or other variables. Performs the action on data stored in the defined file - does not create the file.
用于密码或其他变量的混合批处理 Vbs 加密器/解密器。对存储在定义文件中的数据执行操作 - 不创建文件。
Note: file extension in vbs to match the filetype you save password/text to.
注意:vbs 中的文件扩展名与您保存密码/文本的文件类型相匹配。
To use this program Call it with the name of the Variable you wish to set and the offset to perform.
使用该程序 使用您希望设置的变量名称和要执行的偏移量调用它。
However your Main program takes user input:
但是您的主程序需要用户输入:
Set /p YourVariableName=
Store the Input to a File
将输入存储到文件
ECHO %YourVariableName%>YourSaveFile.txt
Call it with a positive offset (IE: +26) to encrypt, and an equivalent Negative offset to Decrypt. (IE: -26)
使用正偏移量(IE:+26)来加密,并使用等效的负偏移量来解密。(即:-26)
CALL "Insert Filepath To Encrypter.bat Here" YourVariableName +26
Begin Program; Encrypter.bat
开始程序;加密器.bat
@ECHO OFF
REM :: Do NOT modify the variable names Below, DO INSERT the filepath you used to Store the Data Being Encrypted / Decrypted.
Set "VarName=%~1"
Set "offset=%~2"
Set "SaveLoc=Your Filepath Here"
<"%saveLoc%" (
Set /p encryptData=
)
(
ECHO Dim objFSO 'File System Object
ECHO Set objFSO = CreateObject("Scripting.FileSystemObject"^)
ECHO Dim objTS 'Text Stream Object
ECHO Const ForWriting = 2
ECHO Set objTS = objFSO.OpenTextFile("%SaveLoc%", ForWriting, True^)
ECHO objTS.Write(encode("%encryptData%"^)^)
ECHO wscript.sleep "1000"
ECHO function encode(s^)
ECHO For i = 1 To Len(s^)
ECHO newtxt = Mid( s, i, 1^)
ECHO newtxt = Chr(Asc(newtxt^) %offset%^)
ECHO coded = coded + (newtxt^)
ECHO Next
ECHO encode = coded
ECHO End function
ECHO objTS.Close(^)
ECHO Set bjFSO = Nothing 'Destroy the object.
ECHO Set objTS = Nothing 'Destroy the object.
) >%TEMP%\encrypter.vbs
START /wait %TEMP%\encrypter.vbs
DEL /Q "%TEMP%\encrypter.vbs"
GOTO :EOF
```
回答by HackingAddict1337
@rojo's answer pointed out that:
@rojo的回答指出:
Be advised that
doskey
doesn't work in batch scripts -- only the console. If you want do use this in a batch script, make a function.
请注意,这
doskey
不适用于批处理脚本——仅适用于控制台。如果您想在批处理脚本中使用它,请创建一个函数。
An alternative is the string-based macro styleinvented by @jeb, @dbenhamand last but not least, DosTips user @Ed Dyreen:
另一种选择是由@jeb、@dbenham和最后但并非最不重要的 DosTips 用户@Ed Dyreen发明的基于字符串的宏样式:
init_b64encode.bat(DOES NOT WORKon Windows Server 2003 and Windows XP)
init_b64encode.bat(不起作用的Windows Server 2003和Windows XP上)
@echo off
setlocal DisableDelayedExpansion
if /I "%~1" == "help" goto :HELP
::ESC
FOR /F %%a in ('prompt $E ^& cmd /k ^<nul') do set ESC=%%a
if not defined CMDCALLER (
2>nul goto
call set "CMDCALLER=%%~f0"
call "%~f0" %*
set "CMDCALLER="
)
if /I "%CMDCALLER%" == "%%~f0" (
1>&2 echo %ESC%[31mInvalid Call to %~nx0%ESC%[0m
exit /b 5
)
::NL
( set LF=^
%= LF char =%
)
set ^"NL=^^^%LF%%LF%^%LF%%LF%^^" %= NL is a escaped LF =%
::MACRO
ENDLOCAL &^
set $MACRO.b64encode=FOR %%a IN (%%a main) DO ^^%NL%
if "%%a" == "main" (%NL%
2^>nul ;!= THIS SHOULD EXPAND TO NOTHING =! ^&^& (%NL%
SETLOCAL%NL%
^<nul ^>raw.txt set /p "=!args:~1!"%NL%
^>nul certutil -encodehex -f raw.txt b64.txt 0x40000001%NL%
type b64.txt%NL%
echo(%NL%
del /F /Q raw.txt b64.txt%NL%
ENDLOCAL%NL%
) ^|^| 1^>^&2 (%NL%
echo %ESC%[31mEnvironment incorrect.%ESC%[0m%NL%
echo %ESC%[31mLooks like you're trying to run this macro in CMD?%ESC%[0m%NL%
)%NL%
) else setlocal EnableDelayedExpansion ^& set args=
goto :eof
:HELP
FINDSTR /R "^#" "%~dpnx0"
echo,
goto :eof
REM. || (
#%=---------------- MACRO ----------------=%
#In MACRO, use !DELAYEDEXPANSION!
#%=---------------- USAGE ----------------=%
##############################################
## %$MACRO.b64encode% STRING_TO_ENCODE ##
##############################################
#All special characters should be ^escaped if not in quotes
#BANGS (!) should be escaped as ^^!
#or ^! if in quotes
#%=---------------- CERTUTIL ----------------=%
#CERTUTIL has a poorly documented -encodehex verb
#Usage:
#CertUtil [Options] -encodehex InFile OutFile [type]
# - 0x1: no headers
# - 0x40000000: no line terminators
# - 0x80000000: Unix-style endings \n instead or \r\n
#More testing can be found on https://www.dostips.com/forum/viewtopic.php?f=3&t=8521
)
The syntax is described using call init_b64encode.bat help
. Additional syntaxes and examples are given here:
Warning: DO NOT EDITthe batch file to look for correct syntax. Openit instead.
语法使用call init_b64encode.bat help
. 此处提供了其他语法和示例:
警告:请勿编辑批处理文件以查找正确的语法。而是打开它。
@echo off
setlocal DisableDelayedExpansion
FOR /F %%a in ('prompt $E ^& cmd /k ^<nul') do set ESC=%%a
::DO NOT EDIT the batch file to look for correct syntax
::open it instead
echo %ESC%[101;93mNEWLINES%ESC%[0m
echo %%$MACRO.b64encode%% this is a new^^^
^
line
echo %ESC%[101;93mBANGS (!)%ESC%[0m
echo %ESC%[94mNOT IN QUOTES%ESC%[0m
echo %%$MACRO.b64encode%% BANGBANGBANG^^^^!
echo %ESC%[94mIN QUOTES%ESC%[0m
echo %%$MACRO.b64encode%% "BANGBANGBANG^!"
echo %ESC%[94mWITH BANGS
echo THE CARET HAS TO BE ESCAPED FOUR TIMES
echo IF NOT IN QUOTES%ESC%[0m
echo %%$MACRO.b64encode%% this is a caret^^^^^^^^ ^^^^!
echo %%$MACRO.b64encode%% ^^^^!@#$%%%%^^^^^^^^^^^&*()
pause
Unfortunately, there are some limitations to the STRING_TO_ENCODE
:
The firstcharacter must not be any of the following:
<SPACE> <TAB> <0xFF> " =
because SET /P
is used to write to file without trailing newline.
不幸的是,有一些限制STRING_TO_ENCODE
:
第一个字符不能是以下任何一个:
<SPACE> <TAB> <0xFF> " =
因为SET /P
用于写入文件而没有尾随换行符。
Credits to @dbenhamfor mentioning the undocumented verbs of CERTUTIL
:
感谢@dbenham提及以下未记录的动词CERTUTIL
:
certutil -encodehex -f raw.txt b64.txt 0x40000001
The type 0x40000001
of the CryptBinaryToStringA
function is documented hereas:
该函数的类型0x40000001
在此处记录为:CryptBinaryToStringA
Do not append any new line characters to the encoded string. The default behavior is to use a carriage return/line feed (CR/LF) pair (0x0D/0x0A) to represent a new line.
Windows Server 2003 and Windows XP: This value is not supported.
不要将任何新行字符附加到编码字符串。默认行为是使用回车/换行 (CR/LF) 对 (0x0D/0x0A) 来表示新行。
Windows Server 2003 和 Windows XP:不支持此值。