用于将文本转换为md5sum值的批处理文件

时间:2016-02-03 13:25:33

标签: batch-file md5sum

我需要创建一个窗口"批处理"文件包含以下条件。 将文本转换为md5sum值 我尝试使用下面的.bat文件。但是没有工作

@echo off

setlocal ENABLEDELAYEDEXPANSION

set hashmd5=$(echo -n welcome1 | md5sum | cut -c 1-32);

printpass=$printpass"#####MD5: echo.%%hashmd5 "\n"

2 个答案:

答案 0 :(得分:1)

检查MD5.bat

@echo off 
set "string=The quick brown fox jumps over the lazy dog"
(break|set/p=%string%)>~
call md5 ~ m5sting
echo %m5sting%
exit /b 0

虽然无论我做什么,我都无法获得与将字符串转换为MD5的一些在线工具相同的结果(但通常它们彼此不同)。这将始终在字符串的末尾放置一个EOF字符,因为它转换文件而不是纯字符串。

目前,上面的脚本给出了与(在rojo的评论中看到的)相同的结果 powershell "[Security.Cryptography.HashAlgorithm]::Create('MD5').ComputeHash([Text.Encoding]::UTF8.GetBytes('%string%')) | %%{write-host -n $_.tostring('x2')}"虽然仍然不同于PHP和一些Javascript库

答案 1 :(得分:1)

这是另一个版本,也使用certutil生成MD5哈希。它将为您提供文件或字符串参数的MD5sum,并且可以通过管道接受一行输入。此解决方案不依赖于随附的帮助程序脚本。

@echo off & setlocal

set "plaintext=%~1"
set "file=%temp%\%~n0.tmp"
set md5=

if "%~1"=="/?" (
    echo Usage: %~nx0 file^|string
    echo    or: command ^| %~nx0
    echo;
    echo Example: set /P "=password" ^<NUL ^| %~nx0
    goto :EOF
)

if not defined plaintext set /P "plaintext="

if exist "%plaintext%" (
    set "file=%plaintext%"
) else for %%I in ("%file%") do if %%~zI equ 0 (
    <NUL >"%file%" set /P "=%plaintext%"
)

for /f "skip=1 delims=" %%I in ('certutil -hashfile "%file%" MD5') do (
    if not defined md5 set "md5=%%I"
)

2>NUL del "%temp%\%~n0.tmp"

echo %md5: =%

仅仅因为我觉得这是挑战,这是另一个可以通过管道接受多行的版本,以及来自文件重定向的输入。 (当缓冲区为空时,阻止StdIn.AtEndOfStream提示键盘输入并不容易。)

@if (@CodeSection == @Batch) @then
@echo off & setlocal & goto main

:usage
echo Usage: %~nx0 file^|string
echo    or: command ^| %~nx0
echo    or: %~nx0 ^< file
echo;
echo Example: set /P "=password" ^<NUL ^| %~nx0
goto :EOF

:main
set "plaintext=%~1"
set "file=%temp%\%~n0.tmp"
set md5=

rem // check for input via the pipeline; timeout nearly instantly if none
start /b "" cscript /nologo /e:JScript "%~f0" "%file%" watcher
cscript /nologo /e:JScript "%~f0" "%file%"

if "%~1"=="" for %%I in ("%file%") do if %%~zI equ 0 goto usage
if "%~1"=="/?" goto usage

if not defined plaintext set /P "plaintext="

if exist "%plaintext%" (
    set "file=%plaintext%"
) else for %%I in ("%file%") do if %%~zI equ 0 (
    <NUL >"%file%" set /P "=%plaintext%"
)

for /f "skip=1 delims=" %%I in ('certutil -hashfile "%file%" MD5') do (
    if not defined md5 set "md5=%%I"
)

2>NUL del "%temp%\%~n0.tmp"

echo %md5: =%
goto :EOF

@end // end Batch / begin JScript hybrid code

var fso = WSH.CreateObject('scripting.filesystemobject');
if (WSH.Arguments.Length > 1) {
    WSH.Sleep(1);
    if (!fso.FileExists(WSH.Arguments(0)))
        WSH.CreateObject('WScript.Shell').Exec('taskkill /im "cscript.exe" /f');
} else if (!WSH.StdIn.AtEndOfStream) {
    var file = fso.CreateTextFile(WSH.Arguments(0), 1);
    file.Write(WSH.StdIn.ReadAll());
    file.Close();
}