// Checks the signature against
// the message
func SchnorrVerify(suite abstract.Suite,
	kp SchnorrPublicKey,
	msg []byte, sig []byte) (bool, error) {

	buf := bytes.NewBuffer(sig)
	signature := SchnorrSignature{}
	err := abstract.Read(buf, &signature, suite)
	if err != nil {
		return false, err
	}

	s := signature.S
	e := signature.E

	var gs, ye, r abstract.Point
	gs = suite.Point().Mul(nil, s)  // g^s
	ye = suite.Point().Mul(kp.Y, e) // y^e
	r = suite.Point().Add(gs, ye)   // g^xy^e

	r_bin, _ := r.MarshalBinary()
	msg_and_r := append(msg, r_bin...)
	hasher := sha3.New256()
	hasher.Write(msg_and_r)
	h := hasher.Sum(nil)

	// again I'm hoping this just reads the state out
	// and doesn't  actually perform any ops
	lct := suite.Cipher(h)

	ev := suite.Secret().Pick(lct)
	return ev.Equal(e), nil
}
Example #2
0
// ShuffleDecrypt performs a shuffle and partial decyption of the given ciphertexts, producing correctness
// proofs in the process
func ShuffleDecrypt(suite abstract.Suite, ciphertexts []*elgamal.CipherText,
	pks []*elgamal.PubKey, sk *elgamal.PriKey, nonce string, position int) (*VerifiableShuffle, error) {
	amount := len(ciphertexts)
	if amount == 0 {
		panic("Can't shuffle 0 ciphertexts")
	}

	c1, c2 := elgamal.Unpack(ciphertexts)

	// The ciphertexts are encrypted against these public keys; it still includes ours
	// The proof of the shuffle will also be w.r.t. this public key
	sumpk := elgamal.SumKeys(pks[position:])

	// Do the shuffle, create a proof of its correctness
	shuffledC1, shuffledC2, prover := shuffle.Shuffle(suite, sumpk.Base, sumpk.Key, c1, c2, suite.Cipher(nil))
	shuffleProof, err := proof.HashProve(suite, "ElGamalShuffle"+nonce, suite.Cipher(nil), prover)
	if err != nil {
		return nil, err
	}
	shuffled := elgamal.Pack(shuffledC1, shuffledC2)

	// Do the partial decryption, create a proof of its correctness
	decryptionProofs, decrypted := make([][]byte, amount), make([]*elgamal.CipherText, amount)
	for i := range shuffledC1 {
		decrypted[i], decryptionProofs[i], err = sk.PartialProofDecrypt(shuffled[i], nonce)
		if err != nil {
			return nil, err
		}
	}

	return &VerifiableShuffle{shuffled, decrypted, decryptionProofs, shuffleProof}, nil
}
/* GenerateZ takes some random agreed information and creates
   Z the "public-only" key that is witness-independent as per
   the paper. We've probably broken that slightly in this implementation
   because I could not pick a point without generating it
   via a Secret, instead of directly via a Point - that is, even as a
   32-byte string, we cannot decode on C25519 (and this wouldn't work
   for abstract suites anyway).

   However, it demonstrates the idea.
*/
func GenerateZ(suite abstract.Suite, info []byte) (abstract.Point, error) {

	hasher := sha3.New256()
	hasher.Write(info)
	zraw := hasher.Sum(nil)

	//I think this might be cheating
	zrawCt := suite.Cipher(zraw)

	zfactor := suite.Secret().Pick(zrawCt)
	Z := suite.Point()
	Z.Mul(nil, zfactor)

	// every 32-bit integer exists on Curve25519 only if we have the fullgroup
	// this should work, but doesn't.

	/*var Z abstract.Point
	  zrawBuf := bytes.NewBuffer(zraw)
	  err := abstract.Read(zrawBuf, &Z, suite);
	  if err != nil {
	      return nil, err
	  }*/

	return Z, nil
}
Example #4
0
func NewShuffler(suite abstract.Suite, id, k, N int) *shuffler {
	rand := suite.Cipher([]byte(fmt.Sprintf("key%d", id)))

	// This server's own keypair.
	h := suite.Secret().Pick(rand)
	H := suite.Point().Mul(nil, h)

	// The keypairs for the other servers.
	HH := make([]abstract.Point, N)
	for i := 0; i < N; i++ {
		r := suite.Cipher([]byte(fmt.Sprintf("key%d", i)))
		x := suite.Secret().Pick(r)
		HH[i] = suite.Point().Mul(nil, x)
	}

	// Constructors for use with protobuf.
	cons := func(t reflect.Type) interface{} {
		switch t {
		case tSecret:
			return suite.Secret()
		case tPoint:
			return suite.Point()
		default:
			return nil
		}
	}

	s := &shuffler{suite, id, k, N, h, H, HH, cons, nil, nil, nil}
	return s
}
Example #5
0
// Determine all the alternative DH point positions for a ciphersuite.
func (si *suiteInfo) init(ste abstract.Suite, nlevels int) {
	si.ste = ste
	si.tag = make([]uint32, nlevels)
	si.pos = make([]int, nlevels)
	si.plen = ste.Point().(abstract.Hiding).HideLen() // XXX

	// Create a pseudo-random stream from which to pick positions
	str := fmt.Sprintf("NegoCipherSuite:%s", ste.String())
	rand := ste.Cipher([]byte(str))

	// Alternative 0 is always at position 0, so start with level 1.
	levofs := 0 // starting offset for current level
	//fmt.Printf("Suite %s positions:\n", ste.String())
	for i := 0; i < nlevels; i++ {

		// Pick a random position within this level
		var buf [4]byte
		rand.XORKeyStream(buf[:], buf[:])
		levlen := 1 << uint(i) // # alt positions at this level
		levmask := levlen - 1  // alternative index mask
		si.tag[i] = binary.BigEndian.Uint32(buf[:])
		levidx := int(si.tag[i]) & levmask
		si.pos[i] = levofs + levidx*si.plen

		//fmt.Printf("%d: idx %d/%d pos %d\n",
		//		i, levidx, levlen, si.pos[i])

		levofs += levlen * si.plen // next level table offset
	}

	// Limit of highest point field
	si.max = si.pos[nlevels-1] + si.plen
}
Example #6
0
func benchSign(suite abstract.Suite, pub []abstract.Point, pri abstract.Secret,
	niter int) {
	rand := suite.Cipher([]byte("example"))
	for i := 0; i < niter; i++ {
		Sign(suite, rand, benchMessage, Set(pub), nil, 0, pri)
	}
}
Example #7
0
File: enc.go Project: Liamsi/crypto
// Decrypt a message encrypted for a particular anonymity set.
// Returns the cleartext message on success, or an error on failure.
//
// The caller provides the anonymity set for which the message is intended,
// and the private key corresponding to one of the public keys in the set.
// Decrypt verifies that the message is encrypted correctly for this set -
// in particular, that it could be decrypted by ALL of the listed members -
// before returning successfully with the decrypted message.
// This verification ensures that a malicious sender
// cannot de-anonymize a receiver by constructing a ciphertext incorrectly
// so as to be decryptable by only some members of the set.
// As a side-effect, this verification also ensures plaintext-awareness:
// that is, it is infeasible for a sender to construct any ciphertext
// that will be accepted by the receiver without knowing the plaintext.
//
func Decrypt(suite abstract.Suite, ciphertext []byte, anonymitySet Set,
	mine int, privateKey abstract.Secret, hide bool) ([]byte, error) {

	// Decrypt and check the encrypted key-header.
	xb, hdrlen, err := decryptKey(suite, ciphertext, anonymitySet,
		mine, privateKey, hide)
	if err != nil {
		return nil, err
	}

	// Determine the message layout
	cipher := suite.Cipher(xb)
	maclen := cipher.KeySize()
	if len(ciphertext) < hdrlen+maclen {
		return nil, errors.New("ciphertext too short")
	}
	hdrhi := hdrlen
	msghi := len(ciphertext) - maclen

	// Decrypt the message and check the MAC
	ctx := ciphertext[hdrhi:msghi]
	mac := ciphertext[msghi:]
	msg := make([]byte, len(ctx))
	cipher.Message(msg, ctx, ctx)
	cipher.Partial(mac, mac, nil)
	if subtle.ConstantTimeAllEq(mac, 0) == 0 {
		return nil, errors.New("invalid ciphertext: failed MAC check")
	}
	return msg, nil
}
Example #8
0
func newHashProver(suite abstract.Suite, protoName string,
	rand abstract.Cipher) *hashProver {
	var sc hashProver
	sc.suite = suite
	sc.pubrand = suite.Cipher([]byte(protoName))
	sc.prirand = rand
	return &sc
}
Example #9
0
// Verify checks a signature generated by Sign.
//
// The caller provides the message, anonymity set, and linkage scope
// with which the signature was purportedly produced.
// If the signature is a valid linkable signature (linkScope != nil),
// this function returns a linkage tag that uniquely corresponds
// to the signer within the given linkScope.
// If the signature is a valid unlinkable signature (linkScope == nil),
// returns an empty but non-nil byte-slice instead of a linkage tag on success.
// Returns a nil linkage tag and an error if the signature is invalid.
func Verify(suite abstract.Suite, message []byte, anonymitySet Set,
	linkScope []byte, signatureBuffer []byte) ([]byte, error) {

	n := len(anonymitySet)              // anonymity set size
	L := []abstract.Point(anonymitySet) // public keys in ring

	// Decode the signature
	buf := bytes.NewBuffer(signatureBuffer)
	var linkBase, linkTag abstract.Point
	sig := lSig{}
	sig.S = make([]abstract.Scalar, n)
	if linkScope != nil { // linkable ring signature
		if err := suite.Read(buf, &sig); err != nil {
			return nil, err
		}
		linkStream := suite.Cipher(linkScope)
		linkBase, _ = suite.Point().Pick(nil, linkStream)
		linkTag = sig.Tag
	} else { // unlinkable ring signature
		if err := suite.Read(buf, &sig.C0); err != nil {
			return nil, err
		}
		if err := suite.Read(buf, &sig.S); err != nil {
			return nil, err
		}
	}

	// Pre-hash the ring-position-invariant parameters to H1.
	H1pre := signH1pre(suite, linkScope, linkTag, message)

	// Verify the signature
	var P, PG, PH abstract.Point
	P = suite.Point()
	PG = suite.Point()
	if linkScope != nil {
		PH = suite.Point()
	}
	s := sig.S
	ci := sig.C0
	for i := 0; i < n; i++ {
		PG.Add(PG.Mul(nil, s[i]), P.Mul(L[i], ci))
		if linkScope != nil {
			PH.Add(PH.Mul(linkBase, s[i]), P.Mul(linkTag, ci))
		}
		ci = signH1(suite, H1pre, PG, PH)
	}
	if !ci.Equal(sig.C0) {
		return nil, errors.New("invalid signature")
	}

	// Return the re-encoded linkage tag, for uniqueness checking
	if linkScope != nil {
		tag, _ := linkTag.MarshalBinary()
		return tag, nil
	} else {
		return []byte{}, nil
	}
}
Example #10
0
// GenerateKeyPair generates a new random private/public keypair in the specified group
func GenerateKeyPair(suite abstract.Suite) (*PriKey, *PubKey) {
	secret := suite.Secret().Pick(suite.Cipher(nil))
	base := suite.Point().Base()

	pk := PubKey{suite, base, suite.Point().Mul(base, secret)}
	sk := PriKey{pk, secret}

	return &sk, &pk
}
Example #11
0
func signH1pre(suite abstract.Suite, linkScope []byte, linkTag abstract.Point,
	message []byte) abstract.Cipher {
	H1pre := suite.Cipher(message) // m
	if linkScope != nil {
		H1pre.Write(linkScope) // L
		tag, _ := linkTag.MarshalBinary()
		H1pre.Write(tag) // ~y
	}
	return H1pre
}
/* This is the function that given the client's challenge and response from the server is able to
   compute the final blind signature. This is done on the user side (blindly to the signer). */
