初始版本:基于 DHT 的去中心化聊天客户端

- 纯标准库实现 Kademlia DHT(UDP + asyncio),报文 Ed25519 签名认证
- 超过 1200 字节的载荷自动分片与重组,上限 1 MiB
- 公共聊天室:成员公告 + DHT 日志回放,迟到入群者也能补到历史
- 一对一私聊:X25519 + HKDF + AEAD 端到端加密,支持离线信箱
- Tkinter 图形界面,asyncio 运行在后台线程,事件经队列回传 UI
- 局域网组播自动发现 + 手动引导地址(-b)两种互联方式
- run.cmd / start.bat 启动脚本,自动寻找 py -3 或 python
- 48 个单元测试覆盖密码学原语、DHT 路由/协议与聊天层

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
MrhongxingandCopilot committed 2026-09-18 17:38:36 +08:00
commit e002ba9f62
19 files changed
+5064

No files matched your search

+328
View File
@@ -0,0 +1,328 @@
"""Pure-standard-library cryptography for dhtchat.
Implements Ed25519 (RFC 8032), X25519 (RFC 7748) and an AEAD built from
HKDF-SHA256 + HMAC-SHA256 + a SHA-256 counter keystream.
Only ``hashlib``/``hmac``/``os`` are used so the application runs on a stock
Windows Python installation with no third-party packages.
"""
from __future__ import annotations
import hashlib
import hmac
import os
# --------------------------------------------------------------------------
# Curve constants
# --------------------------------------------------------------------------
P = 2 ** 255 - 19
L = 2 ** 252 + 27742317777372353535851937790883648493
D = -121665 * pow(121666, P - 2, P) % P
I = pow(2, (P - 1) // 4, P)
PUBLIC_KEY_LEN = 32
PRIVATE_KEY_LEN = 32
SIGNATURE_LEN = 64
SHARED_SECRET_LEN = 32
AEAD_SALT_LEN = 16
AEAD_NONCE_LEN = 12
AEAD_TAG_LEN = 16
def _sha512(data: bytes) -> bytes:
return hashlib.sha512(data).digest()
def _inv(x: int) -> int:
return pow(x, P - 2, P)
# --------------------------------------------------------------------------
# Ed25519 group arithmetic (extended twisted Edwards coordinates)
# A point is the tuple (X, Y, Z, T) with x = X/Z, y = Y/Z and T = X*Y/Z.
# --------------------------------------------------------------------------
IDENTITY = (0, 1, 1, 0)
_BY = 4 * _inv(5) % P
def _xrecover(y: int) -> int:
xx = (y * y - 1) * _inv(D * y * y + 1) % P
x = pow(xx, (P + 3) // 8, P)
if (x * x - xx) % P:
x = x * I % P
if x % 2:
x = P - x
return x
_BX = _xrecover(_BY)
BASE = (_BX, _BY, 1, _BX * _BY % P)
def _edwards(p1, p2):
"""Unified (also complete for Ed25519) addition for a = -1."""
x1, y1, z1, t1 = p1
x2, y2, z2, t2 = p2
a = (y1 - x1) * (y2 - x2) % P
b = (y1 + x1) * (y2 + x2) % P
c = t1 * 2 * D * t2 % P
d = z1 * 2 * z2 % P
e = b - a
f = d - c
g = d + c
h = b + a
return (e * f % P, g * h % P, f * g % P, e * h % P)
def _scalarmult(point, scalar: int):
if scalar == 0:
return IDENTITY
result = IDENTITY
addend = point
while scalar > 0:
if scalar & 1:
result = _edwards(result, addend)
addend = _edwards(addend, addend)
scalar >>= 1
return result
def _is_identity(point) -> bool:
x, y, z, _ = point
return x % P == 0 and (y - z) % P == 0
def _points_equal(p1, p2) -> bool:
x1, y1, z1, _ = p1
x2, y2, z2, _ = p2
return (x1 * z2 - x2 * z1) % P == 0 and (y1 * z2 - y2 * z1) % P == 0
def _encode_point(point) -> bytes:
x, y, z, _ = point
zi = _inv(z)
x = x * zi % P
y = y * zi % P
return (y | ((x & 1) << 255)).to_bytes(32, "little")
def _decode_point(encoded: bytes):
if len(encoded) != 32:
raise ValueError("point must be 32 bytes")
data = int.from_bytes(encoded, "little")
y = data & ((1 << 255) - 1)
if y >= P:
raise ValueError("non-canonical point encoding")
sign = encoded[31] >> 7
x = _xrecover(y)
if (x & 1) != sign:
x = P - x
if (-x * x + y * y - 1 - D * x * x * y * y) % P:
raise ValueError("point is not on the curve")
return (x, y, 1, x * y % P)
def _is_small_order(point) -> bool:
return _is_identity(_scalarmult(point, 8))
# --------------------------------------------------------------------------
# Ed25519 public API
# --------------------------------------------------------------------------
def generate_private_key() -> bytes:
"""Return a fresh random 32-byte Ed25519 seed."""
return os.urandom(PRIVATE_KEY_LEN)
def _expanded_private_key(seed: bytes):
if len(seed) != PRIVATE_KEY_LEN:
raise ValueError("private key must be 32 bytes")
digest = _sha512(seed)
scalar = bytearray(digest[:32])
scalar[0] &= 248
scalar[31] &= 127
scalar[31] |= 64
return int.from_bytes(bytes(scalar), "little"), digest[32:]
def ed25519_public_key(seed: bytes) -> bytes:
scalar, _ = _expanded_private_key(seed)
return _encode_point(_scalarmult(BASE, scalar))
def ed25519_sign(seed: bytes, message: bytes) -> bytes:
scalar, prefix = _expanded_private_key(seed)
public = _encode_point(_scalarmult(BASE, scalar))
r = int.from_bytes(_sha512(prefix + message), "little") % L
r_point = _encode_point(_scalarmult(BASE, r))
k = int.from_bytes(_sha512(r_point + public + message), "little") % L
s = (r + k * scalar) % L
return r_point + s.to_bytes(32, "little")
def ed25519_verify(public: bytes, message: bytes, signature: bytes) -> bool:
if len(public) != PUBLIC_KEY_LEN or len(signature) != SIGNATURE_LEN:
return False
try:
a_point = _decode_point(public)
r_point = _decode_point(signature[:32])
except ValueError:
return False
if _is_small_order(a_point) or _is_small_order(r_point):
return False
s = int.from_bytes(signature[32:], "little")
if s >= L:
return False
k = int.from_bytes(_sha512(signature[:32] + public + message), "little") % L
left = _scalarmult(BASE, s)
right = _edwards(r_point, _scalarmult(a_point, k))
return _points_equal(left, right)
# --------------------------------------------------------------------------
# X25519 (RFC 7748)
# --------------------------------------------------------------------------
def x25519(private_scalar: bytes, peer_public: bytes) -> bytes:
if len(private_scalar) != 32 or len(peer_public) != 32:
raise ValueError("x25519 inputs must be 32 bytes")
scalar = bytearray(private_scalar)
scalar[0] &= 248
scalar[31] &= 127
scalar[31] |= 64
k = int.from_bytes(bytes(scalar), "little")
x1 = int.from_bytes(peer_public, "little") & ((1 << 255) - 1)
x2, z2, x3, z3 = 1, 0, x1, 1
swap = 0
for bit in reversed(range(255)):
kt = (k >> bit) & 1
swap ^= kt
if swap:
x2, x3 = x3, x2
z2, z3 = z3, z2
swap = kt
a = (x2 + z2) % P
aa = a * a % P
b = (x2 - z2) % P
bb = b * b % P
e = (aa - bb) % P
c = (x3 + z3) % P
d = (x3 - z3) % P
da = d * a % P
cb = c * b % P
x3 = pow(da + cb, 2, P)
z3 = x1 * pow(da - cb, 2, P) % P
x2 = aa * bb % P
z2 = e * (aa + 121665 * e) % P
if swap:
x2, x3 = x3, x2
z2, z3 = z3, z2
if z2 % P == 0:
raise ValueError("x25519 produced the all-zero shared secret")
return (x2 * _inv(z2) % P).to_bytes(32, "little")
def ed25519_private_to_x25519(seed: bytes) -> bytes:
"""Convert an Ed25519 seed into an X25519 scalar."""
if len(seed) != PRIVATE_KEY_LEN:
raise ValueError("private key must be 32 bytes")
return hashlib.sha512(seed).digest()[:32]
def ed25519_public_to_x25519(public: bytes) -> bytes:
"""Convert an Ed25519 public key into an X25519 public key (u-coordinate)."""
if len(public) != PUBLIC_KEY_LEN:
raise ValueError("public key must be 32 bytes")
y = int.from_bytes(public, "little") & ((1 << 255) - 1)
if y >= P:
raise ValueError("non-canonical public key")
if (1 - y) % P == 0:
raise ValueError("public key has no X25519 counterpart")
return ((1 + y) * _inv((1 - y) % P) % P).to_bytes(32, "little")
def shared_secret(seed: bytes, peer_public: bytes) -> bytes:
"""X25519 ECDH between our Ed25519 seed and a peer's Ed25519 public key."""
return x25519(ed25519_private_to_x25519(seed), ed25519_public_to_x25519(peer_public))
# --------------------------------------------------------------------------
# HKDF-SHA256 and AEAD
# --------------------------------------------------------------------------
def hkdf_sha256(secret: bytes, salt: bytes, info: bytes, length: int) -> bytes:
prk = hmac.new(salt or b"\x00" * 32, secret, hashlib.sha256).digest()
output = bytearray()
block = b""
counter = 1
while len(output) < length:
block = hmac.new(prk, block + info + bytes([counter]), hashlib.sha256).digest()
output += block
counter += 1
return bytes(output[:length])
def _keystream(key: bytes, nonce: bytes, length: int) -> bytes:
output = bytearray()
counter = 0
while len(output) < length:
output += hashlib.sha256(key + nonce + counter.to_bytes(8, "big")).digest()
counter += 1
return bytes(output[:length])
def _xor(data: bytes, other: bytes) -> bytes:
if not data:
return b""
return (
int.from_bytes(data, "big") ^ int.from_bytes(other, "big")
).to_bytes(len(data), "big")
def _derive_aead_keys(key: bytes, salt: bytes):
enc = hkdf_sha256(key, salt, b"dhtchat/v1 enc", 32)
mac = hkdf_sha256(key, salt, b"dhtchat/v1 mac", 32)
return enc, mac
def aead_encrypt(key: bytes, plaintext: bytes, aad: bytes = b"") -> bytes:
"""Encrypt with a random salt+nonce; returns salt || nonce || ciphertext || tag."""
salt = os.urandom(AEAD_SALT_LEN)
nonce = os.urandom(AEAD_NONCE_LEN)
enc_key, mac_key = _derive_aead_keys(key, salt)
stream = _keystream(enc_key, nonce, len(plaintext))
ciphertext = _xor(plaintext, stream)
tag = hmac.new(mac_key, salt + nonce + aad + ciphertext, hashlib.sha256).digest()
return salt + nonce + ciphertext + tag[:AEAD_TAG_LEN]
def aead_decrypt(key: bytes, blob: bytes, aad: bytes = b"") -> bytes:
minimum = AEAD_SALT_LEN + AEAD_NONCE_LEN + AEAD_TAG_LEN
if len(blob) < minimum:
raise ValueError("ciphertext is too short")
salt = blob[:AEAD_SALT_LEN]
nonce = blob[AEAD_SALT_LEN:AEAD_SALT_LEN + AEAD_NONCE_LEN]
ciphertext = blob[AEAD_SALT_LEN + AEAD_NONCE_LEN:-AEAD_TAG_LEN]
tag = blob[-AEAD_TAG_LEN:]
enc_key, mac_key = _derive_aead_keys(key, salt)
expected = hmac.new(
mac_key, salt + nonce + aad + ciphertext, hashlib.sha256
).digest()[:AEAD_TAG_LEN]
if not hmac.compare_digest(tag, expected):
raise ValueError("message authentication failed")
return _xor(ciphertext, _keystream(enc_key, nonce, len(ciphertext)))
# --------------------------------------------------------------------------
# Helpers
# --------------------------------------------------------------------------
def fingerprint(public: bytes, length: int = 16) -> str:
"""Short human readable fingerprint of a public key (SHA-1 based)."""
return hashlib.sha1(public).hexdigest()[:length]
def node_id_from_public(public: bytes) -> bytes:
"""20-byte node id derived from the public key (SHA-1, Kademlia space)."""
return hashlib.sha1(public).digest()