AI image API content hashes: Identity, Storage, and Safety
Your image worker downloads a generated PNG, strips metadata, and uploads the result to storage. Later, an integrity check fails because the database contains the download's digest rather than the saved file's digest. AI image API content hashes solve this problem when their meaning is precise: identify the final bytes, not the prompt, the download address, or an earlier version of the image.
For developers integrating GenRelay, hashing belongs in the application’s output-handling layer. It can support integrity checks and duplicate storage detection, but it does not establish image quality, generation provenance, or permission to read an asset. Those are separate decisions with separate evidence.
What are AI image API content hashes?
AI image API content hashes are fixed-length digests computed from image bytes to identify a particular encoded artifact. A digest is the output of a hash function; SHA-256 is a cryptographic hash function that produces a 256-bit result, commonly represented as 64 hexadecimal characters.
Identical bytes produce identical SHA-256 digests. Different bytes are overwhelmingly likely to produce different digests, although a matching digest is not a mathematical proof that two arbitrary inputs are identical. For routine artifact integrity, SHA-256 provides a practical comparison mechanism. Where exact equality must be established independently, compare the bytes as well.
The digest does not describe the picture. It cannot tell you whether a generated label is readable, whether a face is distorted, or whether an image meets a content policy. Treat it as an artifact identifier, not an image assessment.
How do byte identity, visual equivalence, and request identity differ?
Byte identity concerns encoded files, visual equivalence concerns rendered appearance, and request identity concerns the inputs submitted for generation. Keeping these three concepts separate prevents misleading cache hits and incorrect duplicate decisions.
| Identity type | What is compared? | Appropriate application use |
|---|---|---|
| Byte identity | Complete encoded artifact bytes | Integrity checking and exact-file deduplication |
| Visual equivalence | Decoded pixels or perceptual features | Similarity review and duplicate candidates |
| Request identity | A versioned representation of generation inputs | Request grouping or application caching |
Two PNG files can display the same pixels while containing different metadata or compression choices. Their byte hashes will differ. Conversely, identical prompts do not establish identical output bytes: generation can vary, and output encoding can change even when the visible result appears unchanged.
A perceptual hash is a compact representation designed to compare visual features rather than exact file bytes. It can nominate similar images for review, but its distance threshold is a product decision. Crops, transparency, orientation, color management, and subtle text edits can affect what “equivalent” means. Do not use perceptual similarity as authorization evidence or as proof that files are interchangeable.
Which bytes should an application hash and verify?
An application should hash the final encoded bytes it intends to store, then verify the stored object against that expected digest before marking it ready. Hashing an earlier download is insufficient if any subsequent step changes the file.
A reliable sequence is:
- Acquire the output under bounded download limits.
- Validate the file and perform approved transformations.
- Encode the final artifact and calculate its expected digest.
- Write the artifact to storage.
- Read the stored version, recalculate its digest, and compare.
- Commit the ready status with the digest and immutable storage version.
An immutable storage version is an object revision that cannot silently change beneath an existing record. Without that property, another write could replace a file after verification. Storage permissions and version-aware reads are therefore part of the integrity design.
The following application-owned example uses Python’s standard library, performs no network requests or paid calls, and creates a valid one-pixel PNG locally. Its assertions confirm read-back integrity and demonstrate why a metadata change requires a new digest. Temporary files are removed automatically.
import hashlib
import struct
import tempfile
import zlib
from pathlib import Path
def chunk(kind, data):
crc = zlib.crc32(kind + data) & 0xffffffff
return (struct.pack(">I", len(data)) + kind + data
+ struct.pack(">I", crc))
def png(note):
header = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)
return (b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", header)
+ chunk(b"tEXt", b"Comment\x00" + note)
+ chunk(b"IDAT", zlib.compress(b"\x00\xff\x00\x00"))
+ chunk(b"IEND", b""))
def file_digest(path):
digest = hashlib.sha256()
with path.open("rb") as source:
for block in iter(lambda: source.read(65536), b""):
digest.update(block)
return digest.hexdigest()
original = png(b"downloaded")
final_bytes = png(b"application-processed")
expected = hashlib.sha256(final_bytes).hexdigest()
assert hashlib.sha256(original).hexdigest() != expected
with tempfile.TemporaryDirectory() as directory:
target = Path(directory) / "final.png"
target.write_bytes(final_bytes)
assert file_digest(target) == expected
assert target.read_bytes() == final_bytes
target.write_bytes(final_bytes + b"unexpected-change")
assert file_digest(target) != expected
print("Stored-byte verification assertions passed.")
This example changes a PNG comment without changing its pixel data. It deliberately does not claim to implement image validation. Use a maintained image decoder and explicit format, dimension, and resource limits in production; the image output validation guide explains that separate acceptance boundary.
How should request fingerprints relate to content hashes?
Request fingerprints should index application-defined input equivalence, while content hashes identify the resulting stored artifacts. A request fingerprint is a digest of a deliberately normalized request representation, not a prediction of the generated image.
Define which inputs affect your application’s cache policy, including model selection, prompt, dimensions, input-image digests, and any generation options actually supported by your integration. Resolve defaults consistently. Version the fingerprint format so that changing normalization rules does not silently reuse older entries.
Canonicalization means converting equivalent data structures into a consistent representation. Sorting JSON keys addresses ordering, but it does not decide whether omitted values equal explicit defaults or whether two Unicode strings should be normalized. Those decisions require an application contract. Avoid stripping meaningful prompt whitespace simply to increase cache matches.
The next application-owned example is standalone Python standard-library code with no paid calls. Its field names describe a local application record, not a GenRelay request schema. It demonstrates deterministic request fingerprints and a separate tenant authorization check.
import hashlib
import json
def request_fingerprint(tenant_id, inputs):
record = {
"fingerprint_version": 1,
"tenant_id": tenant_id,
"inputs": inputs,
}
encoded = json.dumps(
record, sort_keys=True, separators=(",", ":"),
ensure_ascii=False, allow_nan=False,
).encode("utf-8")
return hashlib.sha256(encoded).hexdigest()
first = {"prompt": "A red square", "width": 512}
reordered = {"width": 512, "prompt": "A red square"}
assert request_fingerprint("tenant-a", first) == request_fingerprint(
"tenant-a", reordered
)
assert request_fingerprint("tenant-a", first) != request_fingerprint(
"tenant-b", first
)
artifact = b"local artifact fixture, not an encoded image"
digest = hashlib.sha256(artifact).hexdigest()
blobs = {digest: artifact}
grants = {("tenant-a", "asset-1"): digest}
def read_asset(authenticated_tenant, asset_id):
authorized_digest = grants.get((authenticated_tenant, asset_id))
if authorized_digest is None:
raise PermissionError("Asset unavailable")
payload = blobs[authorized_digest]
if hashlib.sha256(payload).hexdigest() != authorized_digest:
raise ValueError("Stored artifact integrity failure")
return payload
assert read_asset("tenant-a", "asset-1") == artifact
try:
read_asset("tenant-b", "asset-1")
except PermissionError:
pass
else:
raise AssertionError("Cross-tenant read must fail")
print("Request identity and authorization assertions passed.")
The authenticated tenant must come from trusted authentication context, not a caller-selected body field. Including a tenant identifier in a fingerprint partitions cache entries; it does not replace the permission check illustrated by the grants lookup.
Can content-addressed storage replace tenant authorization?
No: content-addressed storage names objects by their content digest, but possession of that digest does not establish permission to access them. Authorization must connect an authenticated principal to an asset and the permitted operation.
A shared blob may have several tenant-owned asset records. Deduplication can reduce repeated storage, yet each record still needs independent access, retention, and deletion rules. Removing one tenant’s asset should remove that tenant’s grant without prematurely deleting bytes that another authorized asset still references.
Avoid exposing cross-tenant existence through public hash lookup endpoints, distinguishable errors, or “already uploaded” responses. Where this disclosure matters, tenant-scoped storage may be simpler than global deduplication. The cache isolation guide covers the surrounding separation decisions.
Where does hashing fit in a GenRelay integration?
Hashing fits after output acquisition and final application processing, before an artifact becomes available through your application’s read path. Developers exploring the GenRelay image API can apply this design without assuming that a provider supplies any particular checksum field.
Keep application job identity, request fingerprint, final content digest, byte length, media type, storage version, and tenant-owned asset identity as separate records or fields. This lets an incident investigation distinguish a repeated request from repeated bytes and a corrupted object from a denied read.
Do not assume a storage ETag is a SHA-256 checksum; its meaning depends on the storage system and upload method. A trusted manifest is a protected record of expected artifact properties. Protect that manifest separately: changing both the file and its recorded digest can defeat an integrity check against an untrusted record.
What do developers frequently ask about image hashes?
The recurring questions concern re-encoding, retries, checksums, and provenance; each requires distinguishing artifact identity from application policy.
Does converting PNG to JPEG preserve the content hash?
No. Conversion changes the encoded bytes and therefore should produce a new content digest. Store a parent-child relationship if you need to trace the JPEG to its PNG source.
Can a request hash prevent duplicate generation charges?
Not by itself. It can help your application coordinate concurrent work, but billing and retry semantics depend on documented service behavior. Persist job state and reconcile uncertain outcomes before issuing another generation request.
Should I hash base64 text or the decoded image?
Hash the decoded image bytes when identifying the stored image. Base64 is a text representation of binary data; text formatting differences should not create separate identities for the same decoded artifact.
Does a matching hash prove which model generated an image?
No. A digest identifies bytes, not their origin. Provenance requires trusted generation records or independently verifiable attestations connected to the artifact. Keep provenance evidence separate from the content digest.