SHA-256 Implementation - Problem

Implement the SHA-256 cryptographic hash algorithm from scratch following the official NIST FIPS 180-4 specification.

SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function that takes an input message and produces a 256-bit (32-byte) hash value, typically rendered as a 64-character hexadecimal string.

Your implementation must handle:

  • Message preprocessing (padding)
  • Parsing the message into 512-bit chunks
  • Hash computation using the SHA-256 compression function
  • Producing the final hash digest

The function should take a string input and return the SHA-256 hash as a lowercase hexadecimal string.

Note: This is an educational exercise. In production, always use well-tested cryptographic libraries.

Input & Output

Example 1 — Simple Input
$ Input: message = "abc"
Output: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
💡 Note: The string 'abc' is converted to bytes, padded according to SHA-256 specification, processed through 64 rounds of hash computation, and produces the standard SHA-256 hash for 'abc'.
Example 2 — Empty String
$ Input: message = ""
Output: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
💡 Note: An empty string gets padded to 512 bits (just the padding bit and length) and produces the well-known SHA-256 hash of empty input.
Example 3 — Longer Input
$ Input: message = "hello world"
Output: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
💡 Note: The phrase 'hello world' demonstrates SHA-256 processing a longer input that still fits within a single 512-bit block after padding.

Constraints

  • 0 ≤ message.length ≤ 106
  • Message contains only ASCII characters
  • Output must be lowercase hexadecimal

Visualization

Tap to expand
INPUTALGORITHMRESULTMessage Input"abc"Raw bytes: 61 62 63Length: 3 bytes1PreprocessingAdd padding bitPad to 512 bits2Hash Computation64 rounds per blockBitwise operations3Final DigestCombine hash valuesFormat as hexSHA-256 Hashba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad64 hex characters256 bits totalKey Insight:SHA-256 transforms any input into a fixed 256-bit digest through standardizedpreprocessing, block-wise processing, and cryptographic compression functions.TutorialsPoint - SHA-256 Implementation | Direct Implementation
Asked in
Microsoft 15 IBM 12 Coinbase 8 PayPal 6
8.5K Views
Medium Frequency
~45 min Avg. Time
230 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen