keyhalve 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- keyhalve/__init__.py +76 -0
- keyhalve/_timelock.py +53 -0
- keyhalve/binding.py +154 -0
- keyhalve/client.py +1194 -0
- keyhalve/crypto.py +332 -0
- keyhalve/errors.py +32 -0
- keyhalve/offline.py +312 -0
- keyhalve/pdf.py +276 -0
- keyhalve/py.typed +0 -0
- keyhalve/rail.py +77 -0
- keyhalve/types.py +62 -0
- keyhalve-0.1.0.dist-info/METADATA +383 -0
- keyhalve-0.1.0.dist-info/RECORD +16 -0
- keyhalve-0.1.0.dist-info/WHEEL +5 -0
- keyhalve-0.1.0.dist-info/licenses/LICENSE +21 -0
- keyhalve-0.1.0.dist-info/top_level.txt +1 -0
keyhalve/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""KeyHalve SDK for Python.
|
|
2
|
+
|
|
3
|
+
Public API:
|
|
4
|
+
KeyHalveClient — client for the issuing platform API + the KeyHalve rail
|
|
5
|
+
KeyHalveError — exception type raised for all SDK / API errors
|
|
6
|
+
CreateIntentResult, VerifyIntentResult — result dataclasses
|
|
7
|
+
generate_key, encrypt, decrypt — low-level crypto helpers
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .binding import (
|
|
11
|
+
BindingComparisonResult,
|
|
12
|
+
compare_binding_hashes,
|
|
13
|
+
compute_binding_hash,
|
|
14
|
+
)
|
|
15
|
+
from .client import KeyHalveClient
|
|
16
|
+
from .crypto import (
|
|
17
|
+
build_aad,
|
|
18
|
+
build_key_map,
|
|
19
|
+
combine_key_shares,
|
|
20
|
+
compute_commitment_hash,
|
|
21
|
+
decrypt,
|
|
22
|
+
decrypt_bytes,
|
|
23
|
+
decrypt_fields,
|
|
24
|
+
encrypt,
|
|
25
|
+
encrypt_bytes,
|
|
26
|
+
encrypt_fields,
|
|
27
|
+
generate_key,
|
|
28
|
+
split_key,
|
|
29
|
+
split_key_pieces,
|
|
30
|
+
combine_key_pieces,
|
|
31
|
+
)
|
|
32
|
+
from .errors import KeyHalveError
|
|
33
|
+
from .offline import OfflineCache, OfflineVerifyResult
|
|
34
|
+
from .pdf import (
|
|
35
|
+
MIN_RECOMMENDED_QR_PT,
|
|
36
|
+
QrPlacement,
|
|
37
|
+
ResolvedQrRect,
|
|
38
|
+
build_verify_url,
|
|
39
|
+
embed_qr,
|
|
40
|
+
resolve_qr_rect,
|
|
41
|
+
)
|
|
42
|
+
from .types import CreateIntentResult, VerifyIntentResult
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"KeyHalveClient",
|
|
46
|
+
"KeyHalveError",
|
|
47
|
+
"CreateIntentResult",
|
|
48
|
+
"VerifyIntentResult",
|
|
49
|
+
"generate_key",
|
|
50
|
+
"encrypt",
|
|
51
|
+
"encrypt_bytes",
|
|
52
|
+
"decrypt",
|
|
53
|
+
"decrypt_bytes",
|
|
54
|
+
"compute_commitment_hash",
|
|
55
|
+
"build_aad",
|
|
56
|
+
"split_key",
|
|
57
|
+
"combine_key_shares",
|
|
58
|
+
"split_key_pieces",
|
|
59
|
+
"combine_key_pieces",
|
|
60
|
+
"encrypt_fields",
|
|
61
|
+
"build_key_map",
|
|
62
|
+
"decrypt_fields",
|
|
63
|
+
"compute_binding_hash",
|
|
64
|
+
"compare_binding_hashes",
|
|
65
|
+
"BindingComparisonResult",
|
|
66
|
+
"OfflineCache",
|
|
67
|
+
"OfflineVerifyResult",
|
|
68
|
+
"QrPlacement",
|
|
69
|
+
"ResolvedQrRect",
|
|
70
|
+
"MIN_RECOMMENDED_QR_PT",
|
|
71
|
+
"build_verify_url",
|
|
72
|
+
"resolve_qr_rect",
|
|
73
|
+
"embed_qr",
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
__version__ = "1.5.0"
|
keyhalve/_timelock.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Time-Locked Verification helpers (Patent D, MILU-PAT-004).
|
|
2
|
+
|
|
3
|
+
Pure-stdlib utilities for parsing ISO-8601 validity windows, validating
|
|
4
|
+
ordering, and computing client-side enforcement status. The server stores
|
|
5
|
+
the timestamps but never reads them; all decisions live here.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
from .errors import KeyHalveError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def parse_iso(ts: str) -> datetime:
|
|
16
|
+
"""Parse an ISO-8601 timestamp, accepting ``Z`` as UTC."""
|
|
17
|
+
return datetime.fromisoformat(ts.replace("Z", "+00:00"))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def validate_time_lock(valid_from: Optional[str], valid_until: Optional[str]) -> None:
|
|
21
|
+
"""Raise if both are provided and ``valid_until`` is not strictly after ``valid_from``."""
|
|
22
|
+
if not valid_from or not valid_until:
|
|
23
|
+
return
|
|
24
|
+
try:
|
|
25
|
+
from_dt = parse_iso(valid_from)
|
|
26
|
+
until_dt = parse_iso(valid_until)
|
|
27
|
+
except ValueError as exc:
|
|
28
|
+
raise KeyHalveError("invalid_argument", "valid_from / valid_until must be ISO-8601") from exc
|
|
29
|
+
if until_dt <= from_dt:
|
|
30
|
+
raise KeyHalveError("invalid_argument", "valid_until must be after valid_from")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def compute_time_lock_status(
|
|
34
|
+
valid_from: Optional[str],
|
|
35
|
+
valid_until: Optional[str],
|
|
36
|
+
) -> Optional[str]:
|
|
37
|
+
"""Return ``"valid" | "not_yet_valid" | "expired"``, or None if no window is set."""
|
|
38
|
+
if not valid_from and not valid_until:
|
|
39
|
+
return None
|
|
40
|
+
now = datetime.now(timezone.utc)
|
|
41
|
+
if valid_from:
|
|
42
|
+
try:
|
|
43
|
+
if now < parse_iso(valid_from):
|
|
44
|
+
return "not_yet_valid"
|
|
45
|
+
except ValueError:
|
|
46
|
+
return None
|
|
47
|
+
if valid_until:
|
|
48
|
+
try:
|
|
49
|
+
if now > parse_iso(valid_until):
|
|
50
|
+
return "expired"
|
|
51
|
+
except ValueError:
|
|
52
|
+
return None
|
|
53
|
+
return "valid"
|
keyhalve/binding.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Physical Medium Binding — perceptual hashing for document-QR binding.
|
|
2
|
+
|
|
3
|
+
Computes a 64-bit perceptual hash (pHash) of a "binding zone" image.
|
|
4
|
+
The hash is robust to minor lighting/angle variations but changes
|
|
5
|
+
significantly when the underlying paper stock is different.
|
|
6
|
+
|
|
7
|
+
Patent G (MILU-PAT-007).
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from .errors import KeyHalveError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def compute_binding_hash(
|
|
15
|
+
image_bytes: bytes,
|
|
16
|
+
*,
|
|
17
|
+
hash_size: int = 8,
|
|
18
|
+
) -> str:
|
|
19
|
+
"""Compute a perceptual hash of a binding zone image.
|
|
20
|
+
|
|
21
|
+
Uses a DCT-based perceptual hash (pHash) algorithm:
|
|
22
|
+
1. Convert to grayscale (if not already)
|
|
23
|
+
2. Resize to (hash_size*4) x (hash_size*4)
|
|
24
|
+
3. Apply DCT
|
|
25
|
+
4. Extract top-left hash_size x hash_size coefficients
|
|
26
|
+
5. Compute median and threshold to produce binary hash
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
image_bytes: Raw bytes of the binding zone image (JPEG/PNG).
|
|
30
|
+
hash_size: Size of the hash grid. 8 produces a 64-bit hash.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
Hex string of the perceptual hash (16 hex chars for 64-bit).
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
KeyHalveError: If the image cannot be processed.
|
|
37
|
+
"""
|
|
38
|
+
try:
|
|
39
|
+
from PIL import Image
|
|
40
|
+
import numpy as np
|
|
41
|
+
except ImportError:
|
|
42
|
+
raise KeyHalveError(
|
|
43
|
+
"missing_dependency",
|
|
44
|
+
"Physical Medium Binding requires 'Pillow' and 'numpy'. "
|
|
45
|
+
"Install with: pip install keyhalve[binding]",
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
from scipy.fft import dct
|
|
50
|
+
except ImportError:
|
|
51
|
+
raise KeyHalveError(
|
|
52
|
+
"missing_dependency",
|
|
53
|
+
"Physical Medium Binding requires 'scipy'. "
|
|
54
|
+
"Install with: pip install keyhalve[binding]",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
import io
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
img = Image.open(io.BytesIO(image_bytes))
|
|
61
|
+
except Exception as e:
|
|
62
|
+
raise KeyHalveError("invalid_image", f"Cannot open image: {e}")
|
|
63
|
+
|
|
64
|
+
img = img.convert("L")
|
|
65
|
+
|
|
66
|
+
resize_dim = hash_size * 4
|
|
67
|
+
img = img.resize((resize_dim, resize_dim), Image.Resampling.LANCZOS)
|
|
68
|
+
|
|
69
|
+
pixels = np.array(img, dtype=np.float64)
|
|
70
|
+
dct_result = dct(dct(pixels, axis=0, norm="ortho"), axis=1, norm="ortho")
|
|
71
|
+
|
|
72
|
+
low_freq = dct_result[:hash_size, :hash_size]
|
|
73
|
+
|
|
74
|
+
flat = low_freq.flatten()
|
|
75
|
+
# Exclude the DC component for median calculation — it captures overall
|
|
76
|
+
# brightness, which leaks across all bits and biases the threshold.
|
|
77
|
+
median_val = np.median(flat[1:])
|
|
78
|
+
|
|
79
|
+
bits = (flat > median_val).astype(np.uint8)
|
|
80
|
+
|
|
81
|
+
hash_int = 0
|
|
82
|
+
for bit in bits:
|
|
83
|
+
hash_int = (hash_int << 1) | int(bit)
|
|
84
|
+
|
|
85
|
+
hex_length = (hash_size * hash_size) // 4
|
|
86
|
+
return format(hash_int, f"0{hex_length}x")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def compare_binding_hashes(
|
|
90
|
+
hash_a: str,
|
|
91
|
+
hash_b: str,
|
|
92
|
+
*,
|
|
93
|
+
threshold: int = 10,
|
|
94
|
+
) -> "BindingComparisonResult":
|
|
95
|
+
"""Compare two perceptual hashes and determine if they match.
|
|
96
|
+
|
|
97
|
+
Uses Hamming distance — the number of bit positions where the two
|
|
98
|
+
hashes differ. A lower distance means more similar images.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
hash_a: Hex string of the first perceptual hash.
|
|
102
|
+
hash_b: Hex string of the second perceptual hash.
|
|
103
|
+
threshold: Maximum Hamming distance to consider a match.
|
|
104
|
+
Default 10 (out of 64 bits) allows ~15% variation.
|
|
105
|
+
|
|
106
|
+
Returns:
|
|
107
|
+
BindingComparisonResult with match status and distance.
|
|
108
|
+
"""
|
|
109
|
+
if len(hash_a) != len(hash_b):
|
|
110
|
+
raise KeyHalveError(
|
|
111
|
+
"invalid_argument",
|
|
112
|
+
f"Hash lengths differ: {len(hash_a)} vs {len(hash_b)}",
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
int_a = int(hash_a, 16)
|
|
116
|
+
int_b = int(hash_b, 16)
|
|
117
|
+
xor = int_a ^ int_b
|
|
118
|
+
|
|
119
|
+
distance = bin(xor).count("1")
|
|
120
|
+
|
|
121
|
+
return BindingComparisonResult(
|
|
122
|
+
matches=distance <= threshold,
|
|
123
|
+
hamming_distance=distance,
|
|
124
|
+
threshold=threshold,
|
|
125
|
+
hash_bits=len(hash_a) * 4,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class BindingComparisonResult:
|
|
130
|
+
"""Result of comparing two binding zone perceptual hashes."""
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
matches: bool,
|
|
135
|
+
hamming_distance: int,
|
|
136
|
+
threshold: int,
|
|
137
|
+
hash_bits: int,
|
|
138
|
+
):
|
|
139
|
+
self.matches = matches
|
|
140
|
+
self.hamming_distance = hamming_distance
|
|
141
|
+
self.threshold = threshold
|
|
142
|
+
self.hash_bits = hash_bits
|
|
143
|
+
self.similarity_pct = round(
|
|
144
|
+
100 * (1 - hamming_distance / hash_bits), 1
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
def __repr__(self) -> str:
|
|
148
|
+
status = "MATCH" if self.matches else "MISMATCH"
|
|
149
|
+
return (
|
|
150
|
+
f"BindingComparisonResult({status}, "
|
|
151
|
+
f"distance={self.hamming_distance}/{self.hash_bits}, "
|
|
152
|
+
f"similarity={self.similarity_pct}%, "
|
|
153
|
+
f"threshold={self.threshold})"
|
|
154
|
+
)
|