Password hashing, salts & salt rounds
We never store passwords, not even encrypted. We store a one-way hash that is deliberately slow to compute, so a stolen database can't realistically be turned back into passwords.
What we use
- Argon2id by default: memory-hard, which makes GPU and ASIC cracking expensive. Minimum settings follow OWASP: 19 MiB memory, 2 iterations, 1 thread.
- bcrypt where a platform requires it, with a cost factor (salt rounds) of 12 or higher.
- PBKDF2-HMAC-SHA256 with 600,000 iterations only where FIPS compliance is mandated.
Salts, rounds and pepper, explained
- Salt: a unique, random 16-byte value generated for every password and stored with the hash. Two users with the same password get completely different hashes, which defeats precomputed rainbow tables.
- Salt rounds (cost): bcrypt cost 12 means 212 = 4,096 rounds of key expansion, roughly 250 ms per hash. That's unnoticeable at login but slows an attacker to a crawl. We raise it as hardware gets faster.
- Pepper: an extra secret held in a key vault, never in the database. A database leak alone is not enough to start cracking.
- Rehash on login: when we raise the cost, each user's hash is upgraded automatically the next time they sign in.
import argon2 from 'argon2';
// OWASP minimum for Argon2id
const OPTIONS = {
type: argon2.argon2id,
memoryCost: 19456, // 19 MiB
timeCost: 2, // iterations
parallelism: 1,
};
export async function hashPassword(password) {
// A unique random salt is generated and embedded automatically
return argon2.hash(password, OPTIONS);
}
export async function verifyPassword(hash, password) {
const ok = await argon2.verify(hash, password);
// Upgrade old hashes when we raise the cost
if (ok && argon2.needsRehash(hash, OPTIONS)) {
await saveNewHash(await hashPassword(password));
}
return ok;
}
import bcrypt from 'bcrypt';
const SALT_ROUNDS = 12; // 2^12 = 4,096 rounds
const hash = await bcrypt.hash(password, SALT_ROUNDS);
const ok = await bcrypt.compare(password, hash); // constant-time
Anatomy of a stored bcrypt hash
What we never do: store plain-text or reversibly encrypted passwords, use fast hashes like MD5, SHA-1 or plain SHA-256, reuse salts, or email passwords to users. bcrypt only reads the first 72 bytes of input, so we cap password length accordingly or use Argon2id.
Password policy & brute-force protection
Our password rules follow NIST SP 800-63B, and the login endpoint is protected against guessing, credential stuffing and account discovery.
Policy & protections
- Minimum 8 characters (12 for admins), up to at least 64, with all characters and spaces allowed
- New passwords checked against known breached-password lists
- No forced periodic resets or arbitrary composition rules, which push users toward weaker passwords
- Rate limiting per IP and per account, with progressive delays and temporary lockout
- CAPTCHA after repeated failures
- Identical error messages and response times for "wrong password" and "no such user", so attackers can't discover valid accounts
- Users are alerted to new-device sign-ins and password changes
import rateLimit from 'express-rate-limit';
// Max 5 login attempts per 15 minutes per client
export const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 5,
standardHeaders: 'draft-7',
legacyHeaders: false,
message: { error: 'Too many attempts. Please try again later.' },
});
app.post('/api/login', loginLimiter, async (req, res) => {
const user = await findUserByEmail(req.body.email);
const ok = user && await verifyPassword(user.passwordHash, req.body.password);
// Same response whether the user exists or not
if (!ok) return res.status(401).json({ error: 'Invalid email or password' });
// ...
});
A second factor for every account that matters
A stolen password alone should never be enough. We build MFA into the applications we deliver and enforce it for administrators.
Passkeys & security keys
FIDO2 / WebAuthn passkeys are phishing-resistant because they are bound to the real domain. This is our first choice for admin and privileged users.
Authenticator apps
Time-based one-time codes (TOTP, RFC 6238). The TOTP secret is encrypted at rest, and one-time backup codes are hashed like passwords.
Step-up verification
Sensitive actions such as changing email, exporting data or approving payments require re-authentication, even within an active session.
SMS codes are offered only where users need them, never as the only factor for administrators, because SIM-swap attacks can intercept them.
Secure cookies, sessions & JWTs
After login, the session token is the key to the account, so we make it hard to steal and quick to expire.
How we handle sessions
- Tokens are stored in
HttpOnly,Secure,SameSitecookies, never inlocalStorage, where malicious scripts could read them - Session ID regenerated at login to prevent session fixation
- Idle timeout (typically 15–30 minutes) plus an absolute timeout
- Short-lived access tokens (15 minutes) with rotating refresh tokens. Reuse of an old refresh token revokes the whole session
- JWTs signed with RS256 or EdDSA, with
iss,audandexpalways checked and no sensitive data in the payload - Logout and password change invalidate sessions on the server
// Cookie that JavaScript cannot read and that is only sent over HTTPS
res.cookie('access_token', token, {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 15 * 60 * 1000, // 15 minutes
path: '/',
});
// Verify every claim, and only accept the algorithm we expect
import jwt from 'jsonwebtoken';
const payload = jwt.verify(token, PUBLIC_KEY, {
algorithms: ['RS256'],
issuer: 'https://auth.example.gov.in',
audience: 'portal-api',
});
Password reset & email verification
Recovery flows are a favourite target for attackers, so reset links are random, short-lived, single-use and never stored in readable form.
Our reset flow
- 256-bit random token from a cryptographically secure generator
- Only a SHA-256 hash of the token is stored, so a database leak can't be used to reset accounts
- Expires in 30 minutes and works only once
- The same message appears whether or not the email exists
- All active sessions are signed out after a reset, and the user is notified
import crypto from 'node:crypto';
const token = crypto.randomBytes(32).toString('base64url'); // sent by email
const tokenHash = crypto.createHash('sha256').update(token).digest('hex');
await db.passwordResets.insert({
userId: user.id,
tokenHash, // only the hash is stored
expiresAt: new Date(Date.now() + 30 * 60 * 1000),
usedAt: null,
});
Helmet & browser-level protection
Security headers tell the browser to block whole classes of attack, such as XSS, clickjacking and protocol downgrades. In Node.js we set them with helmet, and the equivalent configuration in other stacks. Our target is an A+ rating on Mozilla Observatory.
import helmet from 'helmet';
import cors from 'cors';
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
objectSrc: ["'none'"],
frameAncestors: ["'none'"],
upgradeInsecureRequests: [],
},
},
hsts: { maxAge: 63072000, includeSubDomains: true, preload: true }, // 2 years
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));
// Only our own front-end may call the API with credentials
app.use(cors({ origin: ['https://portal.example.gov.in'], credentials: true }));
app.disable('x-powered-by');
| Header | What it protects against |
|---|---|
| Content-Security-Policy | XSS and injected scripts, by allowing only approved sources |
| Strict-Transport-Security | HTTPS downgrade and cookie theft over plain HTTP |
| X-Content-Type-Options | MIME sniffing that turns uploads into scripts |
| X-Frame-Options / frame-ancestors | Clickjacking through hidden iframes |
| Referrer-Policy | Leaking URLs and tokens to other sites |
| Cross-Origin-Opener-Policy | Cross-window attacks and data leaks |
| Cross-Origin-Resource-Policy | Other sites embedding your private resources |
| Permissions-Policy | Unwanted access to camera, microphone and location |
| X-Powered-By (removed) | Revealing framework versions to attackers |
Validation, injection & file uploads
Every input is treated as untrusted. It is validated against a strict schema on the server, and never pasted into queries or HTML.
Our rules
- Server-side schema validation on every request (type, length, format), rejecting unknown fields
- Parameterised queries / ORM only, never string-built SQL, which prevents SQL injection
- Output encoding through framework auto-escaping, and sanitising any user HTML
- CSRF protection with SameSite cookies plus anti-CSRF tokens on state-changing requests
- SSRF protection: server-side outbound calls go only to an allow-list of hosts
File uploads
- File type checked by content (magic bytes), not just the extension
- Size limits, malware scanning and random file names
- Stored in private storage outside the web root and served through signed, expiring URLs
import { z } from 'zod';
const RegisterSchema = z.object({
name: z.string().trim().min(1).max(100),
email: z.string().email().max(254),
password: z.string().min(12).max(128),
}).strict(); // reject unexpected fields
app.post('/api/register', async (req, res) => {
const parsed = RegisterSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: 'Invalid input' });
const { name, email, password } = parsed.data;
// Values are sent separately from the SQL, so they can never run as code
await db.query(
'INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3)',
[name, email, await hashPassword(password)]
);
res.status(201).end();
});
Encryption in transit, at rest & per field
Disk-level encryption protects against stolen hardware. For sensitive personal data such as Aadhaar, PAN, bank details and health records, we add field-level encryption, so the data stays unreadable even to someone with database access.
Layers of encryption
- In transit: TLS 1.3 (1.2 minimum) with forward-secret ciphers and HSTS. Internal service-to-service traffic uses mTLS
- At rest: AES-256 for databases, disks, object storage and backups
- Field level: AES-256-GCM, which encrypts and detects tampering, with a unique IV for every value
- Envelope encryption: data keys are themselves encrypted by a master key in a KMS/HSM, and the master key never leaves it
- Searchable fields: HMAC-based blind indexes let us look up records without decrypting them
- Key rotation on a schedule and immediately if a key may be compromised
import crypto from 'node:crypto';
// 32-byte data key, unwrapped from the KMS at startup, never hard-coded
export function encrypt(plaintext, key) {
const iv = crypto.randomBytes(12); // unique per value
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const data = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag(); // detects tampering
return Buffer.concat([iv, tag, data]).toString('base64');
}
export function decrypt(payload, key) {
const buf = Buffer.from(payload, 'base64');
const decipher = crypto.createDecipheriv('aes-256-gcm', key, buf.subarray(0, 12));
decipher.setAuthTag(buf.subarray(12, 28));
return Buffer.concat([decipher.update(buf.subarray(28)), decipher.final()]).toString('utf8');
}
Keys, passwords & API tokens
A single leaked key can undo every other control, so secrets never live in code, chat messages or shared documents.
Stored in a vault
Production secrets live in a managed secret store (AWS Secrets Manager, Azure Key Vault, HashiCorp Vault) and are injected at runtime. .env files are for local development only and are never committed.
Blocked before commit
Secret scanning (such as gitleaks) runs on every commit and in CI. A detected secret blocks the merge, and we rotate it immediately.
Least privilege & rotation
Each service gets its own narrowly scoped credentials, with cloud workload identities preferred over long-lived keys. Credentials are rotated regularly and whenever people change roles.
Audit trails without leaking personal data
Logs let us detect and investigate incidents, but they must not become a second copy of your sensitive data.
What we log and how
- Security events: logins, failures, MFA changes, permission changes, data exports and admin actions
- Audit logs record who did what, when and from where
- Passwords, tokens, card numbers and ID numbers are automatically redacted
- Central, tamper-resistant storage, retained for at least 180 days, as CERT-In requires
- Server clocks synchronised to official NTP sources so event timelines are accurate
import pino from 'pino';
export const logger = pino({
redact: {
paths: [
'req.headers.authorization',
'req.headers.cookie',
'*.password',
'*.token',
'*.aadhaar',
'*.pan',
],
censor: '[REDACTED]',
},
});
logger.info({ userId, action: 'export.csv', ip }, 'Data export requested');
Dependency & supply-chain security
Most application code is open-source packages, and we treat them as part of our attack surface.
Our controls
- Lock files committed, and installs use
npm cifor exact, reproducible versions - Vulnerability audit in CI, where a high or critical finding fails the build
- Automated update pull requests through Dependabot or Renovate
- New packages reviewed for maintenance, popularity and licence before adoption
- Container images pinned by digest and scanned before deployment
- A Software Bill of Materials (SBOM) generated for every release
# Runs on every pull request
- run: npm ci # exact versions from the lock file
- run: npm audit --audit-level=high # fail on high or critical issues
- run: npx @cyclonedx/cyclonedx-npm --output-file sbom.json
- uses: gitleaks/gitleaks-action@v2 # block committed secrets
Access control & API security
Logging in proves who you are. Authorization decides what you can see and do, and it is checked on the server for every request. Broken object-level authorization is the number-one risk in the OWASP API Security Top 10.
Our rules
- Deny by default: every route requires authentication unless it is explicitly public
- Object-level checks: users can only access records they own or are permitted to see, which prevents IDOR attacks such as changing
/applications/1001to1002 - Role- and attribute-based access (RBAC / ABAC), with permissions defined centrally rather than scattered through the code
- API keys are scoped, hashed in storage, rotatable and revocable
- Request limits: body size caps, pagination limits and timeouts block abuse and denial-of-service attempts
- Webhooks are verified with HMAC signatures before being trusted
app.use(express.json({ limit: '100kb' })); // cap request size
// Permission check, defined once and reused
const can = (permission) => (req, res, next) =>
req.user.permissions.includes(permission) ? next() : res.sendStatus(403);
app.get('/api/applications/:id', requireAuth, async (req, res) => {
const record = await db.applications.findById(req.params.id);
// Object-level check: is this user allowed to see this record?
const allowed = record &&
(record.ownerId === req.user.id || req.user.permissions.includes('applications:read:any'));
if (!allowed) return res.sendStatus(404); // don't reveal that it exists
res.json(record);
});
app.delete('/api/users/:id', requireAuth, can('users:delete'), deleteUser);
// Verify webhook signatures before trusting the payload
const expected = crypto.createHmac('sha256', WEBHOOK_SECRET).update(rawBody).digest('hex');
const valid = signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
Locking down the database
The database holds the most valuable data, so it gets its own layers: private networking, least-privilege accounts and row-level isolation between tenants or departments.
Our controls
- Reachable only from the private network, never from the public internet
- Encrypted connections with full certificate verification (
sslmode=verify-full) - Separate database users for the application, migrations and reporting, each with only the permissions it needs
- Row-level security, so one tenant or department can never read another's data, even if there's a bug in the application
- Automated encrypted backups with point-in-time recovery
- Database audit logging for privileged and sensitive operations
-- Application runs as a restricted role: no superuser, no schema changes
CREATE ROLE app_user LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE;
GRANT SELECT, INSERT, UPDATE ON records TO app_user;
-- Row-level security: each request only sees its own tenant's rows
ALTER TABLE records ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON records
USING (tenant_id = current_setting('app.tenant_id')::uuid);
Protecting users in the browser
Web and portal front-ends are where users type their data, so we make sure nothing malicious can run there and nothing secret ships to the browser.
Our practices
- User content is inserted as text, never as raw HTML. Where HTML is required, it is sanitised with DOMPurify first
- A strict Content Security Policy blocks injected and inline scripts
- Third-party scripts are kept to a minimum and loaded with Subresource Integrity (SRI) hashes
- No API secrets in front-end code. Anything shipped to the browser is treated as public
- Sensitive data is never kept in
localStorage, and forms disable autofill for sensitive fields - Auto-logout on inactivity for portals handling citizen or financial data
import DOMPurify from 'dompurify';
// Safe by default: content is treated as text, never as code
element.textContent = userInput;
// When rich text is genuinely needed, sanitise it first
element.innerHTML = DOMPurify.sanitize(userHtml);
// React: avoid dangerouslySetInnerHTML, and if unavoidable, sanitise
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />
Android & iOS app security
Mobile apps run on devices we don't control, so we follow the OWASP Mobile Application Security Verification Standard (MASVS) and assume the device may be compromised.
Data on the device
- Tokens kept in iOS Keychain or Android Keystore, never in plain storage
- Biometric unlock backed by hardware keys
- Screenshots and app-switcher previews hidden on sensitive screens
Data in transit
- HTTPS only, with cleartext traffic disabled
- Certificate pinning for high-risk apps
- No secrets or API keys embedded in the app package
App integrity
- Code obfuscation and minification (R8 / ProGuard)
- Root and jailbreak detection where required
- Play Integrity and App Attest to block tampered apps
Hardened containers & infrastructure
Even if an attacker finds a flaw in the application, a hardened runtime limits what they can reach and do.
Runtime hardening
- Minimal base images, patched and pinned by digest
- Containers never run as root, with a read-only file system wherever possible
- All Linux capabilities dropped unless explicitly needed, and privilege escalation blocked
- CPU and memory limits on every service
- Network policies so services can only talk to what they need
- Servers hardened to CIS Benchmarks: SSH keys only, no root login, automatic security updates
# Small, patched base image pinned to an exact version
FROM node:22-alpine@sha256:<digest>
WORKDIR /app
COPY --chown=node:node package*.json ./
RUN npm ci --omit=dev
COPY --chown=node:node . .
# Never run as root
USER node
EXPOSE 3000
CMD ["node", "server.js"]
Automated security testing in every pipeline
Security checks run automatically on every change, long before manual penetration testing, so problems are caught when they're cheapest to fix.
# Static analysis on every pull request
- uses: github/codeql-action/init@v3
with:
languages: javascript
- uses: github/codeql-action/analyze@v3
- run: semgrep scan --config p/owasp-top-ten --error
# Dynamic scan against the staging deployment
- uses: zaproxy/action-baseline@v0.14.0
with:
target: 'https://staging.example.gov.in'
| Test | What it finds | When |
|---|---|---|
| SAST | Insecure code patterns, such as injection or weak crypto | Every commit |
| SCA | Known vulnerabilities in open-source packages | Every commit, plus daily |
| Secret scanning | Keys and passwords committed by mistake | Every commit |
| IaC scanning | Cloud and container misconfigurations | Every change |
| DAST | Runtime flaws in the running application | Every staging deploy |
| Penetration test | Business-logic and chained attacks | Before go-live and after major changes |
Privacy built into the data itself
To meet India's DPDP Act 2023 and similar laws, we limit how much personal data is visible, where it travels and how long it lives.
Techniques we apply
- Data minimisation: collect only the fields the service actually needs
- Masking: screens, exports and logs show only partial values, such as XXXX XXXX 1234
- Tokenisation: card and bank data replaced by tokens, so the real values never touch our systems
- Pseudonymisation: keyed hashes replace identities before data is used for analytics, AI or testing
- Consent records: what was agreed, for which purpose, and when, ready for audit
- Retention jobs: scheduled deletion once data passes its retention period, plus erasure on request
import crypto from 'node:crypto';
import cron from 'node-cron';
// Show only what's needed
export const maskAadhaar = (n) => 'XXXX XXXX ' + n.slice(-4);
export const maskPhone = (p) => p.slice(0, 2) + '******' + p.slice(-2);
// Pseudonymise IDs before data leaves production
export const pseudonymise = (id) =>
crypto.createHmac('sha256', PSEUDO_KEY).update(id).digest('hex');
// Nightly job: delete data past its retention period
cron.schedule('0 2 * * *', () =>
db.query("DELETE FROM otp_logs WHERE created_at < now() - interval '90 days'"));
The same controls, whatever the technology
The examples above use Node.js. When your project uses another stack, we apply the same controls with that platform's standard, well-maintained tools.
| Control | Node.js | Python / Django | Java / Spring | PHP / Laravel |
|---|---|---|---|---|
| Password hashing | argon2, bcrypt | Argon2PasswordHasher | Argon2PasswordEncoder | Hash::make (argon2id) |
| Security headers | helmet | SecurityMiddleware, django-csp | Spring Security headers | Middleware headers |
| CSRF protection | SameSite + CSRF tokens | CsrfViewMiddleware | Spring Security CSRF | VerifyCsrfToken |
| Input validation | zod, joi | Forms, DRF serializers | Bean Validation | Validator |
| Safe database access | Prisma, parameterised pg | Django ORM | JPA / Hibernate | Eloquent, PDO |
| Rate limiting | express-rate-limit | django-ratelimit | Bucket4j | RateLimiter |
Code samples are simplified for illustration. Exact configuration is tailored to each project's requirements and documented in the security architecture we hand over. ← Back to Security overview