SHA-256
- C course
- Advanced
- Lesson 56/83
- 5 min
Learn hashing with SHA-256.
What is SHA-256?
SHA-256 is a standard cryptographic hash function that produces a 32-byte digest. It is used via OpenSSL's EVP interface. You create a context with EVP_MD_CTX *ctx = EVP_MD_CTX_new();.
The flow: initialize with EVP_DigestInit_ex(ctx, EVP_sha256(), NULL), feed data with EVP_DigestUpdate(ctx, data, len), get the digest with EVP_DigestFinal_ex(ctx, digest, &len). When done, clean up with EVP_MD_CTX_free(ctx). The digest is written into unsigned char digest[EVP_MAX_MD_SIZE]. For testing, keeping the output constant is enough.
The SHA-256 call pattern
The typical flow: EVP_MD_CTX *ctx = EVP_MD_CTX_new();, EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);, EVP_DigestUpdate(ctx, "abc", 3);, EVP_DigestFinal_ex(ctx, digest, &len);, EVP_MD_CTX_free(ctx);. digest is the 32-byte digest.
For testing, printing printf("sha256 done\n") is safer than printing the digest; even though the digest bytes are fixed, printing them is environment-dependent. This keeps the output deterministic. In production you print the digest as hex.
Practice Compute SHA-256
Create a context with EVP_MD_CTX *ctx = EVP_MD_CTX_new();. Call EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);, EVP_DigestUpdate(ctx, "abc", 3);, unsigned char digest[EVP_MAX_MD_SIZE]; unsigned int len = 0; EVP_DigestFinal_ex(ctx, digest, &len);, EVP_MD_CTX_free(ctx);. printf("sha256 done\n");.
Starter code
#include <stdio.h>
#include <openssl/evp.h>
// Create sha256 context
// Feed data and get digest
// Print done
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <openssl/evp.h>
int main(void) {
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);
EVP_DigestUpdate(ctx, "abc", 3);
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int len = 0;
EVP_DigestFinal_ex(ctx, digest, &len);
EVP_MD_CTX_free(ctx);
printf("sha256 done\n");
return 0;
}Expected output
sha256 done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match SHA-256 parts
| Term | Meaning |
|---|---|
EVP_MD_CTX_new |
Create context |
EVP_DigestInit_ex |
Initialize |
EVP_DigestUpdate |
Feed data |
EVP_DigestFinal_ex |
Get digest |
2 How many bytes is the SHA-256 digest?
- 16 bytes
- 24 bytes
- 64 bytes
- 32 bytes Correct answer
Explanation: SHA-256 produces a 32-byte digest.
3 EVP_DigestInit_ex
EVP_DigestInit_ex(ctx, ____, NULL);
EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);
Explanation: EVP_sha256() selects the SHA-256 algorithm.