dhe.go 1.68 KB
Newer Older
Thomas Hoffmann's avatar
Thomas Hoffmann committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package homomorphic

import (
	"math/big"
	"crypto/rand"
	mRand "math/rand"
	
)

type Protocol struct {
	d, n int
	pubKey []*big.Int
}

func NewProtocol(d, n int) (sKey *big.Int, pr Protocol, err error) {
	s_int, b_int := big.NewInt(27), big.NewInt(27)
Thomas Hoffmann's avatar
Thomas Hoffmann committed
17
18
	sBytes := make([]byte, 250)
	_, err = rand.Read(sBytes)
Thomas Hoffmann's avatar
Thomas Hoffmann committed
19
	if err != nil {return}
Thomas Hoffmann's avatar
Thomas Hoffmann committed
20
	sBytes[len(sBytes)]
Thomas Hoffmann's avatar
Thomas Hoffmann committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
	sKey = sKey.SetBit(sKey, 0, 1)

	q := make([]*big.Int, n)
	r := make([]*big.Int, n)
	y := make([]*big.Int, n)

	for i := range q {
		q[i], err = rand.Int(rand.Reader, b_int)
		if err != nil {return}
		r[i], err = rand.Int(rand.Reader, s_int)
		if err != nil {return}
		right := big.NewInt(2)
		right.Mul(right,r[i])
		left := right.Mul(sKey,q[i])
		y[i] = right.Add(left, right)
	}
	pr = Protocol{
		n : n,
		d : d,
		pubKey : y,
	}
	return sKey, pr, err
}

func (p *Protocol) Encode(m int) (c *big.Int) {
	SLen := 4 //TODO: Define actual value
	S := make([]int, p.n)
	for i := 0; i < p.n; i++ {
		S[i] = i
	}
	mRand.Shuffle(p.n, func(i,j int) {S[i],S[j] = S[j], S[i]})
	S = S[:SLen]
	c = big.NewInt(int64(m))
	for i := range S {
		c = c.Add(c, p.pubKey[S[i]])
	}
	return
}

Thomas Hoffmann's avatar
Thomas Hoffmann committed
60
61
func (p *Protocol) Decode(c, sKey big.Int) int {
	tmp:= c.Mod(&c, &sKey)
Thomas Hoffmann's avatar
Thomas Hoffmann committed
62
63
64
65
66
	m := tmp.Mod(tmp, big.NewInt(2))
	return int(m.Int64())
}

// Assumes x inputs are negated, so Eval can compute ¬(¬a+b) = a+¬b 
Thomas Hoffmann's avatar
Thomas Hoffmann committed
67
func (p *Protocol) Eval(x,y []*big.Int) *big.Int {
Thomas Hoffmann's avatar
Thomas Hoffmann committed
68
69
70
	one := p.Encode(1)
	tmp := make([]*big.Int,3)
	for i := 0; i < 3; i++ {
Thomas Hoffmann's avatar
Thomas Hoffmann committed
71
72
73
74
75
76
		xi := x[i]
		yi := y[i]
		var val big.Int
		val.Mul(xi,yi)
		val.Add(&val,one)
		tmp[i] = &val
Thomas Hoffmann's avatar
Thomas Hoffmann committed
77
	}
Thomas Hoffmann's avatar
Thomas Hoffmann committed
78
	var res big.Int
Thomas Hoffmann's avatar
Thomas Hoffmann committed
79
	res.Mul(tmp[0],tmp[1])
Thomas Hoffmann's avatar
Thomas Hoffmann committed
80
81
	res.Mul(&res,tmp[2])
	return &res
Thomas Hoffmann's avatar
Thomas Hoffmann committed
82
}