Information Security 19 min read

Implementing the SHA-256 Hash Algorithm in PHP from Scratch

This article explains the theory behind cryptographic hash functions and provides a complete PHP implementation of the SHA‑256 algorithm, detailing each processing step—from converting strings to binary to final compression—along with supporting helper functions and reference tables.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Implementing the SHA-256 Hash Algorithm in PHP from Scratch

Hash functions (also called message digests) map arbitrary input to a fixed‑length fingerprint; in PHP the built‑in hash() function can compute them, but this article walks through the SHA‑256 algorithm step by step.

The article lists the SHA family algorithms published by NIST, showing input size, block size, and output length.

It then defines a PHP class Algorithm with a public method sha256(string $str): string that orchestrates seven processing steps.

Member properties $originLen , $bits , $blocks , and constant arrays H (square‑root constants) and K (cube‑root constants) are introduced.

Helper methods are provided for converting integers to bit arrays, right‑shifting, right‑rotating, bitwise NOT, AND, XOR, addition, printing bits, and converting bits to hexadecimal.

Step 1 converts the input string to a binary array; step 2 appends a single 1 bit; step 3 pads with zeros so the length becomes a multiple of 512 while reserving 64 bits for the original length; step 4 appends the 64‑bit length; step 5 splits the padded data into 512‑bit blocks and extends each block to 2048 bits by adding 48 zero‑filled lines; step 6 expands the block words 16‑63 using the SHA‑256 schedule functions; step 7 performs the main compression loop using the constants H and K and finally produces the hash by concatenating the updated state variables and converting them to hexadecimal.

The implementation is verified by hashing the string “hello world”, which yields the same result as PHP’s native hash('sha256', 'hello world') function.

phpinformation securitycryptographyhash algorithmBinary OperationsSHA-256
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.