## viff

### changeset 836:0422fa73ab29

Paillier crypto system. An implementation of the homomorphic public key crypto system by Paillier. Added by Martin, but written by Mikkel.
author Mikkel Krøigård Wed, 16 Jul 2008 00:09:50 +0200 15bc520032e4 99dc1bb4cddf viff/paillier.py 1 files changed, 53 insertions(+), 0 deletions(-) [+]
line diff
```     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/viff/paillier.py	Wed Jul 16 00:09:50 2008 +0200
1.3 @@ -0,0 +1,53 @@
1.4 +# Copyright 2008 VIFF Development Team.
1.5 +#
1.6 +# This file is part of VIFF, the Virtual Ideal Functionality Framework.
1.7 +#
1.8 +# VIFF is free software: you can redistribute it and/or modify it
1.9 +# under the terms of the GNU Lesser General Public License (LGPL) as
1.10 +# published by the Free Software Foundation, either version 3 of the
1.12 +#
1.13 +# VIFF is distributed in the hope that it will be useful, but WITHOUT
1.14 +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
1.15 +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
1.16 +# Public License for more details.
1.17 +#
1.18 +# You should have received a copy of the GNU Lesser General Public
1.20 +
1.21 +import gmpy
1.22 +
1.23 +from viff.util import rand, find_random_prime
1.24 +
1.25 +def L(u, n):
1.26 +    return (u-1)/n
1.27 +
1.28 +def generate_keys(bit_length):
1.29 +    # Make an RSA modulus n.
1.30 +    p = find_random_prime(bit_length/2)
1.31 +    while True:
1.32 +        q = find_random_prime(bit_length/2)
1.33 +        if p<>q: break
1.34 +
1.35 +    n = p*q
1.36 +    nsq = n*n
1.37 +
1.38 +    # Calculate Carmichael's function.
1.39 +    lm = gmpy.lcm(p-1, q-1)
1.40 +
1.41 +    # Generate a generator g in B.
1.42 +    while True:
1.43 +        g = rand.randint(1, long(nsq))
1.44 +        if gmpy.gcd(L(pow(g, lm, nsq), n), n) == 1: break
1.45 +
1.46 +    return (n, g), (n, g, lm)
1.47 +
1.48 +def encrypt(m, (n, g)):
1.49 +    r = rand.randint(1, long(n))
1.50 +    nsq = n*n
1.51 +    return (pow(g, m, nsq)*pow(r, n, nsq)) % nsq
1.52 +
1.53 +def decrypt(c, (n, g, lm)):
1.54 +    numer = L(pow(c, lm, n*n), n)
1.55 +    denom = L(pow(g, lm, n*n), n)
1.56 +    return (numer*gmpy.invert(denom, n)) % n
```