#!/usr/bin/env python3 """TUVAMBES GeoCam - reference copy check. Reads, from a photo or a copy of one (a messaging-app copy, a screenshot): 1. GeoCam's hidden mark - 8 bytes woven invisibly into the photo's brightness, outside the GeoStamp: the capture's minute (UTC) and place (to about 20 m north-south / 40 m east-west); 2. the GeoStamp QR's GeoCam signature - the QR's place and capture time, signed with GeoCam's QR key (ECDSA P-256 / SHA-256); and whether the two agree, exactly as the app and the online checker do. The method is published at https://tuvambes.in/geocam/verification#copy-check. The copy check is supporting information for copies, not proof: proof is the signed original file (check it with geocam_verify.py). Needs Python 3.9 or later and: pip install pillow numpy cryptography Reading the QR from the photo also needs 'pyzbar' (pip install pyzbar); without it, read the QR with any QR scanner and pass its text with --qr. Usage: python geocam_copycheck.py PHOTO [--qr "geo:...?gc=..."] [--json] (c) 2026 TUVAMBES Technologies, a division of TUVAMBES Enterprises. Provided as is, without warranty. You may use, copy and run this script to check files, and adapt it to build your own checker. """ import argparse import base64 import itertools import json import math import time import os import re import struct import sys import zlib from datetime import datetime, timedelta, timezone try: import numpy as np from PIL import Image, ImageOps from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature except ImportError: # pragma: no cover sys.stderr.write("Needs: pip install pillow numpy cryptography\n") sys.exit(3) CHECKER_VERSION = "1.1" EPOCH = datetime(2026, 1, 1, tzinfo=timezone.utc) SAME_PLACE_METRES = 150 SAME_TIME_SLACK_SECONDS = 60 # GeoCam's QR keys (P-256 public points x, y), by key version. QR_KEYS = { 1: ( "78289e9b1e308ea2057c5cfb45d8fa391122a99167b73c27c0045d4a63d1efb7", "42f3d632c9ff64abdd306b678d7e1c908dfea0c86ef53c10477a1139e627615c", ), } QR_DOMAIN = b"GEOCAM-QR1" # ---------------------------------------------------------------- the mark # # The picture is divided into an N x N grid relative to its size. Each cell's # mean brightness (Y = 0.299 R + 0.587 G + 0.114 B, over the cell's inner # 4/6 x 4/6) sits on one of two interleaved ladders STEP apart, offset by a # per-cell key value: one ladder means bit 0, the other bit 1. The 96 bits # (8 code bytes + their CRC-32) are each spread over ~96 cells (a keyed # shuffle) and read by a soft vote; cells near black or white are weighted # out. A brightness change shifts every cell alike, so 16 offsets are tried. N = 96 CODE_BYTES = 8 CODE_BITS = CODE_BYTES * 8 BITS = CODE_BITS + 32 STEP = 4.0 KEY = 0x6E0CA1 MASK64 = (1 << 64) - 1 def _layout(): s = KEY ^ 0x5DEECE66D def nxt(): nonlocal s s ^= s >> 12 s ^= (s << 25) & MASK64 s ^= s >> 27 return (s * 2685821657736338717) & MASK64 bit_of = [i % BITS for i in range(N * N)] for i in range(N * N - 1, 0, -1): j = (nxt() >> 1) % (i + 1) bit_of[i], bit_of[j] = bit_of[j], bit_of[i] dither = np.array([np.float32((nxt() >> 11) / float(1 << 53)) for _ in range(N * N)], dtype=np.float64) return np.array(bit_of), dither BIT_OF, DITHER = _layout() def _fade(m): return np.clip((m - 20) / 25, 0, 1) * np.clip((235 - m) / 25, 0, 1) class _Luma: def __init__(self, rgb): y = (0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]).astype(np.float32).astype(np.float64) self.h, self.w = y.shape self.sat = np.zeros((self.h + 1, self.w + 1)) self.sat[1:, 1:] = y.cumsum(0).cumsum(1) self.row_busy = (y.std(1) > 2) | (np.ptp(y, 1) > 12) self.col_busy = (y.std(0) > 2) | (np.ptp(y, 0) > 12) def means(self, x0, y0, x1, y1): ax = np.clip(np.trunc(x0), 0, self.w).astype(int) ay = np.clip(np.trunc(y0), 0, self.h).astype(int) bx = np.clip(np.trunc(x1), 0, self.w).astype(int) by = np.clip(np.trunc(y1), 0, self.h).astype(int) area = (bx - ax) * (by - ay) s = self.sat[by, bx] - self.sat[ay, bx] - self.sat[by, ax] + self.sat[ay, ax] ok = (area > 0) & (area >= 0.5 * (x1 - x0) * (y1 - y0)) out = np.full(area.shape, np.nan) out[ok] = s[ok] / area[ok] return out def content(self): def longest(busy): best, start = None, -1 for i in range(len(busy) + 1): on = i < len(busy) and busy[i] if on and start < 0: start = i if not on and start >= 0: if best is None or i - start > best[1] - best[0]: best = (start, i) start = -1 return best rows, cols = longest(self.row_busy), longest(self.col_busy) if rows is None or cols is None: return None if rows[1] - rows[0] > self.h * 0.97 and cols[1] - cols[0] > self.w * 0.97: return None if rows[1] - rows[0] < self.h * 0.2 or cols[1] - cols[0] < self.w * 0.2: return None return (cols[0], rows[0], cols[1], rows[1]) _J = np.tile(np.arange(N), N) _I = np.repeat(np.arange(N), N) def _crc_ok(code, crc): return zlib.crc32(bytes(code)) == crc def _read_frame(img, x0, y0, x1, y1, fix=False): cw, ch = (x1 - x0) / N, (y1 - y0) / N if cw < 2 or ch < 2: return None v = img.means(x0 + (_J + 1 / 6) * cw, y0 + (_I + 1 / 6) * ch, x0 + (_J + 5 / 6) * cw, y0 + (_I + 5 / 6) * ch) return _decode_cells(v, fix) def _decode_cells(v, fix): ok = ~np.isnan(v) w = np.where(ok, _fade(np.nan_to_num(v).astype(np.float32).astype(np.float64)), 0) a = 2 * math.pi * (np.nan_to_num(v) / STEP - DITHER) sum_cos = np.bincount(BIT_OF, weights=w * np.cos(a), minlength=BITS) sum_sin = np.bincount(BIT_OF, weights=w * np.sin(a), minlength=BITS) for k in range(16): th = 2 * math.pi * k / 16 bits = (-(sum_cos * math.cos(th) + sum_sin * math.sin(th)) > 0).astype(int) code = [int("".join(map(str, bits[i * 8:(i + 1) * 8])), 2) for i in range(CODE_BYTES)] crc = int("".join(map(str, bits[CODE_BITS:])), 2) if _crc_ok(code, crc): return bytes(code) return _corrected(sum_cos, sum_sin) if fix else None FIX_WEAKEST = 24 # the least certain bits that may be wrong ... FIX_MOST = 5 # ... and how many of them at once EPOCH_SECONDS = 1767225600 # 2026-01-01 UTC def _corrected(sum_cos, sum_sin): """The code when up to FIX_MOST of the FIX_WEAKEST least certain bits read wrong: a real mark's CRC-32 then passes. Only the two offsets with the strongest votes are tried, and a time in the future is refused.""" offsets = [] for k in range(16): th = 2 * math.pi * k / 16 soft = -(sum_cos * math.cos(th) + sum_sin * math.sin(th)) offsets.append((float(np.abs(soft).sum()), k, soft)) offsets.sort(key=lambda o: (-o[0], o[1])) latest = (time.time() - EPOCH_SECONDS) / 60 + 2880 for _, _, soft in offsets[:2]: data = crc = 0 for b in range(BITS): bit = 1 if soft[b] > 0 else 0 if b < CODE_BITS: data = (data << 1) | bit else: crc = (crc << 1) | bit order = sorted(range(BITS), key=lambda b: (abs(soft[b]), b))[:FIX_WEAKEST] masks = [(1 << (CODE_BITS - 1 - b), 0) if b < CODE_BITS else (0, 1 << (BITS - 1 - b)) for b in order] for n in range(1, FIX_MOST + 1): for flips in itertools.combinations(masks, n): d, c = data, crc for md, mc in flips: d ^= md c ^= mc code = d.to_bytes(CODE_BYTES, "big") if zlib.crc32(code) == c and (d >> 40) <= latest: return code return None def read_exact(rgb): """The mark of a photo at the size it was saved: each cell measured over exactly the pixels the writer used. read_mark is the fallback for copies that were resized, cropped or screenshotted.""" img = _Luma(rgb) sub = 6 grid = N * sub if img.w < grid or img.h < grid: return None def edges(n): cells = np.arange(N) lo = -((-(sub * cells + 1) * n) // grid) hi = -((-(sub * cells + 5) * n) // grid) return lo, hi ax, bx = edges(img.w) ay, by = edges(img.h) a, b, c, d = ay[_I], by[_I], ax[_J], bx[_J] s = img.sat[b, d] - img.sat[a, d] - img.sat[b, c] + img.sat[a, c] return _decode_cells(s / ((b - a) * (d - c)), True) def read_mark(rgb): """The hidden mark of an RGB image array (at most ~2000 px a side), or None.""" img = _Luma(rgb) found = _read_frame(img, 0, 0, img.w, img.h, fix=True) if found: return found inner = img.content() boxes = ([inner] if inner else []) + [(0, 0, img.w, img.h)] steps = [0, 0.01, 0.02, 0.03, 0.04, 0.05] both = [-0.02, -0.01, 0, 0.01, 0.02] if inner: bw, bh = inner[2] - inner[0], inner[3] - inner[1] for l in both: for t in both: for r in both: for b in both: sx, sy = bw / (1 - l - r), bh / (1 - t - b) found = _read_frame(img, inner[0] - l * sx, inner[1] - t * sy, inner[2] + r * sx, inner[3] + b * sy) if found: return found for box in boxes: bw, bh = box[2] - box[0], box[3] - box[1] found = _read_frame(img, *box) if found: return found for l in steps: for t in steps: for r in steps: for b in steps: if l == t == r == b == 0: continue sx, sy = bw / (1 - l - r), bh / (1 - t - b) found = _read_frame(img, box[0] - l * sx, box[1] - t * sy, box[2] + r * sx, box[3] + b * sy) if found: return found return None def unpack_mark(code): """The mark's minute (UTC) and place: 24 bits of minutes since 2026, then 20 bits of latitude and 20 of longitude, big-endian; latitude and longitude all ones = no place.""" word = int.from_bytes(code, "big") lng = word & 0xFFFFF lat = (word >> 20) & 0xFFFFF minutes = word >> 40 if lat == 0xFFFFF: # all ones: no place (the GeoStamp showed none) return (EPOCH + timedelta(minutes=minutes), None, None) return ( EPOCH + timedelta(minutes=minutes), lat / 0xFFFFF * 180 - 90, lng / 0xFFFFF * 360 - 180, ) # --------------------------------------------------------------- the QR def geo_of(text): m = re.match(r"^geo:(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)", text.strip(), re.I) if not m: return None lat, lng = float(m.group(1)), float(m.group(2)) return None if abs(lat) > 90 or abs(lng) > 180 else (lat, lng) def parse_qr(text): """The signed part of a GeoStamp QR: 'geo:LAT,LNG?gc=' + base64url of version(1) key-version(1) lat(int32, 1e-6 deg) lng(int32) seconds-since- 2026(uint32) + signature r||s (64 bytes), over 'GEOCAM-QR1' + those 14.""" at = text.find("gc=") if not text.lower().startswith("geo:") or at < 0: return None b64 = text[at + 3:].split("&")[0] try: raw = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4)) except ValueError: return None if len(raw) != 14 + 64 or raw[0] != 1: return None _, key_version, lat, lng, seconds = struct.unpack(">BBiiI", raw[:14]) return { "keyVersion": key_version, "lat": lat / 1e6, "lng": lng / 1e6, "time": EPOCH + timedelta(seconds=seconds), "payload": raw[:14], "signature": raw[14:], } def verify_qr(q): key = QR_KEYS.get(q["keyVersion"]) if key is None: return False pub = ec.EllipticCurvePublicNumbers(int(key[0], 16), int(key[1], 16), ec.SECP256R1()).public_key() sig = encode_dss_signature(int.from_bytes(q["signature"][:32], "big"), int.from_bytes(q["signature"][32:], "big")) try: pub.verify(sig, QR_DOMAIN + q["payload"], ec.ECDSA(hashes.SHA256())) return True except InvalidSignature: return False def read_qr(image): try: from pyzbar.pyzbar import decode except ImportError: return None texts = [c.data.decode("utf-8", "replace") for c in decode(image)] geo = [t for t in texts if t.lower().startswith("geo:")] signed = [t for t in geo if "gc=" in t] return (signed or geo or [None])[0] # --------------------------------------------------------------- the check def distance(lat1, lng1, lat2, lng2): r = 6371000 d_lat, d_lng = math.radians(lat2 - lat1), math.radians(lng2 - lng1) a = math.sin(d_lat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(d_lng / 2) ** 2 return 2 * r * math.asin(math.sqrt(min(1, max(0, a)))) def check(path, qr_text=None): image = ImageOps.exif_transpose(Image.open(path)).convert("RGB") code = read_exact(np.asarray(image, dtype=np.float64)) if code is None: small = image.copy() small.thumbnail((1600, 1600), Image.BOX) code = read_mark(np.asarray(small, dtype=np.float64)) if qr_text is None: big = image.copy() big.thumbnail((3000, 3000), Image.BOX) qr_text = read_qr(big) mark = unpack_mark(code) if code else None sealed = parse_qr(qr_text) if qr_text else None place = geo_of(qr_text) if qr_text else None # The readable place isn't signed itself: one that differs from the signed # place means the QR was changed. readable_ok = sealed is not None and place is not None and distance(place[0], place[1], sealed["lat"], sealed["lng"]) <= 1 if sealed: state = "signed" if readable_ok and verify_qr(sealed) else "badSignature" else: state = "plain" if place else "none" qr_time = sealed["time"] if state == "signed" else None apart_m = apart_s = agree = None if mark: if mark[1] is not None and place: apart_m = distance(mark[1], mark[2], place[0], place[1]) if qr_time: d = (qr_time - mark[0]).total_seconds() apart_s = 0 if 0 <= d < 60 else abs(int(d)) if apart_m is not None or apart_s is not None: agree = (apart_m is None or apart_m <= SAME_PLACE_METRES) and ( apart_s is None or apart_s <= SAME_TIME_SLACK_SECONDS ) lines = [] if mark and mark[1] is None: lines.append( "Hidden GeoCam mark read: captured %s UTC (to the minute). It keeps no place, because the " "GeoStamp showed none." % mark[0].strftime("%Y-%m-%d %H:%M") ) elif mark: lines.append( "Hidden GeoCam mark read: captured %s UTC (to the minute), near %.4f, %.4f (to about 20-40 m)." % (mark[0].strftime("%Y-%m-%d %H:%M"), mark[1], mark[2]) ) else: lines.append( "No hidden GeoCam mark was read. Very small copies, heavily edited photos and photos from " "before GeoCam 1.1.0 carry none; this alone does not mean the photo was edited." ) qr_place = " (%.6f, %.6f)" % place if place else "" lines.append( { "signed": lambda: "GeoStamp QR signed by GeoCam, signature correct: %.6f, %.6f, captured %s." % (place[0], place[1], qr_time.strftime("%Y-%m-%dT%H:%M:%SZ")), "badSignature": lambda: "The GeoStamp QR%s carries a GeoCam signature that does NOT match: the QR " "was changed or made elsewhere." % qr_place, "plain": lambda: ( "The GeoStamp QR%s has no GeoCam signature, although the photo carries GeoCam's hidden mark: " "the QR may have been replaced." % qr_place if mark else "The GeoStamp QR%s has no GeoCam signature (photos from before GeoCam 1.1.0 have none)." % qr_place ), "none": lambda: "No GeoStamp QR was read.", }[state]() ) if agree is True: lines.append( "The hidden mark and the GeoStamp QR agree." if apart_m is None else "The hidden mark and the GeoStamp QR agree (%d m apart)." % round(apart_m) ) elif agree is False: parts = [] if apart_m is not None and apart_m > SAME_PLACE_METRES: parts.append("%d m" % round(apart_m) if apart_m < 1000 else ("%.1f km" if apart_m < 100000 else "%.0f km") % (apart_m / 1000)) if apart_s and apart_s > SAME_TIME_SLACK_SECONDS: dd, hh, mm = apart_s // 86400, apart_s // 3600 % 24, apart_s // 60 % 60 parts.append("%d d %d h" % (dd, hh) if dd else ("%d h %d min" % (hh, mm) if hh else "%d min" % mm)) lines.append("The hidden mark and the GeoStamp QR DIFFER (%s): the GeoStamp may have been edited." % ", ".join(parts)) if mark or state != "none": lines.append( "Compare these with the GeoStamp visible on the photo: a different time or place means the GeoStamp " "was edited. The copy check is supporting information, not proof; proof is the signed original file." ) return { "file": path, "hiddenMark": None if not mark else {"code": code.hex(), "capturedMinuteUtc": mark[0].isoformat(), "latitude": mark[1], "longitude": mark[2]}, "geoStampQr": { "state": state, "text": qr_text, "latitude": place[0] if place else None, "longitude": place[1] if place else None, "capturedAtUtc": qr_time.isoformat() if qr_time else None, }, "apartMetres": None if apart_m is None else round(apart_m), "apartSeconds": apart_s, "agree": agree, "summary": lines, } def main(argv=None): p = argparse.ArgumentParser(description="TUVAMBES GeoCam reference copy check") p.add_argument("photo") p.add_argument("--qr", help="the GeoStamp QR's text, read with any QR scanner") p.add_argument("--json", action="store_true") args = p.parse_args(argv) r = check(args.photo, args.qr) # The combined result, as the app and the website give it: the photo's # signature first (geocam_verify.py beside this script), then this check. try: sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import geocam_verify # noqa: E402 signed = geocam_verify.verify_file(args.photo) r["result"] = geocam_verify.outcome(signed, r if signed["reason"] == "noSignature" else None) except Exception as e: # noqa: BLE001 r["result"] = None print("Signature not checked (geocam_verify.py not found): %s" % e, file=sys.stderr) if args.json: print(json.dumps(r, indent=2, ensure_ascii=False, default=str)) else: print("TUVAMBES GeoCam reference copy check %s - %s" % (CHECKER_VERSION, args.photo)) o = r["result"] if o: print("Result: %s" % o["headline"]) print(" %s" % o["explanation"]) print("Means: %s" % o["whatItMeans"]) print("To do: %s" % o["whatToDo"]) for line in r["summary"]: print("- " + line) return 0 if r["agree"] is not False and r["geoStampQr"]["state"] != "badSignature" else 1 if __name__ == "__main__": sys.exit(main())