1

Given a string in linux str, how can I calculate SHA256 (in size of 32 bytes) of this string ?
I looking for a way such then if I will compare this result to openssl dgst -sha256 str.txt (Assuming the file str.txt contains the string str).

I know that sha256sum do it, but i don't sure how to require the result to be 32 bytes.

1
  • Did you try it? If yes, did you get anything else than 32 bytes (256 bits)? Usually a SHA256 should have exactly that size. Commented Nov 10, 2022 at 21:35

1 Answer 1

4
$ printf str | sha256sum | cut -c-64
8c25cb3686462e9a86d2883c5688a22fe738b0bbc85f458d2d2b5f3f667c6d5a

printf str prints "str" without any newline characters. sha256sum computes the sha256 and outputs it followed by blanks and hyphen. cut -c-64 is there to make sure that only the first 64 hex characters of the hash are printed.

If you need the raw bytes (not the hex encoded bytes), you can append xxd -r -p to the pipeline. It will convert hexadecimal strings into raw binary.

The result matches that of openssl:

$ printf str | openssl dgst -sha256 -
SHA2-256(stdin)= 8c25cb3686462e9a86d2883c5688a22fe738b0bbc85f458d2d2b5f3f667c6d5a
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.