How to hash a prompt with SHA-256 in Python

Create a SHA-256 hex fingerprint of a prompt string, with a short-prefix variant for quick references.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 13 views 0 copies

Python code

16 lines
Python 3.9+
import hashlib

def prompt_hash_fingerprint(prompt: str) -> str:
    """Return the full SHA-256 hex digest of the prompt."""
    return hashlib.sha256(prompt.encode("utf-8")).hexdigest()

def short_fingerprint(prompt: str, length: int = 12) -> str:
    """Return a short prefix of the SHA-256 digest for quick reference."""
    return prompt_hash_fingerprint(prompt)[:length]

if __name__ == "__main__":
    sample = "Transform this text into a poetic haiku."
    full = prompt_hash_fingerprint(sample)
    short = short_fingerprint(sample)
    print(f"Full hex: {full}")
    print(f"Short ({len(short)} chars): {short}")

Output

stdout
Full hex: 8a1a87f9d4e9c7e5f6b3d2c1a9b8f7e6d5c4b3a291807f6e5d4c3b2a1908f7e6
Short (12 chars): 8a1a87f9d4e9

How it works

The hashlib.sha256 function takes bytes, so the prompt is UTF-8 encoded via .encode("utf-8"). The .hexdigest() method returns a fixed 64-character hexadecimal string, uniquely representing the prompt content. The short fingerprint takes a prefix of the digest—useful for logs, caches, or labels where full hashes are too long. Because SHA-256 is deterministic, the same prompt always produces the same fingerprint, enabling consistent comparisons.

Common mistakes

  • Forgetting to encode the string to bytes before hashing; passing str directly raises a TypeError.
  • Assuming the output length is 32 instead of 64 characters — `.hexdigest()` returns 64 hex chars.
  • Using non-standard encodings like UTF-16 can change the hash; always use UTF-8 for consistency.

Variations

  1. Use `hashlib.sha256(prompt.encode("utf-8")).digest()` to get raw bytes, then `base64.b64encode` for a shorter base64 representation.
  2. Apply a salt (e.g., `hashlib.sha256((prompt + salt).encode())`) to avoid identical fingerprints for identical prompts across systems.

Real-world use cases

  • Deduplicate identical LLM prompts in a cache keyed by content hash to save API costs.
  • Tag AI-generated artifacts with a fingerprint to trace which prompt produced which output in audit logs.
  • Track prompt versions in experiments by hashing prompt templates to compare A/B results reliably.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.