NewOffensive AI & LLM penetration testing is now available —Learn more →
xtreme.infosec
Book a call30 min · free · Google Meet
BlogSource code review

Hardcoded Secrets in Source Code: How to Find and Fix Them

Hardcoded secrets explained for CTOs and dev leads: how API keys and passwords end up in code, how to find them, the right order to fix them, and how to stop new leaks.

By Xtreme InfoSec Security Team·14 Nov 2026·9 min read

Hardcoded secrets are passwords, API keys, tokens, private keys and connection strings written directly into source code, configuration files or build scripts instead of being supplied securely at runtime. They are among the most common findings in a source code review. They are also among the most dangerous, because anyone who gets a copy of the code gets the keys with it.

The fix has three parts. Find every secret, including old ones buried in git history. Rotate each exposed secret so it no longer works. Then move secrets into a proper store and add checks so new ones cannot slip back in. This guide explains how to do each step, which tools help, and what to ask for if you bring in an outside reviewer.

Key takeaways

  • A secret committed to a repository should be treated as leaked, even if the repository is private. Deleting the line in a new commit does not remove it from history.
  • Rotation comes first. Revoke and reissue the key, then clean the code and history. Cleaning without rotating leaves the old key valid.
  • Secret scanning tools such as Gitleaks find most obvious keys quickly. A manual review catches the rest: custom tokens, encoded values, keys in mobile builds and secrets passed through CI pipelines.
  • The long-term fix is a secrets manager or environment-level configuration, plus pre-commit hooks and pipeline checks that block new secrets.
  • Mobile apps, firmware and front-end JavaScript ship to users. Any secret inside them can be extracted, so the design must not depend on hiding it.

What counts as a hardcoded secret

A secret is any value that grants access or proves identity. If an attacker could use it to log in, call a paid service, read data or sign something as you, it is a secret. Common examples in Indian product codebases include:

  • Database usernames, passwords and full connection strings.
  • Cloud access keys for AWS, Azure or Google Cloud.
  • Payment gateway keys and webhook signing secrets.
  • SMS, email and WhatsApp provider API keys used for OTPs and notifications.
  • JWT signing keys and session encryption keys.
  • Private keys and certificates, SSH keys and code-signing keys.
  • Third-party SaaS tokens: CRM, analytics, maps, chat, storage.
  • Default admin passwords for internal panels or devices.

The weakness has its own entry in MITRE's list, CWE-798 Use of Hard-coded Credentials, and the OWASP Top 10 (2021) maps it under A07 Identification and Authentication Failures. In practice it often overlaps with A02 Cryptographic Failures too, because a hardcoded encryption key makes the encryption almost worthless.

How secrets end up in code

It usually happens through ordinary shortcuts that never get undone:

  • A developer tests an integration locally with a real key, and the file gets committed with it.
  • A configuration file meant to stay local is not listed in the ignore file, so it goes into the repository.
  • Sample code from a provider's documentation is pasted in with the key filled in.
  • A CI/CD pipeline file holds a deployment token in plain text rather than referring to the pipeline's secret store.
  • A mobile or front-end developer needs the app to call an API directly and puts the key in the app.
  • Logs, test fixtures, database dumps or notebooks containing credentials are committed alongside the code.

Once committed, the secret travels everywhere the code goes: every developer laptop, every fork, CI runners, backups, vendor handovers and, sometimes, a public repository that was made public by mistake.

Why a private repository is not enough

Many teams assume that keys in a private repository are safe. That assumption fails in several ordinary ways. Former employees and contractors keep their clones. A laptop is lost or infected. A vendor receives a copy of the code. A repository is accidentally made public, or an old mirror is left open on a self-hosted git server.

Git history is the other trap. If someone removes a key in a later commit, the key is still in every earlier commit and every clone. Anyone with access can search the history. That is why the first rule of secret handling is simple: once a real secret has been committed, assume it is exposed and rotate it.

