user20007266
user20007266

Reputation: 87

How to calculate SHA256 of a string

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.

Upvotes: 0

Views: 1584

Answers (1)

knittl
knittl

Reputation: 265807

$ 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

Upvotes: 3

Related Questions