func ClientSignBlindly(suite abstract.Suite, clientParameters WISchnorrClientParamersList, responseMsg WISchnorrResponseMessage, pubKey SchnorrPublicKey, msg []byte) (WIBlindSignature, bool) {

	rho := suite.Secret()
	omega := suite.Secret()
	sigma := suite.Secret()
	delta := suite.Secret()

	rho.Add(responseMsg.R, clientParameters.T1)
	omega.Add(responseMsg.C, clientParameters.T2)
	sigma.Add(responseMsg.S, clientParameters.T3)
	delta.Add(responseMsg.D, clientParameters.T4)

	gp := suite.Point()
	gp.Mul(nil, rho)

	yw := suite.Point()
	yw.Mul(pubKey.Y, omega)
	gpyw := suite.Point()

	gpyw.Add(gp, yw)
	bGpyw, _ := gpyw.MarshalBinary()

	gs := suite.Point()
	gs.Mul(nil, sigma)
	zd := suite.Point()
	zd.Mul(clientParameters.Z, delta)
	gszd := suite.Point()
	gszd.Add(gs, zd)
	bGszd, _ := gszd.MarshalBinary()

	bZ, _ := clientParameters.Z.MarshalBinary()

	var combinedmsg []byte

	combinedmsg = append(combinedmsg, bGpyw...)
	combinedmsg = append(combinedmsg, bGszd...)
	combinedmsg = append(combinedmsg, bZ...)
	combinedmsg = append(combinedmsg, msg...)

	hasher := sha3.New256()
	hasher.Write(combinedmsg)
	bSig := hasher.Sum(nil)
	bSigCt := suite.Cipher(bSig)

	sig := suite.Secret().Pick(bSigCt)

	vsig := suite.Secret()
	vsig.Add(omega, delta)

	//fmt.Println(sig)
	//fmt.Println(vsig)

	return WIBlindSignature{rho, omega, sigma, delta}, sig.Equal(vsig)
}
Example #13
0
func newHashVerifier(suite abstract.Suite, protoName string,
	proof []byte) *hashVerifier {
	var c hashVerifier
	if _, err := c.proof.Write(proof); err != nil {
		panic("Buffer.Write failed")
	}
	c.suite = suite
	c.prbuf = c.proof.Bytes()
	c.pubrand = suite.Cipher([]byte(protoName))
	return &c
}
// (Server side) This function reads the collective challenge
// from the wire, generates and serializes a response
// to that as a raw "secret"
func SchnorrMUnmarshallCCComputeResponse(suite abstract.Suite,
	kv SchnorrKeyset,
	privatecommit SchnorrMPrivateCommitment,
	cc []byte) SchnorrMResponse {
	hct := suite.Cipher(cc)
	c := suite.Secret().Pick(hct)
	r := suite.Secret()
	r.Mul(c, kv.X).Sub(privatecommit.V, r)

	return SchnorrMResponse{r}
}
Example #15
0
func hash(suite abstract.Suite, r abstract.Point, msg []byte) (abstract.Scalar, error) {
	rBuf, err := r.MarshalBinary()
	if err != nil {
		return nil, err
	}
	cipher := suite.Cipher(rBuf)
	cipher.Message(nil, nil, msg)
	// (re)compute challenge (e)
	e := suite.Scalar().Pick(cipher)

	return e, nil
}
Example #16
0
func (v *stateVector) addShuffle(suite abstract.Suite, shuf *shuffler,
	rand abstract.Cipher) error {

	// Get the previous shuffle state.
	i := len(v.States)
	prev := v.States[i-1]
	X, Y := prev.X, prev.Dec

	// Compute the new base using the public keys of the remaining
	// servers.
	H := suite.Point().Null()
	for j := i - 1; j < shuf.N; j++ {
		H = suite.Point().Add(H, shuf.HH[j])
	}

	// Do a key-shuffle.
	Xbar, Ybar, prover := shuffle.Shuffle(suite, nil, H, X, Y, rand)
	prf, err := proof.HashProve(suite, "PairShuffle", rand, prover)
	if err != nil {
		return err
	}

	// Seeded random for the decryption proof.
	seed := abstract.Sum(suite, prf)
	prfRand := suite.Cipher(seed)

	// Scratch space for calculations.
	zs := suite.Secret()
	zp := suite.Point()

	// Peel off a layer of encryption.
	dec := make([]abstract.Point, len(Xbar))
	decPrf := make([]*decryptionProof, len(Xbar))
	for j := range Xbar {
		// Decryption.
		zp.Mul(Xbar[j], shuf.h)
		dec[j] = suite.Point().Sub(Ybar[j], zp)

		// Decryption proof.
		t := suite.Secret().Pick(rand)
		T := suite.Point().Mul(Xbar[j], t)
		c := suite.Secret().Pick(prfRand)
		s := suite.Secret().Add(t, zs.Mul(c, shuf.h))
		decPrf[j] = &decryptionProof{T, s}
	}

	// Append the new state to the state vector.
	state := &shuffleState{H, Xbar, Ybar, dec, prf, decPrf}
	v.States = append(v.States, state)
	return nil
}
// The schnorrGenerateKeypair does exactly that -
// it generates a valid keypair for later use
// in producing signatures.
// I wanted to add a little bit of proper key
// management to the process but I couldn't work out
// how to pass a simple random stream to suite.Secret().Pick().
// I looked into Go streams very briefly  but decided
// I was spending too much time on that
// instead I passed /dev/urandom through the cipher
// interface.
func SchnorrGenerateKeypair(suite abstract.Suite) (SchnorrKeyset, error) {
	rsource := make([]byte, 16)
	_, err := rand.Read(rsource)
	if err != nil {
		return SchnorrKeyset{}, err
	}

	rct := suite.Cipher(rsource)

	x := suite.Secret().Pick(rct)  // some x
	y := suite.Point().Mul(nil, x) // y = g^x \in G, DLP.

	return SchnorrKeyset{x, y}, nil
}
func SchnorrMGenerateCommitment(suite abstract.Suite) (SchnorrMPrivateCommitment, error) {
	rsource := make([]byte, 16)
	_, err := rand.Read(rsource)
	if err != nil {
		return SchnorrMPrivateCommitment{}, err
	}
	// I have no idea if I just encrypted randomness or not
	// I'm hoping this just reads the state out.
	rct := suite.Cipher(rsource)

	v := suite.Secret().Pick(rct)  // some v
	t := suite.Point().Mul(nil, v) // g^v = t
	return SchnorrMPrivateCommitment{T: t, V: v}, nil
}
Example #19
0
func verifyCommitment(suite abstract.Suite, msg []byte, commitment abstract.Point, challenge abstract.Scalar) error {
	pb, err := commitment.MarshalBinary()
	if err != nil {
		return err
	}
	cipher := suite.Cipher(pb)
	cipher.Message(nil, nil, msg)
	// reconstructed challenge
	reconstructed := suite.Scalar().Pick(cipher)
	if !reconstructed.Equal(challenge) {
		return errors.New("Reconstructed challenge not equal to one given")
	}
	return nil
}
// this function produces a signature given a response from the server.
func SchnorrMComputeSignatureFromResponses(suite abstract.Suite,
	cc []byte,
	responses []SchnorrMResponse) SchnorrSignature {
	hct := suite.Cipher(cc)
	c := suite.Secret().Pick(hct) // H(m||r)

	var r abstract.Secret = responses[0].R

	for _, response := range responses[1:] {
		r.Add(r, response.R)
	}

	return SchnorrSignature{S: r, E: c}
}
Example #21
0
func (c *simpleCoder) ClientSetup(suite abstract.Suite,
	sharedsecrets []abstract.Cipher) {
	c.suite = suite
	keysize := suite.Cipher(nil).KeySize()

	// Use the provided shared secrets to seed
	// a pseudorandom DC-nets ciphers shared with each peer.
	npeers := len(sharedsecrets)
	c.dcciphers = make([]abstract.Cipher, npeers)
	for i := range sharedsecrets {
		key := make([]byte, keysize)
		sharedsecrets[i].Partial(key, key, nil)
		c.dcciphers[i] = suite.Cipher(key)
	}
}
Example #22
0
func TestShuffle(suite abstract.Suite, k int, N int) {

	rand := suite.Cipher(abstract.RandomKey)

	// Create a "server" private/public keypair
	h := suite.Scalar().Pick(rand)
	H := suite.Point().Mul(nil, h)

	// Create a set of ephemeral "client" keypairs to shuffle
	c := make([]abstract.Scalar, k)
	C := make([]abstract.Point, k)
	//	fmt.Println("\nclient keys:")
	for i := 0; i < k; i++ {
		c[i] = suite.Scalar().Pick(rand)
		C[i] = suite.Point().Mul(nil, c[i])
		//		fmt.Println(" "+C[i].String())
	}

	// ElGamal-encrypt all these keypairs with the "server" key
	X := make([]abstract.Point, k)
	Y := make([]abstract.Point, k)
	r := suite.Scalar() // temporary
	for i := 0; i < k; i++ {
		r.Pick(rand)
		X[i] = suite.Point().Mul(nil, r)
		Y[i] = suite.Point().Mul(H, r) // ElGamal blinding factor
		Y[i].Add(Y[i], C[i])           // Encrypted client public key
	}

	// Repeat only the actual shuffle portion for test purposes.
	for i := 0; i < N; i++ {

		// Do a key-shuffle
		Xbar, Ybar, prover := Shuffle(suite, nil, H, X, Y, rand)
		prf, err := proof.HashProve(suite, "PairShuffle", rand, prover)
		if err != nil {
			panic("Shuffle proof failed: " + err.Error())
		}
		//fmt.Printf("proof:\n%s\n",hex.Dump(prf))

		// Check it
		verifier := Verifier(suite, nil, H, X, Y, Xbar, Ybar)
		err = proof.HashVerify(suite, "PairShuffle", verifier, prf)
		if err != nil {
			panic("Shuffle verify failed: " + err.Error())
		}
	}
}
Example #23
0
// Apply a standard set of validation tests to a ciphersuite.
func TestSuite(suite abstract.Suite) {

	// Try hashing something
	h := suite.Hash()
	l := h.Size()
	//println("HashLen: ",l)
	h.Write([]byte("abc"))
	hb := h.Sum(nil)
	//println("Hash:")
	//println(hex.Dump(hb))
	if h.Size() != l || len(hb) != l {
		panic("inconsistent hash output length")
	}

	// Generate some pseudorandom bits
	s := suite.Cipher(hb)
	sb := make([]byte, 128)
	s.XORKeyStream(sb, sb)
	//println("Stream:")
	//println(hex.Dump(sb))

	// Test if it generates two fresh keys with nil cipher
	s1 := suite.NewKey(nil)
	s2 := suite.NewKey(nil)
	if s1.Equal(s2) {
		panic("NewKey returns twice the same key given nil")
	}

	// Test if it creates the same with the same seed
	st1 := suite.Cipher(hb)
	st2 := suite.Cipher(hb)
	s3 := suite.NewKey(st1)
	s4 := suite.NewKey(st2)
	if !s3.Equal(s4) {
		panic("NewKey returns two different keys given same stream")
	}

	// Test if it creates two different with random stream
	stream := random.Stream
	s5 := suite.NewKey(stream)
	s6 := suite.NewKey(stream)
	if s5.Equal(s6) {
		panic("NewKey returns same key given random stream")
	}

	// Test the public-key group arithmetic
	TestGroup(suite)
}
Example #24
0
// Test two group implementations that are supposed to be equivalent,
// and compare their results.
func TestCompareGroups(suite abstract.Suite, g1, g2 abstract.Group) {

	// Produce test results from the same pseudorandom seed
	r1 := testGroup(g1, suite.Cipher(abstract.NoKey))
	r2 := testGroup(g2, suite.Cipher(abstract.NoKey))

	// Compare resulting Points
	for i := range r1 {
		b1, _ := r1[i].MarshalBinary()
		b2, _ := r2[i].MarshalBinary()
		if !bytes.Equal(b1, b2) {
			println("result-pair", i,
				"\n1:", r1[i].String(),
				"\n2:", r2[i].String())
			panic("unequal results")
		}
	}
}
// Generates all of the private parameters aside
// from the private / public key pair. Do that
// separately.
func NewPrivateParams(suite abstract.Suite, info []byte) (WISchnorrBlindPrivateParams, error) {

	r1 := make([]byte, 16)
	r2 := make([]byte, 16)
	r3 := make([]byte, 16)

	v := make([]byte, 16)
	_, err := rand.Read(r1)
	if err != nil {
		return WISchnorrBlindPrivateParams{}, err
	}
	_, err = rand.Read(r2)
	if err != nil {
		return WISchnorrBlindPrivateParams{}, err
	}
	_, err = rand.Read(r3)
	if err != nil {
		return WISchnorrBlindPrivateParams{}, err
	}
	_, err = rand.Read(v)
	if err != nil {
		return WISchnorrBlindPrivateParams{}, err
	}
	rc1 := suite.Cipher(r1)
	rc2 := suite.Cipher(r2)
	rc3 := suite.Cipher(r3)

	z, err := GenerateZ(suite, info)
	if err != nil {
		return WISchnorrBlindPrivateParams{}, err
	}

	u := suite.Secret().Pick(rc1)
	s := suite.Secret().Pick(rc2)
	d := suite.Secret().Pick(rc3)

	a := suite.Point().Mul(nil, u)  // g^u
	b1 := suite.Point().Mul(nil, s) // g^s
	b2 := suite.Point().Mul(z, d)   // z^d
	b := suite.Point().Add(b1, b2)  // g^sz^d

	return WISchnorrBlindPrivateParams{u, s, d, z, a, b}, nil
}
Example #26
0
func (c *ownedCoder) ClientSetup(suite abstract.Suite,
	sharedsecrets []abstract.Cipher) {
	c.commonSetup(suite)
	keysize := suite.Cipher(nil).KeySize()

	// Use the provided shared secrets to seed
	// a pseudorandom public-key encryption secret, and
	// a pseudorandom DC-nets cipher shared with each peer.
	npeers := len(sharedsecrets)
	c.vkeys = make([]abstract.Secret, npeers)
	c.vkey = suite.Secret()
	c.dcciphers = make([]abstract.Cipher, npeers)
	for i := range sharedsecrets {
		c.vkeys[i] = suite.Secret().Pick(sharedsecrets[i])
		c.vkey.Add(c.vkey, c.vkeys[i])
		key := make([]byte, keysize)
		sharedsecrets[i].Partial(key, key, nil)
		c.dcciphers[i] = suite.Cipher(key)
	}
}
Example #27
0
File: enc.go Project: Liamsi/crypto
func header(suite abstract.Suite, X abstract.Point, x abstract.Secret,
	Xb, xb []byte, anonymitySet Set) []byte {

	//fmt.Printf("Xb %s\nxb %s\n",
	//		hex.EncodeToString(Xb),hex.EncodeToString(xb))

	// Encrypt the master secret key with each public key in the set
	S := suite.Point()
	hdr := Xb
	for i := range anonymitySet {
		Y := anonymitySet[i]
		S.Mul(Y, x) // compute DH shared secret
		seed, _ := S.MarshalBinary()
		cipher := suite.Cipher(seed)
		xc := make([]byte, len(xb))
		cipher.Partial(xc, xb, nil)
		hdr = append(hdr, xc...)
	}
	return hdr
}
Example #28
0
File: enc.go Project: Liamsi/crypto
// Encrypt a message for reading by any member of an explit anonymity set.
// The caller supplies one or more keys representing the anonymity set.
// If the provided set contains only one public key,
// this reduces to conventional single-receiver public-key encryption.
//
// If hide is true,
// Encrypt will produce a uniformly random-looking byte-stream,
// which reveals no metadata other than message length
// to anyone unable to decrypt the message.
// The provided abstract.Suite must support
// uniform-representation encoding of public keys for this to work.
//
func Encrypt(suite abstract.Suite, rand cipher.Stream, message []byte,
	anonymitySet Set, hide bool) []byte {

	xb, hdr := encryptKey(suite, rand, anonymitySet, hide)
	cipher := suite.Cipher(xb)

	// We now know the ciphertext layout
	hdrhi := 0 + len(hdr)
	msghi := hdrhi + len(message)
	machi := msghi + cipher.KeySize()
	ciphertext := make([]byte, machi)
	copy(ciphertext, hdr)

	// Now encrypt and MAC the message based on the master secret
	ctx := ciphertext[hdrhi:msghi]
	mac := ciphertext[msghi:machi]
	cipher.Message(ctx, message, ctx)
	cipher.Partial(mac, nil, nil)
	return ciphertext
}
Example #29
0
// verifyChallenge will reconstruct the challenge in order to see if any of the
// components of the challenge has been spoofed or not. It may be a different
// timestamp .
func VerifyChallenge(suite abstract.Suite, reply *StampSignature) error {
	dbg.Lvlf3("Reply is %+v", reply)
	// marshal the V
	pbuf, err := reply.AggCommit.MarshalBinary()
	if err != nil {
		return err
	}
	c := suite.Cipher(pbuf)
	// concat timestamp and merkle root
	var b bytes.Buffer
	if err := binary.Write(&b, binary.LittleEndian, reply.Timestamp); err != nil {
		return err
	}
	cbuf := append(b.Bytes(), reply.MerkleRoot...)
	c.Message(nil, nil, cbuf)
	challenge := suite.Secret().Pick(c)
	if challenge.Equal(reply.Challenge) {
		return nil
	}
	return errors.New("Challenge reconstructed is not equal to the one given")
}
/* This function implements the verification protocol and can be used
   by any party given a decoded schnorr signature, a
   message and valid information. Invalid information will break the protocol
   and produce an invalid message; this is tested for in the unit test code. */
