1

I just want to get the SHA256 checksum/hash of a string in my batch script using the Windows inbuilt certUtil utility.

I mean, I know that we can use certUtil for calculcating hashes of a file, but I just want it to calculate the hash of a string inside the batch script itself and store it as a variable like %hash%. The string will also be a variable basically like %var%.

Is there a simple way to do that?

Alternative/complex Approach:

I know a workaround in which we can write the variable into a file using:

echo %var% >>example.txt

And then calculating the hash of this file using:

CertUtil -hashfile "example.txt" SHA256

But this thing has its own set of problems:

  • Firstly using >> also presses an Enter after writing %var% in the file, thereby changing the entire hash.
  • Also I can't get the hash into the variable %hash% in this method. I tried everything in here, but can't get anything to work. (I'm a noob at batchfile programming)

Is there a simple way to do this?

  • 1
    `CertUtil -hashfile` does exactly that, it provides a hash for a file, it does not encode a string. I'd advise that you identify a utility, or scripting/programming mechanism, which provides the function you require of it instead. – Compo Dec 15 '21 at 15:33
  • 1
    Using file redirection does not create a CRLF at the end of your file. The `ECHO` command is doing that. – Squashman Dec 15 '21 at 15:41
  • 1
    Incidentally, `>>` is not pressing `[ENTER]`, the enter, i.e. CRLF is part of the function of `ECHO`. There are many questions on this site which explain and show methods of printing without the CRLF. Please use the search facility to identify one, and adapt it as needed. – Compo Dec 15 '21 at 15:42
  • Please take the [tour], visit the [help] and read [ask] before you ask another ([similar](https://stackoverflow.com/q/70359480)) question! – aschipfl Dec 15 '21 at 15:46
  • 1
    Also, _(although possibly not relevant, once you've found out how to forego the CRLF)_, currently you are redirecting the expanded variable content followed by a single space character to the file, so have included an additional unwanted character too. – Compo Dec 15 '21 at 17:49
  • 2
    You can use something like `echo | set /p dummyValue="Some string or another">test.txt` to create a text file without a trailing space or CRLF. – Anon Coward Dec 16 '21 at 04:29

1 Answers1

1

Here is the one-liner that you're looking for:

echo|set /p="foobar" > %TMP%/hash.txt |certutil -hashfile %TMP%/hash.txt SHA256 | findstr /v "hash"

The details of how to remove the echo new line can be found here.

Nelson
  • 2,040
  • 17
  • 23