# verify_base4096_signature.py
import hashlib
from base4096 import decode, load_frozen_alphabet
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, ec
from cryptography.exceptions import InvalidSignature

# ---------- Config ----------
FROZEN_ALPHABET_FILE = "frozen_base4096_alphabet.txt"
SIGNATURE_BLOCK = """---BEGIN BASE4096 SIGNATURE---
Version: 1
Hash: SHA-256
Domain: ZCHG-Base4096-Fingerprint
Length: 256
Alphabet-Fingerprint:
˪ۢஆؚכ߬ΓᇈMᄹාа၆؁੨ĭ࿈ᆫ˞๓˖჻ᅔဠA၀ჟၿᇒಌෞeኃᄍr۟ęԸටզჩᅶࢫᇕຽঠࡎȂȁໟᆹንدɦ;Ȳຝೄ૦ԇࣻ༃ЈŽ
໊त͢Ɇኖ۩Uଋኗݙ႑Ҷഹđԇ̌Ԣழ௪ᄚ౸ଅ৴ཛܲඈວ۟ࣵ࠘Юëိྠࢻໞۑ́ੑ༫Ԥආஊĵডམᆐࢰחങï܈؛ΝՆڄဴƿٛજҟڜಎኄ
ޗ}ܗȓຯİफగୱଡ଼ʵ૫yൿৗᇵჃѺӸ༪ሃଔଣᆣࠤค౬ˌtำᅖ଼ҙኄဪᆍࡀࢦ϶֥ກཡоܷࣞźݾ֘໕१ˊٷ݁ঘ࣓ǬࡌےॖབϒচႫ෧
ၔʞ̻ਓӡࢶÉჄӊੋྼٓෘෑྃᇽӡȏήĕÇƪࢫ௸ืੂႩઝჀྐաภঅᄿᄈ֊іࡠӪȇͼᅵଲɂݽࣔʊະƄ໓జ؉͐ʎஊѾঊଠਪ́ؒ֗ೀ୨
---END BASE4096 SIGNATURE---
"""  # Paste your full Alphabet-Fingerprint here
MESSAGE_FILE = "message.txt"  # file that was signed
PUBLIC_KEY_FILE = "public_key.pem"  # PEM file

# ---------- Load alphabet ----------
alphabet = load_frozen_alphabet(FROZEN_ALPHABET_FILE)
CHAR_TO_INDEX = {ch: idx for idx, ch in enumerate(alphabet)}

# ---------- Decode signature ----------
signature_bytes = decode(SIGNATURE_BLOCK.replace("\n", ""))
print("Signature length (bytes):", len(signature_bytes))

# ---------- Load message ----------
with open(MESSAGE_FILE, "rb") as f:
    message_bytes = f.read()

# ---------- Hash message ----------
digest = hashlib.sha256(message_bytes).digest()
print("SHA-256 digest:", digest.hex())

# ---------- Load public key ----------
with open(PUBLIC_KEY_FILE, "rb") as f:
    pubkey = serialization.load_pem_public_key(f.read())

# ---------- Verify ----------
try:
    if isinstance(pubkey, ec.EllipticCurvePublicKey):
        # ECDSA verification
        pubkey.verify(signature_bytes, message_bytes, ec.ECDSA(hashes.SHA256()))
    else:
        # Assume RSA with PKCS1v15 padding
        pubkey.verify(
            signature_bytes,
            message_bytes,
            padding.PKCS1v15(),
            hashes.SHA256()
        )
    print("✅ Signature is valid!")
except InvalidSignature:
    print("❌ Signature is INVALID!")
