k = 3 # the number of shares needed to decrypt secret n = 5 # the number of shares p = random_prime(1 << 128) Fp = GF(p) P.<x> = PolynomialRing(Fp) a = randint(2, p-1) # secret coeffs = [a] + [randint(2, p-1) for _ in range(k-1)] f = P(coeffs) shares = [(i, f(i)) for i in range(1, n+1)] import random for _ in range(10): sample = random.sample(shares, k=random.randint(k, n)) f_ = P.lagrange_polynomial(sample) print(f_.constant_coefficient() == a)