0

I use .bat (generate.bat) to convert a string to sha256 encoded in base64

<nul set /p =%1 | openssl dgst -sha256 -binary 2>NUL | openssl base64 2>NUL

when I use generate.bat :

generate.bat foobar

the output is :

qjV6SxGt0Ex4fN0XvaqMGbJCxFVF9ksSlLYfmtCR0G4=

but when I execute :

generate.bat "foobar"

then the output is :

w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI=

this means that "foobar" and foobar are not the same.

Why ? and what's the difference ?

Thanks

Titouan56
  • 6,932
  • 11
  • 37
  • 61

2 Answers2

1

The unquoting suggested by @npocmaka is elegant and should work.

Here is an alternative method:

@echo off
setlocal

Set TXT=%1
CALL :dequote TXT

echo %TXT% | openssl dgst -sha256 -binary 2>NUL | openssl base64 2>NUL

goto xit

::  from http://ss64.com/nt/syntax-dequote.html
:DeQuote
for /f "delims=" %%A in ('echo %%%1%%') do set %1=%%~A
Goto :eof

:xit
endlocal
Axel Kemper
  • 10,544
  • 2
  • 31
  • 54
1

Windows CMD treats the enclosing parameters as part of the parameter (part of the string).

If you want outer quotes to always be part of the string (even if they were not supplied on the command line), then you can do the following:

<nul set /p ^"="%~1"^" | openssl dgst -sha256 -binary 2>NUL | openssl base64 2>NUL

If you don't want the enclosing quotes to be included in the string, then you can generally do:

<nul set /p "=%~1" | openssl dgst -sha256 -binary 2>NUL | openssl base64 2>NUL

The above strategy generally works, but the SET /P hack for printing a string without \r\n at the end does not work if the string starts with space or =.

This is kind of a nasty problem. I imagine the best option is to switch to using powerShell. (I'm not very familiar with PowerShell, so I don't know the syntax).

If you really want to use batch, you can use a fairly complicated process to print any string without \r\n, described at https://stackoverflow.com/a/19468559/1012053

Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390