Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Embedding G1 for the bn256 package #475

Merged
merged 1 commit into from
Oct 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions examples/bn256_enc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package examples

import (
"fmt"

"go.dedis.ch/kyber/v3"
"go.dedis.ch/kyber/v3/pairing"
"go.dedis.ch/kyber/v3/util/random"
)

func ElGamalEncryptBn256(suite pairing.Suite, pubkey kyber.Point, message []byte) (
K, C kyber.Point, remainder []byte) {

// Embed the message (or as much of it as will fit) into a curve point.
M := suite.G1().Point().Embed(message, random.New())
max := suite.G1().Point().EmbedLen()
if max > len(message) {
max = len(message)
}
remainder = message[max:]
// ElGamal-encrypt the point to produce ciphertext (K,C).
k := suite.G1().Scalar().Pick(random.New()) // ephemeral private key
K = suite.G1().Point().Mul(k, nil) // ephemeral DH public key
S := suite.G1().Point().Mul(k, pubkey) // ephemeral DH shared secret
C = suite.G1().Point().Add(S, M) // message blinded with secret
return
}

func ElGamalDecryptBn256(suite pairing.Suite, prikey kyber.Scalar, K, C kyber.Point) (
message []byte, err error) {

// ElGamal-decrypt the ciphertext (K,C) to reproduce the message.
S := suite.G1().Point().Mul(prikey, K) // regenerate shared secret
M := suite.G1().Point().Sub(C, S) // use to un-blind the message
message, err = M.Data() // extract the embedded data
return
}

/*
This example illustrates how the crypto toolkit may be used
to perform "pure" ElGamal encryption,
in which the message to be encrypted is small enough to be embedded
directly within a group element (e.g., in an elliptic curve point).
For basic background on ElGamal encryption see for example
http://en.wikipedia.org/wiki/ElGamal_encryption.

Most public-key crypto libraries tend not to support embedding data in points,
in part because for "vanilla" public-key encryption you don't need it:
one would normally just generate an ephemeral Diffie-Hellman secret
and use that to seed a symmetric-key crypto algorithm such as AES,
which is much more efficient per bit and works for arbitrary-length messages.
However, in many advanced public-key crypto algorithms it is often useful
to be able to embedded data directly into points and compute with them:
as just one of many examples,
the proactively verifiable anonymous messaging scheme prototyped in Verdict
(see http://dedis.cs.yale.edu/dissent/papers/verdict-abs).

For fancier versions of ElGamal encryption implemented in this toolkit
see for example anon.Encrypt, which encrypts a message for
one of several possible receivers forming an explicit anonymity set.
*/
func Example_elGamalEncryption_bn256() {
suite := pairing.NewSuiteBn256()

// Create a public/private keypair
a := suite.G1().Scalar().Pick(suite.RandomStream()) // Alice's private key
A := suite.G1().Point().Mul(a, nil) // Alice's public key

// ElGamal-encrypt a message using the public key.
m := []byte("The quick brown fox")
K, C, _ := ElGamalEncryptBn256(suite, A, m)

// Decrypt it using the corresponding private key.
mm, err := ElGamalDecryptBn256(suite, a, K, C)

// Make sure it worked!
if err != nil {
fmt.Println("decryption failed: " + err.Error())
} else if string(mm) != string(m) {
fmt.Println("decryption produced wrong output: " + string(mm))
} else {
fmt.Println("Decryption succeeded: " + string(mm))
}
// Output:
// Decryption succeeded: The quick brown fox
}
28 changes: 28 additions & 0 deletions pairing/bn256/gfp.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package bn256

import (
"fmt"
"math/big"
)

type gfP [4]uint64
Expand All @@ -18,6 +19,23 @@ func newGFp(x int64) (out *gfP) {
return out
}

func newGFpFromBigInt(bigInt *big.Int) *gfP {
leftPad32 := func(in []byte) []byte {
if len(in) > 32 {
panic("input cannot be more than 32 bytes")
}

o := make([]byte, 32)
copy(o[32-len(in):], in)
return o
}

out := new(gfP)
out.Unmarshal(leftPad32(bigInt.Bytes()))
montEncode(out, out)
return out
}

func (e *gfP) String() string {
return fmt.Sprintf("%16.16x%16.16x%16.16x%16.16x", e[3], e[2], e[1], e[0])
}
Expand Down Expand Up @@ -66,5 +84,15 @@ func (e *gfP) Unmarshal(in []byte) {
}
}

func (e *gfP) BigInt() *big.Int {
bigInt := new(big.Int)
decoded := new(gfP)
montDecode(decoded, e)
buf := make([]byte, 32)
decoded.Marshal(buf)
bigInt.SetBytes(buf)
return bigInt
}

