
September 11, 2026
10 min read
By Kokil Thapa | Last reviewed: September 2026
Cryptography fundamentals for engineers are not abstract math exercises. They are the concrete rules that keep passwords, payment callbacks, session cookies, and uploaded legal documents from leaking on a production Laravel or WordPress site. Most breaches I see in client audits trace back to basics: weak hashing, home-grown ciphers, keys stored in Git, or TLS misconfiguration—not exotic attacks. This guide maps security controls engineers actually ship to the primitives you need before touching REST API development or a client portal.
What Are Cryptography Fundamentals for Engineers?
Cryptography protects data in three states. Data at rest sits in MySQL or on disk. Data in transit crosses HTTPS, webhooks, and SMTP. Data in use lives in application memory during a request. Each state needs a different tool.
Engineers rarely implement algorithms from scratch. You choose primitives, wire them correctly, and manage keys. That discipline separates a secure booking portal from a breach waiting to happen.
Core primitives you must recognise
- Hashing — one-way digests (SHA-256, bcrypt, Argon2id). Used for passwords and integrity checks.
- Symmetric encryption — one shared secret encrypts and decrypts (AES-256-GCM, ChaCha20-Poly1305).
- Asymmetric encryption — key pairs for key exchange and small payloads (RSA, ECDH, Ed25519).
- Digital signatures — prove authenticity without hiding content (Ed25519, ECDSA).
- Key derivation — stretch passwords into keys safely (PBKDF2, scrypt, Argon2).
The NIST SP 800-57 key management guide remains the authoritative reference for key sizes and lifetimes. Bookmark it before you pick cipher suites for a new project.
How Do Cryptography Fundamentals for Engineers Handle Hashing vs Encryption?
Hashing and encryption solve different problems. Mixing them up is one of the most common mistakes on real client projects.
Hashing produces a fixed-length fingerprint. You cannot recover the original input. Password storage must use a slow, salted password hash—never SHA-256 alone. Encryption is reversible with the correct key. Use it when you must read the data later, such as encrypted passport numbers in a legal-tech portal.
| Goal | Use | Never use | Example |
|---|---|---|---|
| Store passwords | Argon2id or bcrypt | MD5, SHA-256 alone | Laravel Hash::make() |
| Verify file integrity | SHA-256 or SHA-512 | CRC32 for security | Composer package checksums |
| Encrypt database fields | AES-256-GCM | AES-ECB, home-grown XOR | Laravel encrypted casts |
| Sign webhooks | HMAC-SHA256 | Plain SHA-256 of body | Stripe-style signatures |
| Exchange session keys | ECDH + AEAD | RSA PKCS#1 v1.5 padding | TLS 1.3 handshake |
Password hashing in Laravel 13
Laravel 13 on PHP 8.3+ defaults to bcrypt. You can switch the driver to Argon2id when libsodium is available. The framework handles salting automatically.
/* config/hashing.php */
'driver' => env('HASH_DRIVER', 'argon2id'),
/* In a Form Request or service class */
use Illuminate\Support\Facades\Hash;
$hash = Hash::make($plainPassword);
Hash::check($plainPassword, $hash); /* constant-time compare */
Test generated hashes with the password generator tool for length and entropy—not for production secrets, but to validate policy rules before you enforce them in code.
Field-level encryption
When a column must be readable after storage, use authenticated encryption. AES-GCM appends an authentication tag that detects tampering. Laravel's encrypter wraps OpenSSL and expects a 32-byte key in APP_KEY.
use Illuminate\Support\Facades\Crypt;
$encrypted = Crypt::encryptString('PAN-123456789');
$plain = Crypt::decryptString($encrypted);
Rotating APP_KEY without a migration plan locks you out of existing ciphertext. Plan key versioning before you encrypt production rows. Cloud KMS patterns are covered in the GCP Cloud KMS fundamentals guide.
Which Cryptography Fundamentals for Engineers Apply to Laravel and PHP 8.5?
PHP 8.5 ships with OpenSSL and sodium extensions enabled on most production hosts I manage. Laravel 13 builds on both. Symfony 8.1 projects follow the same rules with different facades.
Your job is configuration and boundary design—not low-level cipher code. Focus on these integration points.
Session and cookie security
Sessions identify users. Encrypt session payloads at rest when you store them in Redis 8.10 or a database. Mark cookies Secure, HttpOnly, and SameSite=Lax unless cross-site OAuth requires None.
/* config/session.php */
'encrypt' => true,
'secure' => env('SESSION_SECURE_COOKIE', true),
'http_only' => true,
'same_site' => 'lax',
API tokens with Sanctum
Personal access tokens should be stored as hashes in the database. Laravel Sanctum shows only the plain token once at creation. That pattern mirrors how Stripe treats secret keys.
Pair token auth with rate limiting and HTTPS-only routes. Details overlap with GraphQL API design fundamentals, but the crypto layer stays identical: TLS outside, HMAC or signed JWTs at the edge when needed.
libsodium for greenfield crypto
When you are outside Laravel helpers, prefer sodium over composing raw OpenSSL calls. It is harder to misuse.
$key = sodium_crypto_secretbox_keygen();
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox($message, $nonce, $key);
$plain = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
The PHP sodium extension manual documents every constant. Read it before you touch nonce sizes or key lengths.
What Production Mistakes Break Cryptography Fundamentals for Engineers?
Theory is easy. Production breaks when shortcuts meet real traffic. These failures show up repeatedly on audits and incident calls.
- Hard-coded secrets in Git. API keys in
.env.example, payment salts in controllers, old keys in commented blocks. Use environment variables and rotate on leak. - Reused IVs or nonces. AES-GCM with a repeated nonce destroys confidentiality. Always generate a fresh random IV per encryption operation.
- Logging ciphertext or tokens. Debug logs during Khalti or eSewa callback debugging have exposed live secrets. Redact before write.
- Missing TLS on internal hops. Even server-to-server calls behind a VPC deserve HTTPS when credentials travel. See TCP/IP fundamentals for DevOps for network layering context.
- Trusting client-side crypto alone. JavaScript password hashing before POST does not replace server-side Argon2id. Attackers bypass the browser.
On legal-tech portals such as Mijar Law Associates, uploaded PDFs need access control plus encryption at rest on the filesystem or object store. Cryptography without authorisation still leaks files through IDOR bugs.
Webhook signature verification
Payment gateways sign callback bodies. Verify before you mark an order paid.
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
$expected = hash_hmac('sha256', $payload, $webhookSecret);
if (! hash_equals($expected, $signature)) {
abort(401, 'Invalid signature');
}
Use hash_equals() for every secret comparison. Early returns on length mismatch defeat timing attacks. Encode test payloads with the Base64 encoder and decoder when you build fixture files—not for live secrets.
Certificate and TLS hygiene
Let's Encrypt on Ubuntu 24 with Certbot is standard on servers I administer. Auto-renew via cron. Disable TLS 1.0 and 1.1. Prefer TLS 1.3 cipher suites.
Apache or Nginx termination is documented in Linux system administration services. Misconfigured chain files cause mobile browser failures that look like application bugs.
How Should Engineers Apply Cryptography Fundamentals for APIs and Payment Integrations?
Nepal-facing platforms often integrate eSewa, Khalti, IME Pay, and ConnectIPS alongside Stripe or PayPal. Each gateway documents its own signing scheme. The crypto pattern is the same: shared secret or public key, canonical payload, HMAC or RSA verify.
On a production Laravel eCommerce system, I treat payment callbacks as untrusted input until signature verification passes. Idempotency keys prevent duplicate captures when gateways retry webhooks.
Design checklist for REST APIs
- Enforce HTTPS with HSTS on public endpoints.
- Issue short-lived access tokens; rotate refresh tokens.
- Store only hashed API keys; show plain text once at creation.
- Sign outbound webhooks; document verification for integrators.
- Encrypt PII columns that regulations or client contracts require.
- Back up encrypted data and keys on separate paths.
Enterprise portals with document sharing—like those built under enterprise application development—need encryption plus audit logs. Crypto protects confidentiality; logs prove who accessed a file.
LDAP and directory auth introduce another layer. Read LDAP fundamentals alongside this page when Active Directory or FreeIPA handles identity and your app still encrypts data at rest.
Randomness and entropy
Never call rand() for security values. Use random_bytes() or random_int() in PHP. Laravel's Str::random() wraps secure generators.
$token = bin2hex(random_bytes(32)); /* 256-bit hex token */
$otp = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
Validate JSON webhook fixtures with the JSON formatter before they enter your test suite. Broken encoding has caused signature mismatches that teams chased for hours.
The OWASP Cryptographic Storage Cheat Sheet aligns with every checklist above. Treat it as a pre-release gate for new features that touch secrets.
Key Takeaways
- Hash passwords with Argon2id or bcrypt; never encrypt data you only need to verify.
- Use AES-256-GCM or ChaCha20-Poly1305 for reversible field encryption, with a unique nonce every time.
- Keep keys in environment variables or KMS—never in Git, never in client-side JavaScript alone.
- Verify webhook and payment callbacks with HMAC or documented signatures before changing order state.
- TLS 1.3 protects data in transit; it does not replace application-layer encryption for sensitive columns.
- Audit logs and access control complete cryptography—ciphers alone do not stop authorised abuse.
People Also Ask
What is the difference between encoding and encryption?
Encoding transforms data for transport or storage—Base64, hex, URL encoding—and anyone can reverse it without a secret. Encryption requires a key and is designed to resist recovery without that key. Developers confuse the two because both produce unreadable strings. Use encoding for compatibility; use AEAD ciphers when confidentiality matters.
Should engineers build custom encryption algorithms?
No. Custom ciphers fail against modern analysis within hours. Production systems should call vetted libraries—OpenSSL, libsodium, Laravel Crypt—and follow published parameters. Your differentiation is key management and threat modelling, not a new block cipher.
How often should encryption keys be rotated?
Rotate when staff leave, after suspected compromise, or on a schedule your risk policy defines—often 90 to 365 days for data-encryption keys. TLS certificates typically renew every 90 days with Let's Encrypt. Plan dual-key periods so old ciphertext remains decryptable during migration.
Is HTTPS enough to secure an API?
HTTPS is necessary but not sufficient. It protects bytes on the wire. It does not validate business logic, prevent SQL injection, or encrypt database columns. Pair TLS with authentication, authorisation, input validation, and hashed or encrypted storage for secrets and PII.
Ship Cryptography You Can Maintain
Cryptography fundamentals for engineers boil down to picking the right primitive, using maintained libraries, and operating keys safely across deploys. Master hashing versus encryption, wire Laravel's built-ins correctly, verify every payment webhook, and treat TLS as the floor—not the ceiling. When you need a portal that handles documents, payments, and compliance together, review the Notary Nepal portfolio case or reach out via contact us to discuss custom software with proper crypto boundaries. Solid fundamentals today prevent emergency key rotations tomorrow.
Frequently Asked Questions
0 Comments
Leave a comment
Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