Not sure how many keys are sitting in your repositories and their history? A source code review from Xtreme InfoSec includes secret scanning across the full history, manual confirmation of each hit, and a list of what to rotate first.

How to find hardcoded secrets

Finding secrets is a mix of automated scanning and human judgement. Scanners are fast but noisy; humans are slower but understand context.

Automated secret scanning

Secret scanning tools look for known key formats, high-entropy strings and suspicious variable names across files and commit history. Widely used options include:

Tool or featureWhat it does wellWhere to use it
Gitleaks (open source)Fast rule-based scanning of files and full git history; custom rules for your own token formatsPre-commit hooks, CI pipelines, one-off audits
TruffleHog (open source)Scans history and many sources; can check whether some detected keys are still liveAudits and CI
GitHub secret scanning and push protectionDetects many provider key formats and can block a push that contains oneRepositories hosted on GitHub (check which features your plan includes)
GitLab secret detectionPipeline-based detection of committed secretsRepositories hosted on GitLab
SAST tools such as SonarQube, Checkmarx and SemgrepFlag hardcoded password and key patterns as part of wider code analysisRegular code quality and security scans

GitHub, for example, turned on push protection by default for pushes to public repositories in 2024, but users can still choose to bypass a block, and private repositories depend on your plan and settings. Treat platform features as one layer, not the whole answer.

Scan the history, not just the latest code

A scan of the current branch only shows today's code. Run the scanner across the full commit history of every branch, including old feature branches and tags.

Manual review: what tools miss

Scanners miss secrets that do not look like secrets. A reviewer reading the code looks for:

  • Custom tokens and internal API keys that follow no public format.
  • Values that are base64-encoded, split across variables or lightly obfuscated.
  • Credentials inside compiled mobile apps, desktop clients, firmware images and Docker images.
  • Secrets passed into build steps and then printed into build logs.
  • Default or shared passwords in device setup code and admin seed scripts.
  • Encryption keys and initialisation vectors set as constants.

A reviewer also cuts false positives. Test placeholders, public keys and example values often trip scanners. Confirming each hit and noting which system it belongs to turns a list of hundreds of alerts into a short, prioritised action list.

How to fix hardcoded secrets: the right order

The order matters. Teams that clean the code first and rotate later leave a window where the leaked key still works.

  1. Inventory. List every confirmed secret: what it is, which system it unlocks, where it appears, and who owns that system.
  2. Prioritise. Production cloud keys, database credentials, payment keys and signing keys go first. Test keys for sandbox services come later.
  3. Rotate. Generate a new credential in the provider's console, deploy it through a secure channel, then revoke the old one. Check the provider's access logs for any unexpected use of the old key.
  4. Move to a secure store. Replace the hardcoded value with a lookup from a secrets manager or from environment configuration injected at deploy time.
  5. Clean the history if needed. Tools such as git filter-repo or BFG Repo-Cleaner can rewrite history to remove the old value. This needs coordination because every clone must be refreshed. Rotation is still the real fix; history cleanup only reduces noise and future risk.
  6. Prevent regressions. Add secret scanning to pre-commit hooks and CI so a new secret is blocked before it is merged.

Where secrets should live instead

The right store depends on your stack. Common choices are a cloud provider's secrets service (AWS Secrets Manager, Azure Key Vault, Google Secret Manager), HashiCorp Vault, Kubernetes secrets backed by an external store, or your CI/CD platform's protected variables. Whatever you choose, apply a few rules:

  • Give each service its own credential with the minimum permissions it needs.
  • Use separate credentials for development, staging and production.
  • Prefer short-lived credentials or managed identities where the platform supports them.
  • Log access to secrets and review who can read them.
  • Keep local environment files out of the repository through the ignore file, and share a template with dummy values instead.

Special cases: mobile apps, front ends and devices

