C
Summary - Cryptography
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.
Exercise 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");.
Show example 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;
}
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.
Test yourself
-
Which is the correct usage distinction?
- Encrypt first, then hash
- Hash first, then encrypt
- Only random numbers
- Hash for integrity, encrypt for confidentiality
Show answer
Hash for integrity, encrypt for confidentiality — Hash gives integrity, encrypt gives confidentiality; used together.
-
Match crypto tools
- SHA-256
- Digest
- HMAC
- Authentication
- AES
- Encryption
- urandom
- Random
Next lesson: ASCII and UTF-8