func VerifyBlindSignature(suite abstract.Suite, pk SchnorrPublicKey, sig WIBlindSignature, info []byte, msg []byte) (bool, error) {

	z, err := GenerateZ(suite, info)
	if err != nil {
		return false, err
	}

	gp := suite.Point().Mul(nil, sig.P)
	yw := suite.Point().Mul(pk.Y, sig.W)
	gpyw := suite.Point().Add(gp, yw)

	gs := suite.Point().Mul(nil, sig.S)
	zd := suite.Point().Mul(z, sig.D)
	gszd := suite.Point().Add(gs, zd)

	bP1, _ := gpyw.MarshalBinary()
	bP2, _ := gszd.MarshalBinary()
	bZ, _ := z.MarshalBinary()

	var combinedmsg []byte

	combinedmsg = append(combinedmsg, bP1...)
	combinedmsg = append(combinedmsg, bP2...)
	combinedmsg = append(combinedmsg, bZ...)
	combinedmsg = append(combinedmsg, msg...)

	hasher := sha3.New256()
	hasher.Write(combinedmsg)
	bSig := hasher.Sum(nil)
	bSigCt := suite.Cipher(bSig)

	hsig := suite.Secret().Pick(bSigCt)

	vsig := suite.Secret()
	vsig.Add(sig.W, sig.D)

	return hsig.Equal(vsig), nil
}