func Handle(buf []byte, addr *net.UDPAddr, tmpServer *AnonServer, n int) {
	// decode the whole message
	byteArr := make([]util.ByteArray, 2)
	gob.Register(byteArr)

	srcAddr = addr
	anonServer = tmpServer
	event := &proto.Event{}
	err := gob.NewDecoder(bytes.NewReader(buf[:n])).Decode(event)
	util.CheckErr(err)
	switch event.EventType {
	case proto.SERVER_REGISTER_REPLY:
		handleServerRegisterReply(event.Params)
		break
	case proto.ANNOUNCEMENT:
		handleAnnouncement(event.Params)
		break
	case proto.UPDATE_NEXT_HOP:
		handleUpdateNextHop(event.Params)
		break
	case proto.CLIENT_REGISTER_SERVERSIDE:
		handleClientRegisterServerSide(event.Params)
		break
	case proto.ROUND_END:
		handleRoundEnd(event.Params)
		break
	default:
		fmt.Println("Unrecognized request")
		break
	}
}
// encrypt the public key and send to next hop
func handleClientRegisterServerSide(params map[string]interface{}) {
	publicKey := anonServer.Suite.Point()
	err := publicKey.UnmarshalBinary(params["public_key"].([]byte))
	util.CheckErr(err)

	newKey := anonServer.Suite.Point().Mul(publicKey, anonServer.Roundkey)
	byteNewKey, err := newKey.MarshalBinary()
	util.CheckErr(err)
	pm := map[string]interface{}{
		"public_key": byteNewKey,
		"addr":       params["addr"].(string),
	}
	event := &proto.Event{proto.CLIENT_REGISTER_SERVERSIDE, pm}
	util.Send(anonServer.Socket, anonServer.NextHop, util.Encode(event))
	// add into key map
	fmt.Println("[debug] Receive client register request... ")
	anonServer.KeyMap[newKey.String()] = publicKey
}
/**
 * initialize anon server
 * set ip, port and encryption parameters
 */
