# digital signature algorithm (DSA) small numbers
import hashlib

# public parameters
p = 283
q = 47          # q divides p-1  (282 = 47*6)
h = 2
g = pow(h, (p-1)//q, p)

x = 24                  # private key
y = pow(g, x, p)        # public key

msg = "hello"
H = int(hashlib.sha1(msg.encode()).hexdigest(), 16) % q

# signing
k = 5
r = pow(g, k, p) % q
s = (pow(k, -1, q) * (H + x*r)) % q
print("g =", g, " y =", y, " hash =", H)
print("signature (r,s) =", (r, s))

# verifying
w = pow(s, -1, q)
u1 = (H * w) % q
u2 = (r * w) % q
v = ((pow(g, u1, p) * pow(y, u2, p)) % p) % q
print("v =", v)
if v == r:
    print("signature is valid")
else:
    print("signature is NOT valid")
