swisspost-evoting-go-poc/pkg/math/primes.go
saymrwulf e8b6f30871 Swiss Post E-Voting Go PoC
Proof-of-concept reimplementation of the Swiss Post e-voting
cryptographic protocol in Go. Single binary, 52 source files,
2 dependencies. Covers ElGamal encryption, Bayer-Groth verifiable
shuffles, zero-knowledge proofs, return codes, and a full
election ceremony demo.
2026-02-13 19:53:09 +01:00

40 lines
1 KiB
Go

package math
import (
"math/big"
)
// SmallPrimes returns the first n small primes starting from 2.
func SmallPrimes(n int) []*big.Int {
primes := make([]*big.Int, 0, n)
candidate := big.NewInt(2)
for len(primes) < n {
if candidate.ProbablyPrime(20) {
primes = append(primes, new(big.Int).Set(candidate))
}
candidate = new(big.Int).Add(candidate, big.NewInt(1))
}
return primes
}
// Factorize attempts to factorize value as a product of elements from allowedPrimes.
// Returns the prime factors. Panics if factorization fails.
func Factorize(value *big.Int, allowedPrimes []*big.Int) []*big.Int {
remaining := new(big.Int).Set(value)
factors := make([]*big.Int, 0)
for _, p := range allowedPrimes {
for {
quo, rem := new(big.Int).DivMod(remaining, p, new(big.Int))
if rem.Sign() == 0 {
factors = append(factors, new(big.Int).Set(p))
remaining = quo
} else {
break
}
}
}
if remaining.Cmp(big.NewInt(1)) != 0 {
panic("factorization failed: remaining = " + remaining.String())
}
return factors
}