Software downloads come with a published SHA-256 hash. Compare it with the hash of what you received.
What to build
A program that checks a message against an expected SHA-256 digest.
Requirements
- Compute the SHA-256 of the message (encoded as UTF-8) as 64 lower case hex digits.
- Print
okif it equals the expected digest (ignoring upper or lower case), otherwisecorrupted.
Input
Line 1: the message. Line 2: the expected digest in hex.
Output
ok or corrupted.
Constraints
The message has 1 to 100 characters.
Example
Input:
hello
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Output:
ok
Why it works
A hash changes completely when any part of the data changes, so equal hashes mean the data is the same (for practical purposes) and different hashes mean it was changed or damaged.
Examples
hello 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
ok
Hello 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
corrupted
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Import hashlib and use hashlib.sha256(text.encode()).hexdigest().
Hint 2
Compare it with the expected digest; make both lower case first.
Hint 3
Read two lines: the message and then the expected digest.
Solution
Show one correct solution (try it yourself first)
import hashlib
message = input()
expected = input().strip().lower()
digest = hashlib.sha256(message.encode("utf-8")).hexdigest()
print("ok" if digest == expected else "corrupted")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step