Пример #1
0
func TestGenTempKey(t *testing.T) {
	privkey := [PrivateKeySize]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0xaf, 0xff}
	testPriv := [PrivateKeySize]byte{0x00, 0x00, 0x03, 0x03, 0x03, 0x06, 0x07, 0x08, 0x09, 0x07, 0x07, 0x07, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0xaf, 0xff}
	testPriv2 := [PrivateKeySize]byte{0x01, 0x02, 0x03, 0x03, 0x03, 0x06, 0x07, 0x08, 0x09, 0x07, 0x07, 0x07, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0xaf, 0xff}
	testPub := [PublicKeySize]byte{}
	testPub2 := [PublicKeySize]byte{}
	curve25519.ScalarBaseMult(&testPub, &testPriv)
	curve25519.ScalarBaseMult(&testPub2, &testPriv2)
	serverPriv, serverPub, challenge := GenTempKeyTime(uint64(time.Now().Unix()), &privkey)
	_, _, _ = serverPriv, serverPub, challenge
	answer := Answer(challenge, &testPriv)
	ok := Verify(answer, &privkey, &testPub)
	if !ok {
		t.Error("Verification failed")
	}
	ok = Verify(answer, &privkey, &testPub2)
	if ok {
		t.Error("Verification must fail 1")
	}
	answer = Answer(challenge, &testPriv2)
	ok = Verify(answer, &privkey, &testPub)
	if ok {
		t.Error("Verification must fail 2")
	}
	if !VerifyTimeNow(answer, 1) {
		t.Error("Time verification failed")
	}
	answer[0] = 0x01 // bad time
	if VerifyTimeNow(answer, 1) {
		t.Error("Time verification must fail")
	}
}
Пример #2
0
func TestStreamData(t *testing.T) {
	var serverPrivate, clientPrivate, serverPublic, clientPublic [32]byte

	randBytes(serverPrivate[:])
	randBytes(clientPrivate[:])
	curve25519.ScalarBaseMult(&serverPublic, &serverPrivate)
	curve25519.ScalarBaseMult(&clientPublic, &clientPrivate)

	x, y := NewBiDiPipe()
	client := NewClient(x, &clientPrivate, &clientPublic, &serverPublic)
	server := NewServer(y, &serverPrivate)

	clientComplete := make(chan bool)
	go func() {
		defer x.Close()
		err := client.Handshake()
		if err != nil {
			panic(err)
		}
		if _, err = client.Write(nil); err != nil {
			panic(err)
		}
		if _, err = client.Write([]byte("hello")); err != nil {
			panic(err)
		}
		if _, err = client.Write([]byte("world")); err != nil {
			panic(err)
		}
		if _, err = client.Write(make([]byte, 20*1024)); err != nil {
			panic(err)
		}
		close(clientComplete)
	}()

	serverComplete := make(chan bool)
	go func() {
		defer y.Close()
		err := server.Handshake()
		if err != nil {
			panic(err)
		}

		h := sha256.New()
		if _, err := io.Copy(h, server); err != nil {
			panic(err)
		}
		if h.Sum(nil)[0] != 0xec {
			panic("bad data received")
		}
		close(serverComplete)
	}()

	<-clientComplete
	<-serverComplete
}
Пример #3
0
// FillKeyExchange sets elements of kx with key exchange information from the
// ratchet.
func (r *Ratchet) FillKeyExchange(kx *pond.KeyExchange) error {
	if r.kxPrivate0 == nil || r.kxPrivate1 == nil {
		return errors.New("ratchet: handshake already complete")
	}

	var public0, public1 [32]byte
	curve25519.ScalarBaseMult(&public0, r.kxPrivate0)
	curve25519.ScalarBaseMult(&public1, r.kxPrivate1)

	kx.Dh = public0[:]
	kx.Dh1 = public1[:]

	return nil
}
Пример #4
0
func (r *Ratchet) EncryptFirst(out, msg []byte, theirRatchetPublic *[32]byte) []byte {
	r.saved = make(map[[32]byte]map[uint32]savedKey)
	r.ratchet = true
	r.randBytes(r.ourRatchetPrivate[:])
	copy(r.theirRatchetPublic[:], theirRatchetPublic[:])
	copy(r.theirAuthPublic[:], theirRatchetPublic[:])

	var sharedKey [32]byte
	curve25519.ScalarMult(&sharedKey, &r.ourRatchetPrivate, &r.theirRatchetPublic)
	h := hmac.New(sha256.New, sharedKey[:])
	deriveKey(&r.rootKey, rootKeyLabel, h)
	deriveKey(&r.recvHeaderKey, headerKeyLabel, h)
	deriveKey(&r.nextSendHeaderKey, sendHeaderKeyLabel, h)
	deriveKey(&r.nextRecvHeaderKey, nextRecvHeaderKeyLabel, h)
	deriveKey(&r.recvChainKey, chainKeyLabel, h)

	var ourRatchetPublic [32]byte
	curve25519.ScalarBaseMult(&ourRatchetPublic, &r.ourRatchetPrivate)
	tag_idx := len(out)
	out = append(out, make([]byte, authSize)...)
	out = append(out, ourRatchetPublic[:]...)
	out = r.encrypt(out, msg)
	r.FillAuth(out[tag_idx:][:authSize], out[tag_idx+authSize:], theirRatchetPublic)
	return out
}
Пример #5
0
func NewTestServer(setup func(dir string)) *TestServer {
	listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
	if err != nil {
		panic(err)
	}

	dir, err := ioutil.TempDir("", "servertest")
	if err != nil {
		panic(err)
	}

	if setup != nil {
		setup(dir)
	}

	testServer := &TestServer{
		listener: listener,
		addr:     listener.Addr().(*net.TCPAddr),
		dir:      dir,
		server:   NewServer(dir, true),
	}
	io.ReadFull(rand.Reader, testServer.identity[:])
	curve25519.ScalarBaseMult(&testServer.identityPublic, &testServer.identity)

	go testServer.Loop()
	return testServer
}
Пример #6
0
func (c *client) sendDraft(draft *Draft) (uint64, time.Time, error) {
	to := c.contacts[draft.to]

	// Zero length bodies are ACKs.
	if len(draft.body) == 0 {
		draft.body = " "
	}

	id := c.randId()
	created := c.Now()
	message := &pond.Message{
		Id:               proto.Uint64(id),
		Time:             proto.Int64(created.Unix()),
		Body:             []byte(draft.body),
		BodyEncoding:     pond.Message_RAW.Enum(),
		Files:            draft.attachments,
		DetachedFiles:    draft.detachments,
		SupportedVersion: proto.Int32(protoVersion),
	}

	if r := draft.inReplyTo; r != 0 {
		message.InReplyTo = proto.Uint64(r)
	}

	if to.ratchet == nil {
		var nextDHPub [32]byte
		curve25519.ScalarBaseMult(&nextDHPub, &to.currentDHPrivate)
		message.MyNextDh = nextDHPub[:]
	}

	err := c.send(to, message)
	return id, created, err
}
Пример #7
0
func (tmp AddressTemplate) genDetermKeys(nonce, nym []byte) (pub, priv *[KeySize]byte) {
	pub, priv = new([KeySize]byte), new([KeySize]byte)
	privkeyA := calcHmac(tmp.Secret, nonce, nym)
	copy(priv[:], privkeyA)
	curve25519.ScalarBaseMult(pub, priv)
	return pub, priv
}
Пример #8
0
func (c *Conn) handshakeAsServer(ctx context.Context) error {
	// Check that a private key has actually been specified.
	c.curves = c.cfg.Curvek
	if keyIsZero(&c.curves) {
		return fmt.Errorf("Server private key not specified.")
	}

	// Derive server public key from server private key.
	if c.cfg.CurveK != nil {
		c.curveS = *c.cfg.CurveK
	} else {
		curve25519.ScalarBaseMult(&c.curveS, &c.curves)
	}

	err := c.hsReadClientHello()
	if err != nil {
		return err
	}

	err = c.hsWriteServerHello()
	if err != nil {
		return err
	}

	// Determine the shared secret key used for encryption.
	box.Precompute(&c.curveCtSt, &c.curveCt, &c.curvest)

	err = c.hsReadClientCommence()
	if err != nil {
		return err
	}

	return nil
}
Пример #9
0
func TestKeyPairs(t *testing.T) {
	var pubkey, privkey [32]byte
	ikp := GenerateIdentityKeyPair()
	copy(privkey[:], ikp.PrivateKey.Key()[:])
	curve25519.ScalarBaseMult(&pubkey, &privkey)
	assert.Equal(t, pubkey[:], ikp.PublicKey.Key()[:])
}
Пример #10
0
// ECDH computes a Diffie-Hellman (DH) key exchange over the elliptic curve (EC)
// curve25519. If ownPublicKey is given it is used to check for the key
// reflection attack. Otherwise it is derived from privateKey.
func ECDH(privateKey, peersPublicKey, ownPublicKey *[32]byte) (*[32]byte, error) {
	var (
		sharedKey [32]byte
		pubKey    []byte
	)
	// check mandatory key length
	if privateKey == nil {
		return nil, log.Error("cipher: curve25519.ECDH(): privateKey == nil")
	}
	if peersPublicKey == nil {
		return nil, log.Error("cipher: curve25519.ECDH(): peersPublicKey == nil")
	}
	// check for key reflection attack
	if ownPublicKey != nil {
		pubKey = ownPublicKey[:]
	} else {
		var publicKey [32]byte
		curve25519.ScalarBaseMult(&publicKey, privateKey)
		pubKey = publicKey[:]
	}
	if bytes.Equal(pubKey, peersPublicKey[:]) {
		return nil, log.Errorf("cipher: curve25519.ECDH(): publicKey == peersPublicKey")
	}
	// perform Diffie-Hellman key exchange
	curve25519.ScalarMult(&sharedKey, privateKey, peersPublicKey)
	return &sharedKey, nil
}
Пример #11
0
func UnmarshalKeyExchange(rand io.Reader, meetingPlace MeetingPlace, serialised []byte) (*KeyExchange, error) {
	var p panda_proto.KeyExchange
	if err := proto.Unmarshal(serialised, &p); err != nil {
		return nil, err
	}

	sharedSecret, ok := newSharedSecret(p.SharedSecret)
	if !ok {
		return nil, errors.New("panda: invalid shared secret in serialised key exchange")
	}

	kx := &KeyExchange{
		rand:         rand,
		meetingPlace: meetingPlace,
		status:       p.GetStatus(),
		sharedSecret: sharedSecret,
		serialised:   serialised,
		kxBytes:      p.KeyExchangeBytes,
		message1:     p.Message1,
		message2:     p.Message2,
	}

	copy(kx.key[:], p.Key)
	copy(kx.meeting1[:], p.Meeting1)
	copy(kx.meeting2[:], p.Meeting2)
	copy(kx.sharedKey[:], p.SharedKey)
	copy(kx.dhPrivate[:], p.DhPrivate)
	curve25519.ScalarBaseMult(&kx.dhPublic, &kx.dhPrivate)

	return kx, nil
}
Пример #12
0
// Share creates a shared key, which the given key can use to decrypt
// the secret.
// Requires the master key to be unsealed.
func (s *Secret) Share(key *Key) (shared *Secret, err error) {
	if IsSealed() {
		err = errors.New("Please unseal first")
		return
	}
	shared = new(Secret)
	shared.Name = s.Name

	shared.Key = *key

	err = s.Key.Decrypt()
	if err != nil {
		return
	}
	defer s.Key.Zero()

	if err = shared.newNonce(); err != nil {
		return
	}

	// Generate a public key from the master
	pub := new([32]byte)
	curve25519.ScalarBaseMult(pub, master)

	shared.Pubkey = pub[:]

	shared.Message = box.Seal(
		nil,
		s.Key.raw[:],
		shared.nonce(),
		key.pubkey(),
		master)

	return
}
Пример #13
0
func (kp *curve25519KeyPair) generate(rand io.Reader) error {
	if _, err := io.ReadFull(rand, kp.priv[:]); err != nil {
		return err
	}
	curve25519.ScalarBaseMult(&kp.pub, &kp.priv)
	return nil
}
Пример #14
0
func TestBox(t *testing.T) {
	var privateKey1, privateKey2 [32]byte
	for i := range privateKey1[:] {
		privateKey1[i] = 1
	}
	for i := range privateKey2[:] {
		privateKey2[i] = 2
	}

	var publicKey1 [32]byte
	curve25519.ScalarBaseMult(&publicKey1, &privateKey1)
	var message [64]byte
	for i := range message[:] {
		message[i] = 3
	}

	var nonce [24]byte
	for i := range nonce[:] {
		nonce[i] = 4
	}

	box := Seal(nil, message[:], &nonce, &publicKey1, &privateKey2)

	// expected was generated using the C implementation of NaCl.
	expected, _ := hex.DecodeString("78ea30b19d2341ebbdba54180f821eec265cf86312549bea8a37652a8bb94f07b78a73ed1708085e6ddd0e943bbdeb8755079a37eb31d86163ce241164a47629c0539f330b4914cd135b3855bc2a2dfc")

	if !bytes.Equal(box, expected) {
		t.Fatalf("box didn't match, got\n%x\n, expected\n%x", box, expected)
	}
}
Пример #15
0
// Encrypt an envelope (Client-Mix) with CURVE25519-AES-GCM
func Encrypt(peerPublicKey, myPrivateKey *[KeySize]byte, cleartextData []byte) ([]byte, error) {
	var myPublicKey [KeySize]byte
	if myPrivateKey == nil {
		myPrivateKey = new([KeySize]byte)
		_, err := io.ReadFull(Rand, myPrivateKey[:])
		if err != nil {
			return nil, err
		}
	}
	secret, nonce := CalculateSharedSecret(peerPublicKey, myPrivateKey, nil)
	if secret == nil {
		return nil, ErrNoKeys
	}
	curve25519.ScalarBaseMult(&myPublicKey, myPrivateKey)
	encData, err := GCMEncrypt(nonce[:], secret[:], cleartextData)
	if err != nil {
		return nil, err
	}
	encData2 := make([]byte, KeySize*3+len(encData))
	copy(encData2[0:KeySize], peerPublicKey[:])
	copy(encData2[KeySize:KeySize*2], myPublicKey[:])
	copy(encData2[KeySize*2:KeySize*3], nonce[:])
	copy(encData2[KeySize*3:], encData)
	return encData2, nil
}
Пример #16
0
func TestBasic(t *testing.T) {
	var priv, pub [32]byte
	rand.Read(priv[:])
	curve25519.ScalarBaseMult(&pub, &priv)

	var d Descriptor
	d.Nickname = "mylittletorry18"
	d.Contact = "TvdW"
	d.Platform = "Tor 0.2.6.2-alpha on MS-DOS"
	d.Address = net.ParseIP("80.57.124.58")
	d.ORPort = 1234
	d.UptimeStart = time.Now()
	d.NTORKey = pub[:]
	d.BandwidthAvg = 1000000
	d.BandwidthBurst = 1200000
	d.BandwidthObserved = 30107
	k, err := openssl.GenerateRSAKeyWithExponent(1024, 65537)
	if err != nil {
		t.Error(err)
	}
	d.OnionKey, err = openssl.GenerateRSAKeyWithExponent(1024, 65537)
	d.SigningKey = k
	desc, err := d.SignedDescriptor()
	if err != nil {
		t.Error(err)
	}

	log.Println(desc)
}
Пример #17
0
// DeriveKeyPair takes a utf8 string, returns the [32]byte pub and secret keys
func DeriveKeyPair(input string) (pubKey, privateKey *[32]byte) {
	privateKey = new([32]byte)
	pubKey = new([32]byte)
	privateKeySlice := sha512.Sum512([]byte(input))
	copy(privateKey[:], privateKeySlice[0:32])
	curve25519.ScalarBaseMult(pubKey, privateKey)
	return
}
Пример #18
0
// encrypt acts like append() but appends an encrypted version of msg to out.
func (r *Ratchet) encrypt(out, msg []byte) []byte {
	if r.ratchet {
		r.randBytes(r.ourRatchetPrivate[:])
		r.randBytes(r.ourAuthPrivate[:])
		copy(r.sendHeaderKey[:], r.nextSendHeaderKey[:])

		var sharedKey, keyMaterial [32]byte
		curve25519.ScalarMult(&sharedKey, &r.ourRatchetPrivate, &r.theirRatchetPublic)
		sha := sha256.New()
		sha.Write(rootKeyUpdateLabel)
		sha.Write(r.rootKey[:])
		sha.Write(sharedKey[:])

		sha.Sum(keyMaterial[:0])
		h := hmac.New(sha256.New, keyMaterial[:])
		deriveKey(&r.rootKey, rootKeyLabel, h)
		deriveKey(&r.nextSendHeaderKey, sendHeaderKeyLabel, h)
		deriveKey(&r.sendChainKey, chainKeyLabel, h)

		r.prevSendCount, r.sendCount = r.sendCount, 0
		r.ratchet = false
	}

	var messageKey [32]byte
	h := hmac.New(sha256.New, r.sendChainKey[:])
	deriveKey(&messageKey, messageKeyLabel, h)
	deriveKey(&r.sendChainKey, chainKeyStepLabel, h)

	var ourRatchetPublic, ourAuthPublic [32]byte
	curve25519.ScalarBaseMult(&ourRatchetPublic, &r.ourRatchetPrivate)
	curve25519.ScalarBaseMult(&ourAuthPublic, &r.ourAuthPrivate)
	var header [headerSize]byte
	var headerNonce, messageNonce [24]byte
	r.randBytes(headerNonce[:])
	r.randBytes(messageNonce[:])

	binary.LittleEndian.PutUint32(header[0:4], r.sendCount)
	binary.LittleEndian.PutUint32(header[4:8], r.prevSendCount)
	copy(header[8:], ourRatchetPublic[:])
	copy(header[8+32:], ourAuthPublic[:])
	copy(header[nonceInHeaderOffset:], messageNonce[:])
	out = append(out, headerNonce[:]...)
	out = secretbox.Seal(out, header[:], &headerNonce, &r.sendHeaderKey)
	r.sendCount++
	return secretbox.Seal(out, msg, &messageNonce, &messageKey)
}
Пример #19
0
func TestKeyEntry(t *testing.T) {
	// create UID message
	msg, err := Create("*****@*****.**", false, "", "", Strict,
		hashchain.TestEntry, cipher.RandReader)
	if err != nil {
		t.Fatal(err)
	}

	// KeyInit
	now := uint64(times.Now())
	ki, _, privateKey, err := msg.KeyInit(1, now+times.Day, now-times.Day,
		false, "mute.berlin", "", "", cipher.RandReader)
	if err != nil {
		t.Fatal(err)
	}

	// KeyEntry
	ke, err := ki.KeyEntryECDHE25519(msg.SigPubKey())
	if err != nil {
		t.Fatal(err)
	}

	// verify consistency
	if err := ke.Verify(); err != nil {
		t.Fatal(err)
	}

	// equal
	if !KeyEntryEqual(ke, ke) {
		t.Error("ke should be equal to itself")
	}
	a := ke
	var b KeyEntry
	b.CIPHERSUITE = a.CIPHERSUITE
	b.FUNCTION = a.FUNCTION
	b.HASH = a.HASH
	b.PUBKEY = a.PUBKEY
	if !KeyEntryEqual(a, &b) {
		t.Error("a and b should be equal to itself")
	}

	// private key check
	if err := ke.SetPrivateKey(privateKey); err != nil {
		t.Fatal(err)
	}
	privKey := ke.PrivateKey32()
	if privateKey != base64.Encode(privKey[:]) {
		t.Error("private keys differ")
	}

	// public key check
	var publicKey [32]byte
	curve25519.ScalarBaseMult(&publicKey, privKey)
	pubKey := ke.PublicKey32()
	if !bytes.Equal(publicKey[:], pubKey[:]) {
		t.Error("public keys differ")
	}
}
Пример #20
0
// genKey returns a keypair
func genKey() (pub, priv *[KeySize]byte, err error) {
	publicKey := new([KeySize]byte)
	privateKey := new([KeySize]byte)
	if _, err := io.ReadFull(Rand, privateKey[:]); err != nil {
		return nil, nil, err
	}
	curve25519.ScalarBaseMult(publicKey, privateKey)
	return publicKey, privateKey, nil
}
Пример #21
0
// Pubkey returns the associated public key for the supplied private key.
func (k *Private) Pubkey() *Public {
	var pub [32]byte
	priv := [32]byte(*k)

	// Performs ScalarBaseMult on the supplied private key, returning the public key
	curve25519.ScalarBaseMult(&pub, &priv)
	public := Public(pub)
	return &public
}
Пример #22
0
func genKeyRandom() (pub, priv *[KeySize]byte, err error) {
	privateKey, err := genNonce()
	if err != nil {
		return nil, nil, err
	}
	publicKey := new([KeySize]byte)
	curve25519.ScalarBaseMult(publicKey, privateKey)
	return publicKey, privateKey, nil
}
Пример #23
0
// NewECDH_Curve25519 returns an Elliptic Curve Diffie-Hellman Curve25519 KeyExchange algorithm.
func NewECDH_Curve25519() (err error, keyexchange KeyExchange) {
	c := new(c255)
	_, err = io.ReadFull(rand.Reader, c.privateKey[:])
	if err != nil {
		return
	}
	curve25519.ScalarBaseMult(&c.publicKey, &c.privateKey)
	return nil, c
}
Пример #24
0
func TestHandshake(t *testing.T) {
	var serverPrivate, clientPrivate, serverPublic, clientPublic [32]byte

	randBytes(serverPrivate[:])
	randBytes(clientPrivate[:])
	curve25519.ScalarBaseMult(&serverPublic, &serverPrivate)
	curve25519.ScalarBaseMult(&clientPublic, &clientPrivate)

	clientError, serverError := runHandshake(&clientPrivate, &clientPublic, &serverPrivate, &serverPublic)
	if clientError != nil || serverError != nil {
		t.Fatalf("handshake failed: client:'%s' server:'%s'", clientError, serverError)
	}

	serverPublic[0] ^= 0x40
	clientError, serverError = runHandshake(&clientPrivate, &clientPublic, &serverPrivate, &serverPublic)
	if clientError == nil && serverError == nil {
		t.Fatal("bad handshake succeeded")
	}
}
Пример #25
0
// Curve25519Generate generates a new Curve25519 key pair.
func Curve25519Generate(rand io.Reader) (*Curve25519Key, error) {
	var c Curve25519Key
	c.privateKey = new([32]byte)
	if _, err := io.ReadFull(rand, c.privateKey[:]); err != nil {
		return nil, err
	}
	c.publicKey = new([32]byte)
	curve25519.ScalarBaseMult(c.publicKey, c.privateKey)
	return &c, nil
}
Пример #26
0
func TestKeys(t *testing.T) {
	var cpriv, cpub, cpub2 [32]byte
	pub, priv, err := ed25519.GenerateKey(rand.Reader)
	if assert.NoError(t, err) {
		assert.True(t, extra25519.PublicKeyToCurve25519(&cpub, pub), "Calling PublicKeyToCurve25519 failed")
		extra25519.PrivateKeyToCurve25519(&cpriv, priv)
		curve25519.ScalarBaseMult(&cpub2, &cpriv)
		assert.Equal(t, cpub, cpub2)
	}
}
Пример #27
0
func TestCalculateSharedSecret(t *testing.T) {
	var pubkey1, privkey1, pubkey2, privkey2 [KeySize]byte
	testData := []byte("Some data to be tested")
	io.ReadFull(Rand, privkey1[:])
	io.ReadFull(Rand, privkey2[:])
	curve25519.ScalarBaseMult(&pubkey1, &privkey1)
	curve25519.ScalarBaseMult(&pubkey2, &privkey2)
	secret, nonce := CalculateSharedSecret(nil, nil, nil)
	if secret != nil || nonce != nil {
		t.Error("CalculateSharedSecret without parameters must return nils")
	}
	secret1, nonce1 := CalculateSharedSecret(&pubkey1, &privkey2, nil)
	secret2, nonce2 := CalculateSharedSecret(&pubkey2, &privkey1, nonce1)
	if *secret1 != *secret2 {
		t.Error("Secrets do not match")
	}
	if *nonce1 != *nonce2 || nonce1 == nil {
		t.Error("Nonce creation failed")
	}
	encryptedData, err := GCMEncrypt(nonce1[:], secret1[:], testData)
	if err != nil {
		t.Fatalf("GCMEncrypt: %s", err)
	}
	decryptedData, err := GCMDecrypt(nonce2[:], secret2[:], encryptedData)
	if err != nil {
		t.Fatalf("GCMDecrypt: %s", err)
	}
	if !bytes.Equal(testData, decryptedData) {
		t.Error("Pre/Post encryption data do not match")
	}
	encryptedData, err = Encrypt(&pubkey2, &privkey1, testData)
	if err != nil {
		t.Errorf("Encrypt failed: %s", err)
	}
	decryptedData, err = Decrypt(func(*[KeySize]byte) *[KeySize]byte { return &privkey2 }, encryptedData)
	if err != nil {
		t.Errorf("Decrypt failed: %s", err)
	}
	if !bytes.Equal(testData, decryptedData) {
		t.Error("Pre/Post encryption data do not match")
	}
}
Пример #28
0
func pairedRatchet() (a, b *Ratchet) {
	var privA, pubA, privB, pubB [32]byte
	io.ReadFull(rand.Reader, privA[:])
	io.ReadFull(rand.Reader, privB[:])
	curve25519.ScalarBaseMult(&pubA, &privA)
	curve25519.ScalarBaseMult(&pubB, &privB)

	// These are the "Ed25519" public keys for the two parties. Of course,
	// they're not actually valid Ed25519 keys but that doesn't matter
	// here.
	var aSigningPublic, bSigningPublic [32]byte
	io.ReadFull(rand.Reader, aSigningPublic[:])
	io.ReadFull(rand.Reader, bSigningPublic[:])

	a, b = New(rand.Reader), New(rand.Reader)
	a.Now = nowFunc
	b.Now = nowFunc
	a.MyIdentityPrivate = &privA
	b.MyIdentityPrivate = &privB
	a.TheirIdentityPublic = &pubB
	b.TheirIdentityPublic = &pubA
	a.MySigningPublic = &aSigningPublic
	b.MySigningPublic = &bSigningPublic
	a.TheirSigningPublic = &bSigningPublic
	b.TheirSigningPublic = &aSigningPublic

	kxA, kxB := new(pond.KeyExchange), new(pond.KeyExchange)
	if err := a.FillKeyExchange(kxA); err != nil {
		panic(err)
	}
	if err := b.FillKeyExchange(kxB); err != nil {
		panic(err)
	}
	if err := a.CompleteKeyExchange(kxB, true); err != nil {
		panic(err)
	}
	if err := b.CompleteKeyExchange(kxA, true); err != nil {
		panic(err)
	}

	return
}
Пример #29
0
func TestPublicPrivateKeys(test *testing.T) {
	tox := initialize(test)
	defer tox.Destroy()
	publicKey := tox.GetPublicKey()
	secretKey := tox.GetSecretKey()
	var product [32]byte
	curve25519.ScalarBaseMult(&product, (*[32]byte)(&secretKey))
	if product != publicKey {
		test.Fatalf("Failed to generate valid Tox public/private key pair.")
	}
}
Пример #30
0
func (a *api) auth() bool {
	var err error

	k := new(secrets.Key)

	var secretKey string

	// Grab the credentials, look in the header first and fall back to the query string.
	if k.Name = a.req.Header.Get("X-Secret-ID"); k.Name == "" {
		k.Name = a.req.FormValue("secretid")
	}
	if secretKey = a.req.Header.Get("X-Secret-Key"); secretKey == "" {
		secretKey = a.req.FormValue("secretkey")
	}

	// If the master key has been used then just check the key, else check both.
	if k.Name == secrets.MasterKeyName {
		if secretKeyRegex.MatchString(secretKey) != true {
			log.Error("Invalid auth credential format.")
			return false
		}
	} else if secretIDRegex.MatchString(k.Name) != true || secretKeyRegex.MatchString(secretKey) != true {
		log.Error("Invalid auth credential format.")
		return false
	}

	a.keyID = k.Name
	a.key, err = base64.StdEncoding.DecodeString(
		secretKey)
	if err != nil {
		return false
	}

	priv := new([32]byte)
	pub := new([32]byte)

	copy(priv[:], a.key)
	defer secrets.Zero(priv[:])

	err = database.GetKey(k)
	if err != nil {
		return false
	}

	if !k.ReadOnly {
		a.admin = true
	}

	curve25519.ScalarBaseMult(pub, priv)
	if subtle.ConstantTimeCompare(pub[:], k.Public) == 1 {
		return true
	}
	return false
}