func montEncode(c, a *gfP) { gfpMul(c, a, r2) }
func montDecode(c, a *gfP) { gfpMul(c, a, &gfP{1}) }
83 changes: 58 additions & 25 deletions pairing/bn256/point.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,21 +62,58 @@ func (p *pointG1) Clone() kyber.Point {
}

func (p *pointG1) EmbedLen() int {
panic("bn256.G1: unsupported operation")
// 2^255 is ~size of the curve P
// minus one byte for randomness
// minus one byte for len(data)
return (255 - 8 - 8) / 8
}

func (p *pointG1) Embed(data []byte, rand cipher.Stream) kyber.Point {
// XXX: An approach to implement this is:
// - Encode data as the x-coordinate of a point on y²=x³+3 where len(data)
// is stored in the least significant byte of x and the rest is being
// filled with random values, i.e., x = rand || data || len(data).
// - Use the Tonelli-Shanks algorithm to compute the y-coordinate.
// - Convert the new point to Jacobian coordinates and set it as p.
panic("bn256.G1: unsupported operation")
// How many bytes to embed?
dl := p.EmbedLen()
if dl > len(data) {
dl = len(data)
}

for {
// Pick a random point, with optional embedded data
var b [32]byte
rand.XORKeyStream(b[:], b[:])
if data != nil {
b[0] = byte(dl) // Encode length in low 8 bits
copy(b[1:1+dl], data) // Copy in data to embed
}
x := new(big.Int).SetBytes(b[:])

y := deriveY(x)
if y != nil {
p.g.x = *newGFpFromBigInt(x)
p.g.y = *newGFpFromBigInt(y)
p.g.z = *newGFp(1)
if p.g.IsOnCurve() {
return p
}
}
}
}

func (p *pointG1) Data() ([]byte, error) {
panic("bn256.G1: unsupported operation")
var b [32]byte

pgtemp := *p.g
pgtemp.MakeAffine()
if pgtemp.IsInfinity() {
return b[:], nil
}
tmp := &gfP{}
montDecode(tmp, &pgtemp.x)
tmp.Marshal(b[:])

dl := int(b[0]) // extract length byte
if dl > p.EmbedLen() {
return nil, errors.New("invalid embedded data length")
}
return b[1 : 1+dl], nil
}

func (p *pointG1) Add(a, b kyber.Point) kyber.Point {
Expand Down Expand Up @@ -224,27 +261,12 @@ func (p *pointG1) Hash(m []byte) kyber.Point {
// hashes a byte slice into two points on a curve represented by big.Int
// ideally we want to do this using gfP, but gfP doesn't have a ModSqrt function
func hashToPoint(m []byte) (*big.Int, *big.Int) {
// we need to convert curveB into a bigInt for our computation
intCurveB := new(big.Int)
{
decodedCurveB := new(gfP)
montDecode(decodedCurveB, curveB)
bufCurveB := make([]byte, 32)
decodedCurveB.Marshal(bufCurveB)
intCurveB.SetBytes(bufCurveB)
}

h := sha256.Sum256(m)
x := new(big.Int).SetBytes(h[:])
x.Mod(x, p)

for {
xxx := new(big.Int).Mul(x, x)
xxx.Mul(xxx, x)
xxx.Mod(xxx, p)

t := new(big.Int).Add(xxx, intCurveB)
y := new(big.Int).ModSqrt(t, p)
y := deriveY(x)
if y != nil {
return x, y
}
Expand All @@ -253,6 +275,17 @@ func hashToPoint(m []byte) (*big.Int, *big.Int) {
}
}

func deriveY(x *big.Int) *big.Int {
intCurveB := curveB.BigInt()
xxx := new(big.Int).Mul(x, x)
xxx.Mul(xxx, x)
xxx.Mod(xxx, p)

t := new(big.Int).Add(xxx, intCurveB)
y := new(big.Int).ModSqrt(t, p)
return y
}

type pointG2 struct {
g *twistPoint
}
Expand Down
15 changes: 15 additions & 0 deletions pairing/bn256/point_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package bn256
import (
"bytes"
"encoding/hex"
"go.dedis.ch/kyber/v3/util/random"
"testing"
)

Expand Down Expand Up @@ -39,3 +40,17 @@ func TestPointG1_HashToPoint(t *testing.T) {
t.Error("hash does not match reference")
}
}

func TestPointG1_EmbedData(t *testing.T) {
m := []byte("The quick brown fox")
// Embed m onto prime group
M := newPointG1().Embed(m, random.New())

// Retrieve message encoded in x coordinate
mm, err := M.Data()
if err != nil {
t.Error(err)
} else if string(mm) != string(m) {
t.Error("G1: Embed/Data produced wrong output: ", string(mm), " expected ", string(m))
}
}