Let to pass an arbitrary number of cyphers to PublicKey.Add #5

Merged
pdyraga merged 5 commits from master into master 2018-07-03 18:53:09 -04:00
2 changed files with 27 additions and 13 deletions
Showing only changes of commit 053ae45b59 - Show all commits

No files matched your search

+15 -5
View File
@@ -40,14 +40,24 @@ func (pub *PublicKey) Encrypt(m *big.Int, random io.Reader) (*Cypher, error) {
return &Cypher{new(big.Int).Mod(new(big.Int).Mul(rn, gm), nSquare)}, nil return &Cypher{new(big.Int).Mod(new(big.Int).Mul(rn, gm), nSquare)}, nil
} }
// Takes two cypher texts and returns a 3rd one that encode // Add takes an arbitrary number of cyphertexts and returns one that encodes
// the sum of the two plain texts. // their sum.
// //
// It's possible because Paillier is a homomorphic encryption scheme, where // It's possible because Paillier is a homomorphic encryption scheme, where
// E(m1) * E(m2) = E(m1 + m2) // E(m1) * E(m2) = E(m1 + m2)
func (this *PublicKey) Add(cypher1, cypher2 *Cypher) *Cypher { func (pub *PublicKey) Add(cypher ...*Cypher) *Cypher {
m := new(big.Int).Mul(cypher1.C, cypher2.C) accumulator := big.NewInt(1)
return &Cypher{new(big.Int).Mod(m, this.GetNSquare())}
for _, c := range cypher {
accumulator = new(big.Int).Mod(
new(big.Int).Mul(accumulator, c.C),
pub.GetNSquare(),
)
}
return &Cypher{
C: accumulator,
}
} }
type PrivateKey struct { type PrivateKey struct {
+12 -8
View File
@@ -64,13 +64,17 @@ func TestEncryptDecryptSmall(t *testing.T) {
} }
} }
func TestAddCypher(t *testing.T) { func TestAddCyphers(t *testing.T) {
privateKey := CreatePrivateKey(big.NewInt(13), big.NewInt(11)) privateKey := CreatePrivateKey(big.NewInt(17), big.NewInt(13))
cypher1, _ := privateKey.Encrypt(big.NewInt(12), rand.Reader)
cypher2, _ := privateKey.Encrypt(big.NewInt(13), rand.Reader) cypher1, _ := privateKey.Encrypt(big.NewInt(5), rand.Reader)
cypher3 := privateKey.Add(cypher1, cypher2) cypher2, _ := privateKey.Encrypt(big.NewInt(6), rand.Reader)
m := privateKey.Decrypt(cypher3) cypher3, _ := privateKey.Encrypt(big.NewInt(7), rand.Reader)
if !reflect.DeepEqual(m, big.NewInt(25)) { cypher4, _ := privateKey.Encrypt(big.NewInt(8), rand.Reader)
t.Error(m) cypher5 := privateKey.Add(cypher1, cypher2, cypher3, cypher4)
m := privateKey.Decrypt(cypher5)
if !reflect.DeepEqual(m, big.NewInt(26)) {
t.Errorf("Unexpected decrypted value [%v]", m)
} }
} }