Skip to main content
CybersecurityAI & Machine Learning

Secure AI Code Generation: Why Good Prompts Matter More Than You Think

Secure AI Code Generation: Why Good Prompts Matter More Than You Think

Recent discussions in the tech community have highlighted concerns that artificial intelligence (AI) tools like GPT inherently produce insecure code. Headlines have painted AI-assisted programming as a looming security disaster. However, the reality is quite different. AI itself isn’t to blame – rather, it’s the improper or incomplete instructions we provide that lead to insecure code generation. In short, the age-old programming adage remains true: garbage in, garbage out.

Garbage In, Garbage Out: A Timeless Principle

The fundamental principle of “garbage in, garbage out” (GIGO) predates AI by decades. If inputs are poorly formed or incomplete, the outputs will inevitably reflect those shortcomings. This principle holds equally true whether you’re programming manually or instructing an AI assistant.

When developers fail to provide or follow clear, comprehensive guidelines, AI tools have no choice but to fill in gaps based on training data – which may include less-than-ideal examples. Poorly defined prompts inevitably result in poor-quality outputs, including code riddled with bugs and/or security vulnerabilities.

The Real Culprit: Poor Prompt Engineering

Just like human developers, AI requires clear and precise instructions. Writing a strong prompt is analogous to clearly defining software requirements. Effective prompts should include explicit directions on security, coding standards, formatting guidelines, and best practices.

An Example of a Well-Formed AI Programming Prompt

Here’s an example of a robust, carefully structured Python programming prompt that ensures the AI’s output aligns with best practices and secure coding guidelines:

Write a Python script/module that aligns to best practices in formatting, structure, security, and documentation.

Detailed Instructions:
When generating Python code:
---
Code Quality and Style
- Adhere strictly to PEP8 formatting standards.
- Follow broader PEP guidelines, including naming conventions, structure, and documentation (e.g., PEP257 for docstrings).
- Apply clear and consistent naming for functions, variables, and classes.
- Use type hints for all function arguments and return values.
- Structure the code into functions and modules when logical to promote extensibility and reuse.
- If needed, break out complex functionality into multiple files or modules with importable classes/functions.
---
Documentation
- Add a module-level docstring explaining the script's purpose and usage.
- Each function and class must have a clear, concise docstring describing:
  - Purpose
  - Inputs (types and descriptions)
  - Outputs (types and descriptions)
- Comment critical or non-obvious sections of code to enhance readability.
---
Security and Best Practices
- Use the latest stable versions of any libraries.
- Where applicable, validate and sanitize user inputs and external data.
- Do not hardcode sensitive values (passwords, keys); use secure retrieval methods like environment variables or secret managers.
- Follow OWASP Secure Coding Practices guidelines where appropriate.
- Prefer built-in libraries and modules unless a third-party library is clearly advantageous and reputable.
- Handle exceptions thoughtfully, avoiding over-broad exception catches.
- Use secure communication protocols (e.g., HTTPS over HTTP).
---
Output Requirements
- Start the script with an appropriate shebang (`#!/usr/bin/env python3`).
- Include an `if __name__ == "__main__":` guard for script execution.
- Include logging using Python’s `logging` module, not print statements for non-debug output.
- Log files should be named in the format `<scriptname>-YYYYMMDD_HHmmss.log`.
- Parameterize configurable options (like file paths, user inputs, etc.) using CLI arguments (e.g., `argparse`).
- Any temporary or generated files should be securely handled (permissions set appropriately, deleted when no longer needed).
---
Testing and Validation
- If appropriate, include basic unit tests using `unittest` or `pytest`.
- Ensure the script runs successfully without syntax errors or warnings on Python 3.11+.
---
Tone
- Make the code clear, maintainable, and professional — as if it were going into a public GitHub repository.

By embedding security considerations explicitly within the above prompt, we proactively guide the AI toward generating secure and robust code. However, this is still no substitute for running your code through a security tool to confirm your directions were followed and the goal achieved.

The Real Risk: Blind Trust in AI Outputs

What we should truly be worried about isn’t the AI itself, but rather the current generation of “programmers” who don’t know – or care – enough about coding standards, best practices, or security guidelines to recognize when poor or insecure code has been generated. Too many developers treat AI as a magical “vibe-coding” buddy that’s always correct, failing to understand that AI is merely another advanced tool in their toolkit.

Putting innate trust in another programmer’s application – and make no mistake, that’s exactly what AI-driven coding assistants are – is fundamentally flawed. Even the most diligent programmers make mistakes, so expecting AI to be infallible is dangerously naive.

Improving Outcomes with Better Prompt Engineering

To combat the “onslaught” of insecure code blamed unfairly on AI, developers must master the skill of prompt engineering. Effective prompt writing is as critical to AI-assisted development as clear requirements gathering is to traditional programming.

Instead of blaming AI for insecure outputs, let’s recognize the true source of the problem: unclear, incomplete, or poorly structured prompts. By refining how we instruct AI, we can harness its full potential, dramatically enhancing both productivity and security.

AI doesn’t generate insecure code by default—careless prompts do. The responsibility to provide clear, secure, and comprehensive instructions remains squarely on the shoulders of the human operator.

So before you blame the AI, check your prompt – and maybe your fundamentals.

You feeling my vibe? 😏