Base64编码“字符串”-命令行Windows?

0dxa2lsx  于 2023-03-19  发布在  Windows
关注(0)|答案(8)|浏览(107)

我已经找到了许多在Windows上使用命令行对整个文件进行base64编码的方法,但似乎找不到一种简单的方法来使用命令行实用程序对“字符串”进行批编码。
如何做到这一点,例如在批处理文件中使用?

z0qdvdin

z0qdvdin1#

这是一个PowerShell一行程序,你可以从cmd控制台运行,它将Base64编码一个字符串。

powershell "[convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(\"Hello world!\"))"

它可能没有npocmaka的解决方案快,但你可以set a console macro with it

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

注意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

或者,如果您更喜欢批处理+ 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)));

编辑:@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>
mqkwyuun

mqkwyuun2#

根据对问题的评论,您可以使用certutil.例如,

certutil -encode raw.txt encoded.txt

certutil -f -encode raw.txt encoded.txt

-f表示“强制覆盖”。否则,如果输出文件(上面的encoded.txt)已经存在,你会得到一个错误。
但是,这会将输出格式化为encoded.txt文件,就像它是证书PEM文件一样,包含开始和END行,并在字符max处拆分行。因此,您需要在批处理场景中做进一步的处理,如果字符串很长,还需要做一些额外的工作。

cunj1qz1

cunj1qz13#

如果您安装了OpenSSL for Windows,则可以使用此代码对字符串“Hello”进行编码:

echo | set /p="Hello" | openssl base64

| set /p=用于抑制echo通常输出的换行符。
这将产生与bash中的以下内容相同的结果:

echo -n 'Hello' | openssl base64

输出:

SGVsbG8=
7gyucuyw

7gyucuyw4#

This script可以在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"

这个函数只接受一个参数--你想编码为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>
3qpi33ja

3qpi33ja5#

这可以(技术上)完全在批处理中完成,方法是从批处理中创建一个加密\解密VBS脚本,该脚本可以使用您希望对其数据进行加密\解密的变量的名称进行调用。
注:以下脚本为独立子程序。
密码或其他变量的混合批处理Vbs加密器/解密器。对存储在定义文件中的数据执行操作-不创建文件。
注意:vbs中的文件扩展名与保存密码/文本的文件类型相匹配。
要使用此程序,请使用要设置的变量名和要执行的偏移量来调用它。
但是,主程序接受用户输入:

Set /p YourVariableName=

将输入存储到文件

ECHO %YourVariableName%>YourSaveFile.txt

调用时使用正偏移(即:+26)进行加密,并将等效的负偏移量设置为解密。(IE:-26)

CALL "Insert Filepath To Encrypter.bat Here" YourVariableName +26

加密器. 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
    ```
afdcj2ne

afdcj2ne6#

请注意doskey不能在批处理脚本中使用--只能在控制台中使用。如果您想在批处理脚本中使用它,请创建一个函数
或使用macro

@echo off
====SETLOCAL DisableDelayedExpansion EnableExtensions

REM Initalize
set ^"LF=^
%===EXPANDS TO NOTHING===%
"
::\n is an escaped LF + caret for line continuation
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

REM MACRO
set ^"$b64.encode=FOR %%$ in (%%$ MainMacro) do if "%%$" == "MainMacro" (%\n%
    ^>nul %__APPDIR__%certutil.exe -f -encodehex args.tmp proc.tmp 0x40000001%\n%
    type proc.tmp%\n%
    echo(%\n%
    del args.tmp proc.tmp%\n%
) 2^>nul ELSE ^<nul ^>args.tmp set/p="

REM EXAMPLES
%$b64.encode%"=I WILL FAIL (string cannot start with =)"
%$b64.encode%^"     leading spaces/tabs will be stripped%\n%
but other characters are%\n%
OK!%\n%
;%%~dp$^&^|"""""""

限制

字符串不能以<SPACE> <TAB> <0xFF> =开始
因为SET /P用于write without trailing CRLF

@dbenham提到了undocumented verbs of CERTUTILCryptBinaryToStringA函数的类型0x40000001记录为:

不要在编码字符串后追加任何新行字符。默认行为是使用回车/换行符(CR/LF)对(0x 0 D/0x 0A)表示新行。

Windows Server 2003和Windows XP操作系统:不支持此值。

q8l4jmvw

q8l4jmvw7#

最优,可靠...使用Powershell。不过,在文本长度上有一些限制。
统一码

@echo off
    set "string=Everything will be fine"
    for /f "tokens=* delims=" %%i in ('powershell       [convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes("""%string%"""^)^)') do set "encoded=%%i"
    echo %encoded%

UTF8基因

@echo off
    set "string=Everything will be fine"
    for /f "tokens=* delims=" %%i in ('powershell       [convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("""%string%"""^)^)') do set "encoded=%%i"
    echo %encoded%
bbuxkriu

bbuxkriu8#

这对我很有效,certutil不会生成额外的行,它会将文件data.txt的内容转换为base64并将其保存到新文件data.b64中。

certutil -encode data.txt tmp.b64 && findstr /v /c:- tmp.b64 > data.b64 && del tmp.b64

相关问题