Skip to content

Instantly share code, notes, and snippets.

@bquast
Last active Aug 16, 2019
Embed
What would you like to do?
Paillier Cryptosystem for E-voting (using RSA) in R
# Paillier cryptosystem in R
# Bastiaan Quast
# install and load the GNU Multiple Percision Arithmetic R package
install.packages('gmp')
library(gmp)
# define parameters
# p and q are private to the Inspector
Inspector = list()
Inspector$p = 3
Inspector$q = 11
n = Inspector$p * Inspector$q
n2 = n^2
# find the Lowest Common Multiple (LCM) of p-1 and q-1
Inspector$p-1
Inspector$q-1
# the LCM of 3 and 11 is 10
Inspector$lambda = 10
# randomly chose g
g = 911
# Create 6 votes
V1 = list()
V2 = list()
V3 = list()
# V4 = list()
# V5 = list()
# V6 = list()
# There are three candidates, Alice, Bob, and Charlie
# each is assigned a binary identifier
# Alice = 010000
Bob = 0001 # 000100
Charlie = 0100 # 000001
# in decimal format we get
# Alice = 16
# strtoi(Alice, base = 2)
# Bob = 4
strtoi(Bob, base = 2)
# Charlie = 1
strtoi(Charlie, base = 2)
# define the Encoding function
# g and r are wrapped with as.bigz() to deal with the large values of the integers
Enc = function(x, r)
(as.bigz(g)^x * as.bigz(r)^n) %% n2
# voter decide their votes
# 16 for Alice
# 4 for Bob
# 1 for Charlie
V1$x = 4
V2$x = 1
V3$x = 4
# V4$x = 1
# V5$x = 16
# V6$x = 1
# Voters randomly decide their r
V1$r = 2
V2$r = 4
V3$r = 7
# V4$r = 12
# V5$r = 11
# V6$r = 32
# Voters now encode their votes
# r is wrapped with as.bigz to deal with the large values of the integers
V1$enc1 = Enc(V1$x, V1$r)
V2$enc2 = Enc(V2$x, V2$r)
V3$enc3 = Enc(V3$x, V3$r)
# V4$enc4 = Enc(V4$x, V4$r)
# V5$enc5 = Enc(V5$x, V5$r)
# V6$enc6 = Enc(V6$x, V6$r)
# Voters make their encrypted votes public
enc1 = V1$enc1
enc2 = V2$enc2
enc3 = V3$enc3
# enc4 = V4$enc4
# enc5 = V5$enc5
# enc6 = V6$enc6
# multiply all the votes
votes = enc1 * enc2 * enc3 # * enc4 * enc5 * enc6
votes
n2
# take modulo
votes %% n2
# define L(u)
L = function(u)
(u-1) / n
Ly = L( (votes^Inspector$lambda) %% n2)
# Lg = L( (as.bigz(g)^Inspector$lambda) %% n2 )
#
# as.double(Ly / Lg) %% n
# Ly of 21 gives m = 9
# which in binary form is
# 1001
# which means 10 for Bob, or 2 in decimal
# and 01 for Charlie, or 1 in decimal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment