Summary - Cryptography
- C course
- Advanced
- Lesson 60/83
- 5 min
Combine SHA-256 and HMAC to write a message authenticator.
Cryptography summary
You learned the cryptography toolkit: hash for digests, SHA-256 for standard hashing, HMAC for keyed authentication, AES for symmetric encryption, /dev/urandom for secure random. These are the core of data integrity, authenticity and confidentiality.
In this summary we will combine SHA-256, HMAC and urandom into a crypto preparation app. Using them together shows how a real security flow is built. The output is deterministic: we print a fixed ready message.
Practice Prepare crypto
Compute SHA-256 with 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);. Compute HMAC with HMAC(EVP_sha256(), "key", 3, (const unsigned char *)"msg", 3, digest, &len);. Open and close urandom with int fd = open("/dev/urandom", O_RDONLY); if (fd >= 0) close(fd);. printf("crypto ready\n");.
Starter code
#include <stdio.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <fcntl.h>
#include <unistd.h>
// Compute sha256 and hmac
// Open and close urandom
// Print ready
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <fcntl.h>
#include <unistd.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);
HMAC(EVP_sha256(), "key", 3, (const unsigned char *)"msg", 3, digest, &len);
int fd = open("/dev/urandom", O_RDONLY);
if (fd >= 0) close(fd);
printf("crypto ready\n");
return 0;
}Expected output
crypto ready
Next steps
You completed cryptography basics. These tools are the core of authentication systems, secure file transfer and encrypted communication. SHA-256 for integrity, HMAC for authenticity, AES for confidentiality, urandom for key generation.
Next topics: TLS for network security, key derivation (PBKDF2), asymmetric encryption (RSA, ECC). In production you combine these tools to build end-to-end secure systems. Always use proven libraries (OpenSSL, libsodium); do not roll your own crypto.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is the correct usage distinction?
- Encrypt first, then hash
- Hash first, then encrypt
- Only random numbers
- Hash for integrity, encrypt for confidentiality Correct answer
Explanation: Hash gives integrity, encrypt gives confidentiality; used together.
2 Match crypto tools
| Term | Meaning |
|---|---|
SHA-256 |
Digest |
HMAC |
Authentication |
AES |
Encryption |
urandom |
Random |