Some code is delivered to the people who use it. Android APKs, iOS apps, browser JavaScript, desktop clients and device firmware can all be unpacked and read. No amount of obfuscation makes a secret inside them truly secret. It only slows an attacker down.

The design answer is to keep powerful keys on your server. The app talks to your backend with the user's own session, and the backend calls the payment, SMS or cloud provider. Where a key must sit in the client, such as a maps key, restrict it at the provider by app signature, package name or domain, and limit what it can do. For IoT and CCTV products, avoid shared default passwords across devices and make sure each unit has its own credentials. This is something manufacturers preparing for lab testing should fix early; see our guide to STQC certification for CCTV.

What to ask a reviewer for

If you engage an external team, ask how they handle credentials in the repository specifically. A useful secrets section in a source code review report should give you:

  • Scan coverage: which repositories, branches and how much history were scanned.
  • Each confirmed secret with its type, location (file and commit) and the system it unlocks, with the value itself masked in the report.
  • A severity based on what the secret can do, not just that it exists.
  • Clear rotation and remediation steps, and a recommended prevention setup.
  • A retest after you fix, confirming the secrets are gone from the code and the pipeline checks work.

Also agree on how the reviewer will handle any live secret they find. They should report it quickly, never test it against production without written permission, and never put the full value in shared documents.

A quick self-check for your team

Before a formal review, your developers can do a first pass in an afternoon:

  1. Run Gitleaks or a similar tool across the full history of your main repositories.
  2. Search configuration and pipeline files for words such as password, secret, token and key.
  3. Check that local environment files and key files are listed in the ignore file.
  4. Unpack your latest Android build and look for API keys in the resources and strings.
  5. Confirm that production and staging use different credentials.

For a wider set of checks, see our secure code review checklist.

Frequently asked questions

If we delete the secret from the code, are we safe?

No. The value remains in git history and in every clone made before the change. Rotate the secret first so the old value stops working, then remove it from the code and, if needed, from history.

Are secrets in a private repository a real risk?

Yes. Private repositories are shared with employees, contractors, vendors, CI systems and backups. Any of these can leak. Treat a committed secret as exposed regardless of repository visibility.

Is a secret scanning tool enough on its own?

It is a strong first layer, but tools miss custom formats, encoded values and secrets inside compiled builds, and they produce false positives. A manual review confirms real findings and covers what scanners miss.

Can we hide API keys inside a mobile app with obfuscation?

Obfuscation slows attackers down but does not stop them. Keep sensitive keys on your backend, and restrict any key that must sit in the app by package name, signature or domain at the provider.

How long does a source code review that covers secrets take?

Most source code review projects at Xtreme InfoSec take 3-5 working days, with an express option within 2 working days. The exact time depends on codebase size and number of repositories, which we confirm during scoping.

Bring the secrets problem under control

Hardcoded secrets are easy to create and slow to clean up, but the fix is well understood: find them all, rotate them, store them properly and block new ones at commit time. The earlier you do it, the fewer systems you have to rotate. Xtreme InfoSec reviews code manually alongside tools such as Gitleaks, Semgrep, SonarQube and Checkmarx, verifies every finding, and includes a free retest after you fix. Source code review starts from ₹15,000, with a fixed quote after scoping; you can also check the VAPT cost estimator for testing work.

Find the secrets in your code before someone else does

Share your repository details and we will send a fixed quote for a source code review that covers secrets, dependencies and code-level vulnerabilities. NDA on request. Email contact@xtremeinfosec.com or call +91 98183 63944.

Get a code review quote

Keep reading

Get started

Get a free quote for your VAPT.

Share your app, scope and deadline. You’ll get a clear plan, a timeline and a fixed quote — we reply within 1 hour.

+91 98183 63944

    Message Us

    Tell us what you need — we’ll reply with clear next steps and a fixed quote.

    Your details stay confidential and are used only to respond to your enquiry.

    Privacy Overview

    This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

    Chat on WhatsApp