In our previous post, we built a privacy-preserving, verifiable Yes/No referendum using partially homomorphic encryption, zero-knowledge proofs and threshold decryption. But real-world elections are rarely binary: they have multiple candidates, parties, or choices. That raises a new question: how do we tally votes for many options under encryption, without one candidate’s count bleeding into another’s, while still proving that every ballot is valid?

LightPHE offers two strategies, and the cryptosystem you choose decides which ones are available:
🙋♂️ You may consider to enroll my top-rated cryptography course on Udemy
- Base encoding packs every candidate’s tally into a single ciphertext by encrypting a vote for candidate k as base^k. The decrypted tally is a large number, so this needs a cryptosystem with a large plaintext space and direct decryption. So, Paillier or Damgard-Jurik are strong candidates for this approach.
- One-hot encodes each ballot as an array of 0/1 ciphertexts, one per candidate, with a proof that exactly one slot is 1. Each candidate’s count stays small, so it works with Exponential ElGamal and Elliptic Curve ElGamal as well as Paillier and Damgard-Jurik.
Both approaches rely on the same building blocks: homomorphic addition to tally ballots without decrypting them, zero-knowledge proofs that every ballot is valid and bound to its voter, and threshold decryption in which trustees prove their partial results are correct, so no single party can read individual votes or fake the outcome.
In this post, we’ll dive into both approaches, compare their trade-offs, and walk through complete implementations in Python, Go, Java, and TypeScript.
Designing a Multi-Candidate E-Voting System
Our system will use four building blocks, all of which apply to both approaches:
1. Homomorphic addition. Ballots are summed while still encrypted, so individual votes are never decrypted.
2. Zero-knowledge proofs of ballot validity. These are OR-proofs, meaning they show a ballot encrypts one of the allowed values without revealing which:
- Base encoding: a proof that the ciphertext encrypts one of base^0, base^1, …, base^(k−1).
- One-hot: a proof that each slot is 0 or 1, plus a proof that the slots add up to 1. Voting for two parties, voting twice for one party, or leaving every slot empty all fail verification.
3. Binding each proof to its voter. Each proof is tied to the voter’s identity (context = voter). That’s why, in the code below, Mallory’s copy of Alice’s ballot fails to verify, and so do Oscar’s tampered ballots: doubling a base-encoded ballot to vote twice, or reordering the slots of a one-hot ballot to move his vote to another party. The context is just a public string, so the bulletin board that collects ballots must also authenticate voters, accept a ballot only for the ID of the authenticated voter, and accept at most one ballot per ID.
4. Verifiable threshold decryption. A dealer splits the private key among trustees (any 2 out of 3 in our examples) and forgets it. Any 2 trustees decrypt the tally partially, and each partial decryption carries a proof that it was computed with the trustee’s own share. This matters: without these proofs, a trustee nominated by one party can tamper with its partial decryption and quietly add 50 votes to its own party, because the Lagrange coefficients of the other trustees are public. With the proofs, the forged partial decryption is discarded and the honest trustees still decrypt the correct tally.
Approach 1: Base Encoding (Single Ciphertext)
In this approach, we utilize cryptosystems with a large plaintext space like Paillier or Damgard-Jurik. Instead of creating multiple ciphertexts for each candidate, we pack all party votes into a single ciphertext using a chosen base (B).
For instance, if our base is 100, a vote for a party k is encrypted as 100k.
Red (Index 0): 1000 = 1
Green (Index 1): 1001 = 100
Blue (Index 2): 1002 = 10000
During tallying, all individual ballots are homomorphically added together into one single ciphertext. When the trustees decrypt the final tally, the result is a packed integer (e.g., 10002), which can be easily split by reading digits from right to left: 2 votes for red, 0 for green and 1 for blue. The base must be greater than the number of votes a party can get—with base 100, a party can get at most 99 votes, since 100 votes for red would carry into green’s digit. Use a larger base for real elections, e.g. 1000001 for a million votes per party.
While Exponential-ElGamal or EC-ElGamal are additively homomorphic as well, their decryption requires solving a discrete logarithm, which is only feasible for small numbers. A packed tally like 10002—let alone one with a base of a million—is far beyond that. Therefore, this approach is reserved for schemes that decrypt directly, like Paillier and Damgard-Jurik. Their keys must be generated with safe_primes = True so that trustees can prove their partial decryptions.
from lightphe import LightPHE
# dealer generates the key, splits it among 3 trustees (any 2 can decrypt), then forgets it.
# safe primes let trustees prove their partial decryptions with Paillier
dealer_cs = LightPHE(algorithm_name = "Paillier", safe_primes = True)
share_keys = dealer_cs.generate_threshold_keys(threshold = 2, parties = 3)
dealer_cs.export_keys(target_file = "public.txt", public = True)
# each share key is sent to its own trustee secretly
trustees = [LightPHE(algorithm_name = "Paillier", keys = keys) for keys in share_keys]
# everyone else works with the public key only
public_cs = LightPHE(algorithm_name = "Paillier", key_file = "public.txt")
# a vote for party k is encrypted as 100^k, i.e. 1 for red, 100 for green and 10000 for blue
parties = ["red", "green", "blue"]
values = [100 ** k for k in range(len(parties))]
# each voter encrypts a vote for one party with a proof that it is one of the allowed values
alice_ballot, alice_proof = public_cs.encrypt_with_proof(values[0], values = values, context = "alice")
bob_ballot, bob_proof = public_cs.encrypt_with_proof(values[2], values = values, context = "bob")
carol_ballot, carol_proof = public_cs.encrypt_with_proof(values[0], values = values, context = "carol")
# anyone verifies the published ballots without decrypting them
assert public_cs.verify_ciphertext(alice_ballot, alice_proof, values = values, context = "alice") is True
assert public_cs.verify_ciphertext(bob_ballot, bob_proof, values = values, context = "bob") is True
assert public_cs.verify_ciphertext(carol_ballot, carol_proof, values = values, context = "carol") is True
# mallory's copy of alice's ballot is rejected
assert public_cs.verify_ciphertext(alice_ballot, alice_proof, values = values, context = "mallory") is False
# oscar doubles his ballot to vote twice for green, but 2 x 100 is not an allowed value
oscar_ballot, oscar_proof = public_cs.encrypt_with_proof(values[1], values = values, context = "oscar")
assert public_cs.verify_ciphertext(oscar_ballot + oscar_ballot, oscar_proof, values = values, context = "oscar") is False
# valid ballots are tallied homomorphically into a single ciphertext
tally = alice_ballot + bob_ballot + carol_ballot
# any 2 trustees decrypt the tally partially with proofs, and anyone combines them
partials = [trustee.partial_decrypt(tally, prove = True) for trustee in trustees[:2]]
result = public_cs.combine_partial_decryptions(tally, partials, verify = True)
# tally is 2 x 1 + 0 x 100 + 1 x 10000 = 10002, read 2 digits at a time from right: 1 | 00 | 02
votes = {party: (result // 100 ** k) % 100 for k, party in enumerate(parties)}
assert votes == {"red": 2, "green": 0, "blue": 1}
package main
import (
"fmt"
"log"
"math/big"
"github.com/serengil/lightphe-go/lightphe"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func mustBeValid(valid bool, err error, voter string) {
check(err)
if !valid {
log.Fatalf("ballot of %s is rejected", voter)
}
}
func main() {
// dealer generates the key, splits it among 3 trustees (any 2 can decrypt), then forgets it.
// safe primes let trustees prove their partial decryptions with Paillier
dealerCs, err := lightphe.New(lightphe.Paillier, lightphe.WithSafePrimes(true))
check(err)
publicKey, shareKeys, err := dealerCs.GenerateThresholdKeys(2, 3)
check(err)
// everyone else works with the public key only
publicCs, err := lightphe.New(lightphe.Paillier, lightphe.WithKeys(publicKey))
check(err)
// a vote for party k is encrypted as 100^k, i.e. 1 for red, 100 for green and 10000 for blue
parties := []string{"red", "green", "blue"}
values := []*big.Int{big.NewInt(1), big.NewInt(100), big.NewInt(10000)}
// each voter encrypts a vote for one party with a proof that it is one of the allowed values
aliceBallot, aliceProof, err := publicCs.EncryptWithProof(values[0], values, "alice")
check(err)
bobBallot, bobProof, err := publicCs.EncryptWithProof(values[2], values, "bob")
check(err)
carolBallot, carolProof, err := publicCs.EncryptWithProof(values[0], values, "carol")
check(err)
// anyone verifies the published ballots without decrypting them
valid, err := publicCs.VerifyCiphertext(aliceBallot, aliceProof, values, "alice")
mustBeValid(valid, err, "alice")
valid, err = publicCs.VerifyCiphertext(bobBallot, bobProof, values, "bob")
mustBeValid(valid, err, "bob")
valid, err = publicCs.VerifyCiphertext(carolBallot, carolProof, values, "carol")
mustBeValid(valid, err, "carol")
// mallory's copy of alice's ballot is rejected
valid, err = publicCs.VerifyCiphertext(aliceBallot, aliceProof, values, "mallory")
check(err)
if valid {
log.Fatal("mallory's copy of alice's ballot is accepted")
}
// oscar doubles his ballot to vote twice for green, but 2 x 100 is not an allowed value
oscarBallot, oscarProof, err := publicCs.EncryptWithProof(values[1], values, "oscar")
check(err)
doubled, err := oscarBallot.Add(oscarBallot)
check(err)
valid, err = publicCs.VerifyCiphertext(doubled, oscarProof, values, "oscar")
check(err)
if valid {
log.Fatal("oscar's doubled ballot is accepted")
}
// valid ballots are tallied homomorphically into a single ciphertext
tally, err := aliceBallot.Add(bobBallot)
check(err)
tally, err = tally.Add(carolBallot)
check(err)
// any 2 trustees decrypt the tally partially with proofs, and anyone combines them
var partials []*lightphe.PartialDecryption
for _, keys := range shareKeys[:2] {
trustee, err := lightphe.New(lightphe.Paillier, lightphe.WithKeys(keys))
check(err)
partial, err := trustee.PartialDecrypt(tally, true)
check(err)
partials = append(partials, partial)
}
result, err := publicCs.CombinePartialDecryptions(tally, partials, true)
check(err)
// tally is 2 x 1 + 0 x 100 + 1 x 10000 = 10002, read 2 digits at a time from right: 1 | 00 | 02
votes := map[string]int64{}
for _, party := range parties {
digit := new(big.Int)
result.DivMod(result, big.NewInt(100), digit)
votes[party] = digit.Int64()
}
fmt.Println(votes) // map[blue:1 green:0 red:2]
}
import io.github.serengil.lightphe.LightPHE;
import io.github.serengil.lightphe.model.Ciphertext;
import io.github.serengil.lightphe.model.Keys;
import io.github.serengil.lightphe.model.PartialDecryption;
import io.github.serengil.lightphe.model.Proven;
import java.math.BigInteger;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
// dealer generates the key, splits it among 3 trustees (any 2 can decrypt), then forgets it.
// safe primes let trustees prove their partial decryptions with Paillier
LightPHE dealerCs = LightPHE.builder().algorithmName("Paillier").safePrimes(true).build();
List<Keys> shareKeys = dealerCs.generateThresholdKeys(2, 3);
dealerCs.exportKeys(Path.of("public.txt"), true);
// each share key is sent to its own trustee secretly
List<LightPHE> trustees = shareKeys.stream()
.map(keys -> LightPHE.builder().algorithmName("Paillier").keys(keys).build())
.toList();
// everyone else works with the public key only
LightPHE publicCs = LightPHE.builder()
.algorithmName("Paillier")
.keyFile(Path.of("public.txt"))
.build();
// a vote for party k is encrypted as 100^k, i.e. 1 for red, 100 for green and 10000 for blue
List<String> parties = List.of("red", "green", "blue");
List<Long> values = List.of(1L, 100L, 10000L);
// each voter encrypts a vote for one party with a proof that it is one of the allowed values
Proven<Ciphertext> alice = publicCs.encryptWithProof(values.get(0), values, "alice");
Proven<Ciphertext> bob = publicCs.encryptWithProof(values.get(2), values, "bob");
Proven<Ciphertext> carol = publicCs.encryptWithProof(values.get(0), values, "carol");
// anyone verifies the published ballots without decrypting them
assert publicCs.verifyCiphertext(alice.value(), alice.proof(), values, "alice");
assert publicCs.verifyCiphertext(bob.value(), bob.proof(), values, "bob");
assert publicCs.verifyCiphertext(carol.value(), carol.proof(), values, "carol");
// mallory's copy of alice's ballot is rejected
assert !publicCs.verifyCiphertext(alice.value(), alice.proof(), values, "mallory");
// oscar doubles his ballot to vote twice for green, but 2 x 100 is not an allowed value
Proven<Ciphertext> oscar = publicCs.encryptWithProof(values.get(1), values, "oscar");
Ciphertext doubled = oscar.value().add(oscar.value());
assert !publicCs.verifyCiphertext(doubled, oscar.proof(), values, "oscar");
// valid ballots are tallied homomorphically into a single ciphertext
Ciphertext tally = alice.value().add(bob.value()).add(carol.value());
// any 2 trustees decrypt the tally partially with proofs, and anyone combines them
List<PartialDecryption> partials = trustees.subList(0, 2).stream()
.map(trustee -> trustee.partialDecrypt(tally, true))
.toList();
BigInteger result = publicCs.combinePartialDecryptions(tally, partials, true);
// tally is 2 x 1 + 0 x 100 + 1 x 10000 = 10002, read 2 digits at a time from right: 1 | 00 | 02
List<BigInteger> votes = new ArrayList<>();
for (int k = 0; k < parties.size(); k++) {
votes.add(result.divide(BigInteger.valueOf(100).pow(k)).mod(BigInteger.valueOf(100)));
}
assert votes.equals(List.of(BigInteger.TWO, BigInteger.ZERO, BigInteger.ONE));
import { LightPHE } from 'lightphe-ts';
// dealer generates the key, splits it among 3 trustees (any 2 can decrypt), then forgets it.
// safe primes let trustees prove their partial decryptions with Paillier
const dealerCs = new LightPHE({ algorithmName: 'Paillier', safePrimes: true });
const shareKeys = dealerCs.generateThresholdKeys(2, 3);
dealerCs.exportKeys('public.txt', true);
// each share key is sent to its own trustee secretly
const trustees = shareKeys.map((keys) => new LightPHE({ algorithmName: 'Paillier', keys }));
// everyone else works with the public key only
const publicCs = new LightPHE({ algorithmName: 'Paillier', keyFile: 'public.txt' });
// a vote for party k is encrypted as 100^k, i.e. 1 for red, 100 for green and 10000 for blue
const parties = ['red', 'green', 'blue'];
const values = parties.map((_, k) => 100n ** BigInt(k));
// each voter encrypts a vote for one party with a proof, and anyone verifies it
const ballots = [
['alice', 'red'],
['bob', 'blue'],
['carol', 'red'],
].map(([voter, party]) => {
const [ballot, proof] = publicCs.encryptWithProof(values[parties.indexOf(party)], {
values,
context: voter,
});
console.assert(publicCs.verifyCiphertext(ballot, proof, { values, context: voter }));
// mallory's copy of the ballot is rejected
console.assert(!publicCs.verifyCiphertext(ballot, proof, { values, context: 'mallory' }));
return ballot;
});
// oscar doubles his ballot to vote twice for green, but 2 x 100 is not an allowed value
const [oscarBallot, oscarProof] = publicCs.encryptWithProof(values[1], {
values,
context: 'oscar',
});
console.assert(
!publicCs.verifyCiphertext(oscarBallot.add(oscarBallot), oscarProof, {
values,
context: 'oscar',
})
);
// valid ballots are tallied homomorphically into a single ciphertext
const tally = ballots.reduce((sum, ballot) => sum.add(ballot));
// any 2 trustees decrypt the tally partially with proofs, and anyone combines them
const partials = trustees.slice(0, 2).map((trustee) => trustee.partialDecrypt(tally, { prove: true }));
const result = publicCs.combinePartialDecryptions(tally, partials, { verify: true });
// tally is 2 x 1 + 0 x 100 + 1 x 10000 = 10002, read 2 digits at a time from right: 1 | 00 | 02
const votes = parties.map((_, k) => (result / 100n ** BigInt(k)) % 100n);
console.assert(votes.join() === '2,0,1');
Approach 2: One-Hot Encoding (One Ciphertext per Party)
In this approach, rather than packing all party votes into a single integer, each voter casts a vote as a one-hot vector (e.g., [1, 0, 0, 0] for a vote to the first party).
Supported by cryptosystems like Exponential-ElGamal, EC-ElGamal, Paillier, and Damgard-Jurik, individual ballots consist of an array of ciphertexts along with zero-knowledge proofs. During tallying, votes are summed slot by slot, meaning each party’s votes are counted independently in its own dedicated ciphertext slot. The trustees then decrypt each party’s count separately. Exponential-ElGamal keys must be generated with prime_order = True for the proofs and threshold decryption.
from lightphe import LightPHE
# dealer generates the key, splits it among 3 trustees (any 2 can decrypt), then forgets it
dealer_cs = LightPHE(algorithm_name = "Exponential-ElGamal", prime_order = True)
share_keys = dealer_cs.generate_threshold_keys(threshold = 2, parties = 3)
dealer_cs.export_keys(target_file = "public.txt", public = True)
# each share key is sent to its own trustee secretly
trustees = [LightPHE(algorithm_name = "Exponential-ElGamal", keys = keys) for keys in share_keys]
# everyone else works with the public key only
public_cs = LightPHE(algorithm_name = "Exponential-ElGamal", key_file = "public.txt")
parties = ["red", "green", "blue", "yellow"]
# each voter encrypts a vote for one party as a one-hot ballot with a proof
alice_ballot, alice_proof = public_cs.encrypt_one_hot(parties.index("red"), options = len(parties), context = "alice")
bob_ballot, bob_proof = public_cs.encrypt_one_hot(parties.index("blue"), options = len(parties), context = "bob")
carol_ballot, carol_proof = public_cs.encrypt_one_hot(parties.index("red"), options = len(parties), context = "carol")
# anyone verifies the published ballots without decrypting them
assert public_cs.verify_one_hot(alice_ballot, alice_proof, context = "alice") is True
assert public_cs.verify_one_hot(bob_ballot, bob_proof, context = "bob") is True
assert public_cs.verify_one_hot(carol_ballot, carol_proof, context = "carol") is True
# mallory's copy of alice's ballot is rejected
assert public_cs.verify_one_hot(alice_ballot, alice_proof, context = "mallory") is False
# oscar reorders the slots of his ballot to move his vote to another party, but the proof breaks
oscar_ballot, oscar_proof = public_cs.encrypt_one_hot(parties.index("green"), options = len(parties), context = "oscar")
reordered = oscar_ballot[1:] + oscar_ballot[:1]
assert public_cs.verify_one_hot(reordered, oscar_proof, context = "oscar") is False
# valid ballots are summed slot by slot, so each party's votes are counted in its own ciphertext
tally = [a + b + c for a, b, c in zip(alice_ballot, bob_ballot, carol_ballot)]
# any 2 trustees decrypt each party's count partially with proofs, and anyone combines them
votes = {}
for party, count in zip(parties, tally):
partials = [trustee.partial_decrypt(count, prove = True) for trustee in trustees[:2]]
votes[party] = public_cs.combine_partial_decryptions(count, partials, verify = True)
assert votes == {"red": 2, "green": 0, "blue": 1, "yellow": 0}
package main
import (
"fmt"
"log"
"github.com/serengil/lightphe-go/lightphe"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func mustBeValid(valid bool, err error, voter string) {
check(err)
if !valid {
log.Fatalf("ballot of %s is rejected", voter)
}
}
func main() {
// dealer generates the key, splits it among 3 trustees (any 2 can decrypt), then forgets it
dealerCs, err := lightphe.New(lightphe.ExponentialElGamal, lightphe.WithPrimeOrder(true))
check(err)
publicKey, shareKeys, err := dealerCs.GenerateThresholdKeys(2, 3)
check(err)
// everyone else works with the public key only
publicCs, err := lightphe.New(lightphe.ExponentialElGamal, lightphe.WithKeys(publicKey))
check(err)
parties := []string{"red", "green", "blue", "yellow"}
// each voter encrypts a vote for one party as a one-hot ballot with a proof
aliceBallot, aliceProof, err := publicCs.EncryptOneHot(0, len(parties), "alice") // red
check(err)
bobBallot, bobProof, err := publicCs.EncryptOneHot(2, len(parties), "bob") // blue
check(err)
carolBallot, carolProof, err := publicCs.EncryptOneHot(0, len(parties), "carol") // red
check(err)
// anyone verifies the published ballots without decrypting them
valid, err := publicCs.VerifyOneHot(aliceBallot, aliceProof, "alice")
mustBeValid(valid, err, "alice")
valid, err = publicCs.VerifyOneHot(bobBallot, bobProof, "bob")
mustBeValid(valid, err, "bob")
valid, err = publicCs.VerifyOneHot(carolBallot, carolProof, "carol")
mustBeValid(valid, err, "carol")
// mallory's copy of alice's ballot is rejected
valid, err = publicCs.VerifyOneHot(aliceBallot, aliceProof, "mallory")
check(err)
if valid {
log.Fatal("mallory's copy of alice's ballot is accepted")
}
// oscar reorders the slots of his ballot to move his vote to another party, but the proof breaks
oscarBallot, oscarProof, err := publicCs.EncryptOneHot(1, len(parties), "oscar") // green
check(err)
reordered := append([]*lightphe.Ciphertext{}, oscarBallot[1:]...)
reordered = append(reordered, oscarBallot[0])
valid, err = publicCs.VerifyOneHot(reordered, oscarProof, "oscar")
check(err)
if valid {
log.Fatal("oscar's reordered ballot is accepted")
}
// valid ballots are summed slot by slot, and any 2 trustees decrypt each party's count
votes := map[string]int64{}
for k, party := range parties {
count, err := aliceBallot[k].Add(bobBallot[k])
check(err)
count, err = count.Add(carolBallot[k])
check(err)
var partials []*lightphe.PartialDecryption
for _, keys := range shareKeys[:2] {
trustee, err := lightphe.New(lightphe.ExponentialElGamal, lightphe.WithKeys(keys))
check(err)
partial, err := trustee.PartialDecrypt(count, true)
check(err)
partials = append(partials, partial)
}
result, err := publicCs.CombinePartialDecryptions(count, partials, true)
check(err)
votes[party] = result.Int64()
}
fmt.Println(votes) // map[blue:1 green:0 red:2 yellow:0]
}
import io.github.serengil.lightphe.LightPHE;
import io.github.serengil.lightphe.model.Ciphertext;
import io.github.serengil.lightphe.model.Keys;
import io.github.serengil.lightphe.model.PartialDecryption;
import io.github.serengil.lightphe.model.Proven;
import java.math.BigInteger;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
// dealer generates the key, splits it among 3 trustees (any 2 can decrypt), then forgets it
LightPHE dealerCs =
LightPHE.builder().algorithmName("Exponential-ElGamal").primeOrder(true).build();
List<Keys> shareKeys = dealerCs.generateThresholdKeys(2, 3);
dealerCs.exportKeys(Path.of("public.txt"), true);
// each share key is sent to its own trustee secretly
List<LightPHE> trustees = shareKeys.stream()
.map(keys -> LightPHE.builder().algorithmName("Exponential-ElGamal").keys(keys).build())
.toList();
// everyone else works with the public key only
LightPHE publicCs = LightPHE.builder()
.algorithmName("Exponential-ElGamal")
.keyFile(Path.of("public.txt"))
.build();
List<String> parties = List.of("red", "green", "blue", "yellow");
// each voter encrypts a vote for one party as a one-hot ballot with a proof
Proven<List<Ciphertext>> alice = publicCs.encryptOneHot(parties.indexOf("red"), parties.size(), "alice");
Proven<List<Ciphertext>> bob = publicCs.encryptOneHot(parties.indexOf("blue"), parties.size(), "bob");
Proven<List<Ciphertext>> carol = publicCs.encryptOneHot(parties.indexOf("red"), parties.size(), "carol");
// anyone verifies the published ballots without decrypting them
assert publicCs.verifyOneHot(alice.value(), alice.proof(), "alice");
assert publicCs.verifyOneHot(bob.value(), bob.proof(), "bob");
assert publicCs.verifyOneHot(carol.value(), carol.proof(), "carol");
// mallory's copy of alice's ballot is rejected
assert !publicCs.verifyOneHot(alice.value(), alice.proof(), "mallory");
// oscar reorders the slots of his ballot to move his vote to another party, but the proof breaks
Proven<List<Ciphertext>> oscar = publicCs.encryptOneHot(parties.indexOf("green"), parties.size(), "oscar");
List<Ciphertext> reordered = new ArrayList<>(oscar.value().subList(1, parties.size()));
reordered.add(oscar.value().get(0));
assert !publicCs.verifyOneHot(reordered, oscar.proof(), "oscar");
// valid ballots are summed slot by slot, and any 2 trustees decrypt each party's count
List<BigInteger> votes = new ArrayList<>();
for (int k = 0; k < parties.size(); k++) {
Ciphertext count = alice.value().get(k).add(bob.value().get(k)).add(carol.value().get(k));
List<PartialDecryption> partials = trustees.subList(0, 2).stream()
.map(trustee -> trustee.partialDecrypt(count, true))
.toList();
votes.add(publicCs.combinePartialDecryptions(count, partials, true));
}
assert votes.equals(List.of(BigInteger.TWO, BigInteger.ZERO, BigInteger.ONE, BigInteger.ZERO));
import { LightPHE } from 'lightphe-ts';
// dealer generates the key, splits it among 3 trustees (any 2 can decrypt), then forgets it
const dealerCs = new LightPHE({ algorithmName: 'Exponential-ElGamal', primeOrder: true });
const shareKeys = dealerCs.generateThresholdKeys(2, 3);
dealerCs.exportKeys('public.txt', true);
// each share key is sent to its own trustee secretly
const trustees = shareKeys.map(
(keys) => new LightPHE({ algorithmName: 'Exponential-ElGamal', keys })
);
// everyone else works with the public key only
const publicCs = new LightPHE({ algorithmName: 'Exponential-ElGamal', keyFile: 'public.txt' });
const parties = ['red', 'green', 'blue', 'yellow'];
// each voter encrypts a vote for one party as a one-hot ballot with a proof, and anyone verifies it
const ballots = [
['alice', 'red'],
['bob', 'blue'],
['carol', 'red'],
].map(([voter, party]) => {
const [ballot, proof] = publicCs.encryptOneHot(parties.indexOf(party), parties.length, {
context: voter,
});
console.assert(publicCs.verifyOneHot(ballot, proof, { context: voter }));
// mallory's copy of the ballot is rejected
console.assert(!publicCs.verifyOneHot(ballot, proof, { context: 'mallory' }));
return ballot;
});
// oscar reorders the slots of his ballot to move his vote to another party, but the proof breaks
const [oscarBallot, oscarProof] = publicCs.encryptOneHot(parties.indexOf('green'), parties.length, {
context: 'oscar',
});
const reordered = [...oscarBallot.slice(1), oscarBallot[0]];
console.assert(!publicCs.verifyOneHot(reordered, oscarProof, { context: 'oscar' }));
// valid ballots are summed slot by slot, so each party's votes are counted in its own ciphertext
const tally = ballots.reduce((sums, ballot) => sums.map((sum, i) => sum.add(ballot[i])));
// any 2 trustees decrypt each party's count partially with proofs, and anyone combines them
const votes = tally.map((count) => {
const partials = trustees.slice(0, 2).map((trustee) => trustee.partialDecrypt(count, { prove: true }));
return publicCs.combinePartialDecryptions(count, partials, { verify: true });
});
console.assert(votes.join() === '2,0,1,0');
In both approaches, the dealer’s cryptosystem is never used to decrypt anything: it drops the private key right after splitting it, and a single trustee cannot decrypt a tally alone. Java snippets use assert for brevity, so run them with -ea to enable assertions.
Architectural Comparison
When choosing between Base Encoding and One-Hot Encoding for a multi-candidate election system, developers must weigh key trade-offs regarding algorithm compatibility, bandwidth, decryptions, and capacity limits:
| One-hot | Base Encoding | |
| Algorithms | EC ElGamal, Exponential ElGamal, Paillier, Damgard-Jurik | Paillier, Damgard-Jurik |
| Max votes per party | No hard limit. With Paillier and Damgard-Jurik, decryption cost doesn’t depend on the count. With ElGamal variants, decryption time grows with the count (a discrete logarithm search) | base – 1 |
| Max parties | No limit | base ^ parties < n (e.g. 51 parties at base 10^6 with 1024 bit key) |
| Ballot size | Grows with the number of parties (k ciphertexts and k+1 proofs) | One ciphertext, with a proof that grows with the number of parties |
| Tally decryptions | One per party | One in total |
To put the ElGamal caveat into numbers: in Python on my laptop, decrypting a party’s count of 100,000 votes takes about 2 seconds with Exponential ElGamal (threshold decryption included), and about a minute with EC ElGamal, because the search grows linearly with the count. That is fine for a city council election, but for a nationwide election with millions of votes per party, Paillier or Damgard-Jurik with one-hot ballots is the safer choice.
When to Choose Base Encoding:
- Ideal for elections with a small, fixed number of candidates and a known voter cap (e.g., board elections or local council voting).
- Minimizes network payload during ballot submission since the entire ballot fits into a single ciphertext.
- Drastically speeds up final tallying, requiring only one threshold decryption regardless of the candidate count.
When to Choose One-Hot Encoding:
- Essential for large-scale, nationwide, or open-ended elections where candidate counts or total voters could exceed packed integer capacity.
- Removes the overflow risk (base – 1) and the modulus capacity constraint (base^parties < n). With the ElGamal variants, keep the decryption time of large counts in mind.
- Allows full leverage of Exponential-ElGamal and EC-ElGamal cryptosystems alongside Paillier and Damgard-Jurik.
What This Design Does Not Cover
As in the referendum, cryptography covers the tally, not the whole election. Voter authentication is up to the bulletin board. The dealer knows the private key during setup, so it must be trusted, or replaced with a distributed key generation protocol. A voter can still reveal the randomness of their ballot to prove how they voted, so coercion and vote selling need additional techniques. And the proofs show that a ballot is valid, not that it is the choice the voter intended, so a compromised voter device remains a risk.
Conclusion
Moving from a Yes/No referendum to a multi-candidate election doesn’t need new cryptography. It needs a smarter way to encode the ballot. Base encoding packs every candidate’s count into one ciphertext, so each ballot is compact and the whole tally is decrypted once. In exchange, you’re tied to Paillier or Damgard-Jurik and to two ceilings: votes per candidate must stay below the base, and base^candidates must fit within the key’s plaintext space. One-hot puts each candidate in its own slot. That removes both ceilings and opens the door to Exponential ElGamal and EC ElGamal, at the cost of ballots and proofs that grow with every candidate, one decryption per candidate, and—with the ElGamal variants—decryption time that grows with each candidate’s count.
Whichever you choose, the guarantees stay the same: ballots are tallied without being decrypted, zero-knowledge proofs reject malformed, copied or tampered ballots, and threshold decryption with proofs keeps any single trustee from reading votes or forging the result. As a rule of thumb, base encoding suits elections with a few candidates and a modest number of voters per candidate, while one-hot scales to long ballots and gives you the widest choice of cryptosystems. With LightPHE, either one is only a few lines of code.
Support this blog financially if you do like!