func initAnonServer() {
	config = util.ReadConfig()
	// load controller ip and port
	ServerAddr, err := net.ResolveUDPAddr("udp", config["coordinator_ip"]+":"+config["coordinator_port"])
	util.CheckErr(err)
	// initialize suite
	suite := nist.NewAES128SHA256QR512()
	a := suite.Secret().Pick(random.Stream)
	A := suite.Point().Mul(nil, a)
	RoundKey := suite.Secret().Pick(random.Stream)
	anonServer = &server.AnonServer{ServerAddr, nil, suite, a, A, suite.Point(), nil,
		false, ServerAddr, ServerAddr, make(map[string]abstract.Point), nil, RoundKey}
}
func main() {
	// init anon server
	initAnonServer()
	fmt.Println("[debug] AnonServer started...")
	// check available port
	localPort, err := strconv.Atoi(config["local_port"])
	util.CheckErr(err)
	for i := localPort; i <= localPort+3; i++ {
		conn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4zero, Port: i})
		if err == nil {
			// set socket
			anonServer.Socket = conn
			break
		}
	}

	// start Listener
	go startAnonServerListener()
	// register itself to coordinator
	serverRegister()

	// wait until register successful
	for i := 0; i < 100; i++ {
		if anonServer.IsConnected {
			break
		}
		time.Sleep(500 * time.Millisecond)
	}

	if anonServer.IsConnected != true {
		log.Fatal("Fails to connect to coordinator")
		os.Exit(1)
	}
	fmt.Println("[debug] Register success...")
	for {
		time.Sleep(100000000 * time.Millisecond)
	}

	fmt.Println("[debug] Exit system...")

}
func handleRoundEnd(params map[string]interface{}) {
	keyList := util.ProtobufDecodePointList(params["keys"].([]byte))
	size := len(keyList)
	byteValList := make([][]byte, size)
	if _, ok := params["is_start"]; ok {
		intValList := params["vals"].([]int)
		// The request is sent by coordinator, deserialize the data part
		for i := 0; i < len(intValList); i++ {
			byteValList[i] = util.IntToByte(intValList[i])
		}
	} else {
		// verify neff shuffle if needed
		verifyNeffShuffle(params)
		// deserialize data part
		byteArr := params["vals"].([]util.ByteArray)
		for i := 0; i < len(byteArr); i++ {
			byteValList[i] = byteArr[i].Arr
		}
	}

	rand1 := anonServer.Suite.Cipher([]byte("example"))
	// Create a public/private keypair (X[mine],x)
	X := make([]abstract.Point, 1)
	X[0] = anonServer.PublicKey

	newKeys := make([]abstract.Point, size)
	newVals := make([][]byte, size)
	for i := 0; i < size; i++ {
		// decrypt the public key
		newKeys[i] = anonServer.KeyMap[keyList[i].String()]
		// encrypt the reputation using ElGamal algorithm
		C := anon.Encrypt(anonServer.Suite, rand1, byteValList[i], anon.Set(X), false)
		newVals[i] = C
	}
	byteNewKeys := util.ProtobufEncodePointList(newKeys)

	// type is []ByteArr
	byteNewVals := util.SerializeTwoDimensionArray(newVals)

	if size <= 1 {
		// no need to shuffle, just send the package to next server
		pm := map[string]interface{}{
			"keys": byteNewKeys,
			"vals": byteNewVals,
		}
		event := &proto.Event{proto.ROUND_END, pm}
		util.Send(anonServer.Socket, anonServer.PreviousHop, util.Encode(event))
		// reset RoundKey and key map
		anonServer.Roundkey = anonServer.Suite.Secret().Pick(random.Stream)
		anonServer.KeyMap = make(map[string]abstract.Point)
		return
	}

	Xori := make([]abstract.Point, len(newVals))
	for i := 0; i < size; i++ {
		Xori[i] = anonServer.Suite.Point().Mul(nil, anonServer.PrivateKey)
	}
	byteOri := util.ProtobufEncodePointList(Xori)

	rand := anonServer.Suite.Cipher(abstract.RandomKey)
	// *** perform neff shuffle here ***
	Xbar, Ybar, _, Ytmp, prover := neffShuffle(Xori, newKeys, rand)
	prf, err := proof.HashProve(anonServer.Suite, "PairShuffle", rand, prover)
	util.CheckErr(err)

	// this is the shuffled key
	finalKeys := convertToOrigin(Ybar, Ytmp)
	finalVals := rebindReputation(newKeys, newVals, finalKeys)

	// send data to the next server
	byteXbar := util.ProtobufEncodePointList(Xbar)
	byteYbar := util.ProtobufEncodePointList(Ybar)
	byteFinalKeys := util.ProtobufEncodePointList(finalKeys)
	byteFinalVals := util.SerializeTwoDimensionArray(finalVals)
	bytePublicKey, _ := anonServer.PublicKey.MarshalBinary()
	// prev keys means the key before shuffle
	pm := map[string]interface{}{
		"xbar":       byteXbar,
		"ybar":       byteYbar,
		"keys":       byteFinalKeys,
		"vals":       byteFinalVals,
		"proof":      prf,
		"prev_keys":  byteOri,
		"prev_vals":  byteNewKeys,
		"shuffled":   true,
		"public_key": bytePublicKey,
	}
	event := &proto.Event{proto.ROUND_END, pm}
	util.Send(anonServer.Socket, anonServer.PreviousHop, util.Encode(event))

	// reset RoundKey and key map
	anonServer.Roundkey = anonServer.Suite.Secret().Pick(random.Stream)
	anonServer.KeyMap = make(map[string]abstract.Point)
}
func handleAnnouncement(params map[string]interface{}) {
	var g abstract.Point = nil
	keyList := util.ProtobufDecodePointList(params["keys"].([]byte))
	valList := params["vals"].([]util.ByteArray)
	size := len(keyList)

	if val, ok := params["g"]; ok {
		// contains g
		byteG := val.([]byte)
		g = anonServer.Suite.Point()
		g.UnmarshalBinary(byteG)
		g = anonServer.Suite.Point().Mul(g, anonServer.Roundkey)
		// verify the previous shuffle
		verifyNeffShuffle(params)
	} else {
		g = anonServer.Suite.Point().Mul(nil, anonServer.Roundkey)
	}

	X1 := make([]abstract.Point, 1)
	X1[0] = anonServer.PublicKey

	newKeys := make([]abstract.Point, size)
	newVals := make([][]byte, size)
	for i := 0; i < len(keyList); i++ {
		// encrypt the public key using modPow
		newKeys[i] = anonServer.Suite.Point().Mul(keyList[i], anonServer.Roundkey)
		// decrypt the reputation using ElGamal algorithm
		MM, err := anon.Decrypt(anonServer.Suite, valList[i].Arr, anon.Set(X1), 0, anonServer.PrivateKey, false)
		util.CheckErr(err)
		newVals[i] = MM
		// update key map
		anonServer.KeyMap[newKeys[i].String()] = keyList[i]
	}
	byteNewKeys := util.ProtobufEncodePointList(newKeys)
	byteNewVals := util.SerializeTwoDimensionArray(newVals)
	byteG, err := g.MarshalBinary()
	util.CheckErr(err)

	if size <= 1 {
		// no need to shuffle, just send the package to next server
		pm := map[string]interface{}{
			"keys": byteNewKeys,
			"vals": byteNewVals,
			"g":    byteG,
		}
		event := &proto.Event{proto.ANNOUNCEMENT, pm}
		util.Send(anonServer.Socket, anonServer.NextHop, util.Encode(event))
		return
	}

	Xori := make([]abstract.Point, len(newVals))
	for i := 0; i < size; i++ {
		Xori[i] = anonServer.Suite.Point().Mul(nil, anonServer.PrivateKey)
	}
	byteOri := util.ProtobufEncodePointList(Xori)

	rand := anonServer.Suite.Cipher(abstract.RandomKey)
	// *** perform neff shuffle here ***
	Xbar, Ybar, _, Ytmp, prover := neffShuffle(Xori, newKeys, rand)
	prf, err := proof.HashProve(anonServer.Suite, "PairShuffle", rand, prover)
	util.CheckErr(err)

	// this is the shuffled key
	finalKeys := convertToOrigin(Ybar, Ytmp)
	finalVals := rebindReputation(newKeys, newVals, finalKeys)

	// send data to the next server
	byteXbar := util.ProtobufEncodePointList(Xbar)
	byteYbar := util.ProtobufEncodePointList(Ybar)
	byteFinalKeys := util.ProtobufEncodePointList(finalKeys)
	byteFinalVals := util.SerializeTwoDimensionArray(finalVals)
	bytePublicKey, _ := anonServer.PublicKey.MarshalBinary()
	// prev keys means the key before shuffle
	pm := map[string]interface{}{
		"xbar":       byteXbar,
		"ybar":       byteYbar,
		"keys":       byteFinalKeys,
		"vals":       byteFinalVals,
		"proof":      prf,
		"prev_keys":  byteOri,
		"prev_vals":  byteNewKeys,
		"shuffled":   true,
		"public_key": bytePublicKey,
		"g":          byteG,
	}
	event := &proto.Event{proto.ANNOUNCEMENT, pm}
	util.Send(anonServer.Socket, anonServer.NextHop, util.Encode(event))
}
func handleUpdateNextHop(params map[string]interface{}) {
	addr, err := net.ResolveUDPAddr("udp", params["next_hop"].(string))
	util.CheckErr(err)
	anonServer.NextHop = addr
}
Exemple #8
0
func main() {
	/*
		suite1 := nist.NewAES128SHA256QR512()
		l := make([]abstract.Point,1)
		key := suite1.Secret().Pick(random.Stream)
		l[0] = suite1.Point().Mul(nil,key)
		m := make(map[string]int)
		m[l[0].String()] = 2
		bytes := util.ProtobufEncodePointList(l)
		keyList := util.ProtobufDecodePointList(bytes)

		fmt.Println(m[l[0].String()])
		fmt.Println(m[keyList[0].String()])
		fmt.Println(l[0].String())
		fmt.Println(keyList[0].String())
	*/
	/*
		suite1 := nist.NewAES128SHA256QR512()
		key := suite1.Secret().Pick(random.Stream)
		publicKey := suite1.Point().Mul(nil,key)
		var a int = 1
		aBytes := util.IntToByte(a)
		_,_,data := util.ElGamalEncrypt(suite1,publicKey,aBytes)
		fmt.Println(data)
		_,_,qdata := util.ElGamalEncrypt(suite1,publicKey,data)
		fmt.Println(qdata)
	*/
	var a int = 1
	aBytes := util.IntToByte(a)
	arr := make([]Message, 2)
	gob.Register(arr)
	arr[0].Nym = aBytes
	arr[1].Nym = aBytes
	pm := map[string]interface{}{
		"keys": arr,
	}
	event := &proto.Event{proto.ROUND_END, pm}
	data := util.Encode(event)
	newEvent := &proto.Event{}
	err := gob.NewDecoder(bytes.NewReader(data)).Decode(newEvent)
	util.CheckErr(err)
	fmt.Println((newEvent.Params["keys"].([]Message))[0])

	/*
		suite := nist.NewAES128SHA256QR512()
		key := suite.Secret().Pick(random.Stream)
		publicKey := suite.Point().Mul(nil,key)
		var a int = 0
		s := make([]abstract.Point,2)
		s[0] = nist.NewResidueGroup().NewPoint(int64(a))
		fmt.Println(s[0].String())

		K,C,_ := util.ElGamalEncrypt(suite,publicKey,s[0])
		K1,C1,_ := util.ElGamalEncrypt(suite,publicKey,C)
		P1 := util.ElGamalDecrypt(suite, key, K1, C1)
		P := util.ElGamalDecrypt(suite, key, K, P1)
		//_,_,qdata := util.ElGamalEncrypt(suite,publicKey,data)
		fmt.Println(P)
	*/
	/*
			suite := nist.NewAES128SHA256QR512()
			rand := suite.Cipher([]byte("example"))

			// Create a public/private keypair (X[mine],x)
			X := make([]abstract.Point, 1)
			mine := 0                           // which public key is mine
			x := suite.Secret().Pick(rand)      // create a private key x
			X[mine] = suite.Point().Mul(nil, x) // corresponding public key X

			// Encrypt a message with the public key
			var a int = 3
			M := util.IntToByte(a)
			C := anon.Encrypt(suite, rand, M, anon.Set(X), false)
			//fmt.Printf("Encryption of '%s':\n%s", string(M), hex.Dump(C))
			//fmt.Println(string(C))

			// another
			rand = suite.Cipher([]byte("example"))
			X1 := make([]abstract.Point, 1)
			x1 := suite.Secret().Pick(rand)      // create a private key x
			X1[0] = suite.Point().Mul(nil, x1) // corresponding public key X
			C1 := anon.Encrypt(suite, rand, C, anon.Set(X1), false)

			p,pdw := suite.Point().Pick(C1,random.)
			suite.Point().
			fmt.Println(C1)
			pd, _ := p.Data()
			fmt.Println(pd)
			fmt.Println(pdw)
		suite.
			// Decrypt the ciphertext with the private key
			MM, err := anon.Decrypt(suite,pd , anon.Set(X1), 0, x1, false)
			if err != nil {
				panic(err.Error())
			}
			MF, err1 := anon.Decrypt(suite, MM, anon.Set(X), 0, x, false)
			if err1 != nil {
				panic(err.Error())
			}

			fmt.Println(util.ByteToInt(MF))
	*/

	/*
		suite1 := nist.NewAES128SHA256QR512()
		suite2 := nist.NewAES128SHA256QR512()
		suite3 := nist.NewAES128SHA256QR512()
		key := suite1.Secret().Pick(random.Stream)
		g1 := suite1.Point().Mul(nil,key)
		byte1, _ := g1.MarshalBinary()
		fmt.Println(g1)

		g2 := suite2.Point()
		err := g2.UnmarshalBinary(byte1)
		g2 = suite2.Point().Mul(g2,key)
		bytes2, _ := g2.MarshalBinary()
		fmt.Println(g2)

		g3 := suite3.Point()
		err = g3.UnmarshalBinary(bytes2)
		util.CheckErr(err)
		g3 = suite3.Point().Mul(g3,key)

		fmt.Println(g3)
	*/

	/*
		var aSecret abstract.Secret
		var tSecret = reflect.TypeOf(&aSecret).Elem()

		suite := nist.NewAES128SHA256QR512()
		cons := protobuf.Constructors {
			tSecret: func()interface{} { return suite.Secret() },
		}

		a := suite.Secret().Pick(random.Stream)
		b := suite.Secret().Pick(random.Stream)
		fmt.Println(a)
		fmt.Println(b)

		byteA, _ := a.MarshalBinary()
		byteB, _ := b.MarshalBinary()
		l := map[string][]byte {
			"a":byteA,
			"b":byteB,
		}

		byteNym, err := protobuf.Encode(&Message{l})
		if err != nil {
			fmt.Println(err.Error())
		}

		var msg Message
		if err = protobuf.DecodeWithConstructors(byteNym, &msg, cons); err != nil {
			fmt.Println(err.Error())
		}
		fmt.Println(msg.Nym["a"])
		fmt.Println(msg.Nym["b"])
	*/
}