Esempio n. 1
0
// Tests whether a message can be signed, and wrapped in plain-text.
func TestMessageCleartextSignRecover(t *testing.T) {
	key, err := crypto.GenerateKey()
	if err != nil {
		t.Fatalf("failed to create crypto key: %v", err)
	}
	payload := []byte("hello world")

	msg := NewMessage(payload)
	if _, err := msg.Wrap(DefaultPoW, Options{
		From: key,
	}); err != nil {
		t.Fatalf("failed to sign message: %v", err)
	}
	if msg.Flags&signatureFlag != signatureFlag {
		t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, signatureFlag)
	}
	if bytes.Compare(msg.Payload, payload) != 0 {
		t.Fatalf("payload mismatch after signing: have 0x%x, want 0x%x", msg.Payload, payload)
	}

	pubKey := msg.Recover()
	if pubKey == nil {
		t.Fatalf("failed to recover public key")
	}
	p1 := elliptic.Marshal(crypto.S256(), key.PublicKey.X, key.PublicKey.Y)
	p2 := elliptic.Marshal(crypto.S256(), pubKey.X, pubKey.Y)
	if !bytes.Equal(p1, p2) {
		t.Fatalf("public key mismatch: have 0x%x, want 0x%x", p2, p1)
	}
}
Esempio n. 2
0
func main() {
	logger.AddLogSystem(logger.NewStdLogSystem(os.Stdout, log.LstdFlags, logger.InfoLevel))

	// Generate the peer identity
	key, err := crypto.GenerateKey()
	if err != nil {
		fmt.Printf("Failed to generate peer key: %v.\n", err)
		os.Exit(-1)
	}
	name := common.MakeName("whisper-go", "1.0")
	shh := whisper.New()

	// Create an Shift peer to communicate through
	server := p2p.Server{
		PrivateKey: key,
		MaxPeers:   10,
		Name:       name,
		Protocols:  []p2p.Protocol{shh.Protocol()},
		ListenAddr: ":30300",
		NAT:        nat.Any(),
	}
	fmt.Println("Starting Shift peer...")
	if err := server.Start(); err != nil {
		fmt.Printf("Failed to start Shift peer: %v.\n", err)
		os.Exit(1)
	}

	// Send a message to self to check that something works
	payload := fmt.Sprintf("Hello world, this is %v. In case you're wondering, the time is %v", name, time.Now())
	if err := selfSend(shh, []byte(payload)); err != nil {
		fmt.Printf("Failed to self message: %v.\n", err)
		os.Exit(-1)
	}
}
Esempio n. 3
0
func newkey() *ecdsa.PrivateKey {
	key, err := crypto.GenerateKey()
	if err != nil {
		panic("couldn't generate key: " + err.Error())
	}
	return key
}
Esempio n. 4
0
func TestEnvelopeIdentifiedOpenUntargeted(t *testing.T) {
	key, err := crypto.GenerateKey()
	if err != nil {
		t.Fatalf("failed to generate test identity: %v", err)
	}

	payload := []byte("hello envelope")
	envelope, err := NewMessage(payload).Wrap(DefaultPoW, Options{})
	if err != nil {
		t.Fatalf("failed to wrap message: %v", err)
	}
	opened, err := envelope.Open(key)
	switch err {
	case nil:
		t.Fatalf("envelope opened with bad key: %v", opened)

	case ecies.ErrInvalidPublicKey:
		// Ok, key mismatch but opened

	default:
		t.Fatalf("failed to open envelope: %v", err)
	}

	if opened.To != nil {
		t.Fatalf("recipient mismatch: have 0x%x, want nil", opened.To)
	}
	if bytes.Compare(opened.Payload, payload) != 0 {
		t.Fatalf("payload mismatch: have 0x%x, want 0x%x", opened.Payload, payload)
	}
}
Esempio n. 5
0
// Tests whether a message can be encrypted and decrypted using an anonymous
// sender (i.e. no signature).
func TestMessageAnonymousEncryptDecrypt(t *testing.T) {
	key, err := crypto.GenerateKey()
	if err != nil {
		t.Fatalf("failed to create recipient crypto key: %v", err)
	}
	payload := []byte("hello world")

	msg := NewMessage(payload)
	envelope, err := msg.Wrap(DefaultPoW, Options{
		To: &key.PublicKey,
	})
	if err != nil {
		t.Fatalf("failed to encrypt message: %v", err)
	}
	if msg.Flags&signatureFlag != 0 {
		t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, 0)
	}
	if len(msg.Signature) != 0 {
		t.Fatalf("signature found for anonymous message: 0x%x", msg.Signature)
	}

	out, err := envelope.Open(key)
	if err != nil {
		t.Fatalf("failed to open encrypted message: %v", err)
	}
	if !bytes.Equal(out.Payload, payload) {
		t.Error("payload mismatch: have 0x%x, want 0x%x", out.Payload, payload)
	}
}
Esempio n. 6
0
func setupTxPool() (*TxPool, *ecdsa.PrivateKey) {
	db, _ := ethdb.NewMemDatabase()
	statedb := state.New(common.Hash{}, db)

	var m event.TypeMux
	key, _ := crypto.GenerateKey()
	return NewTxPool(&m, func() *state.StateDB { return statedb }, func() *big.Int { return big.NewInt(1000000) }), key
}
Esempio n. 7
0
func init() {
	ringKeys[0] = benchRootKey
	ringAddrs[0] = benchRootAddr
	for i := 1; i < len(ringKeys); i++ {
		ringKeys[i], _ = crypto.GenerateKey()
		ringAddrs[i] = crypto.PubkeyToAddress(ringKeys[i].PublicKey)
	}
}
Esempio n. 8
0
// NewIdentity generates a new cryptographic identity for the client, and injects
// it into the known identities for message decryption.
func (self *Whisper) NewIdentity() *ecdsa.PrivateKey {
	key, err := crypto.GenerateKey()
	if err != nil {
		panic(err)
	}
	self.keys[string(crypto.FromECDSAPub(&key.PublicKey))] = key

	return key
}
Esempio n. 9
0
// Tests whether a message can be properly signed and encrypted.
func TestMessageFullCrypto(t *testing.T) {
	fromKey, err := crypto.GenerateKey()
	if err != nil {
		t.Fatalf("failed to create sender crypto key: %v", err)
	}
	toKey, err := crypto.GenerateKey()
	if err != nil {
		t.Fatalf("failed to create recipient crypto key: %v", err)
	}

	payload := []byte("hello world")
	msg := NewMessage(payload)
	envelope, err := msg.Wrap(DefaultPoW, Options{
		From: fromKey,
		To:   &toKey.PublicKey,
	})
	if err != nil {
		t.Fatalf("failed to encrypt message: %v", err)
	}
	if msg.Flags&signatureFlag != signatureFlag {
		t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, signatureFlag)
	}
	if len(msg.Signature) == 0 {
		t.Fatalf("no signature found for signed message")
	}

	out, err := envelope.Open(toKey)
	if err != nil {
		t.Fatalf("failed to open encrypted message: %v", err)
	}
	if !bytes.Equal(out.Payload, payload) {
		t.Error("payload mismatch: have 0x%x, want 0x%x", out.Payload, payload)
	}

	pubKey := out.Recover()
	if pubKey == nil {
		t.Fatalf("failed to recover public key")
	}
	p1 := elliptic.Marshal(crypto.S256(), fromKey.PublicKey.X, fromKey.PublicKey.Y)
	p2 := elliptic.Marshal(crypto.S256(), pubKey.X, pubKey.Y)
	if !bytes.Equal(p1, p2) {
		t.Fatalf("public key mismatch: have 0x%x, want 0x%x", p2, p1)
	}
}
Esempio n. 10
0
func TestSharedSecret(t *testing.T) {
	prv0, _ := crypto.GenerateKey() // = ecdsa.GenerateKey(crypto.S256(), rand.Reader)
	pub0 := &prv0.PublicKey
	prv1, _ := crypto.GenerateKey()
	pub1 := &prv1.PublicKey

	ss0, err := ecies.ImportECDSA(prv0).GenerateShared(ecies.ImportECDSAPublic(pub1), sskLen, sskLen)
	if err != nil {
		return
	}
	ss1, err := ecies.ImportECDSA(prv1).GenerateShared(ecies.ImportECDSAPublic(pub0), sskLen, sskLen)
	if err != nil {
		return
	}
	t.Logf("Secret:\n%v %x\n%v %x", len(ss0), ss0, len(ss0), ss1)
	if !bytes.Equal(ss0, ss1) {
		t.Errorf("dont match :(")
	}
}
Esempio n. 11
0
func writeKey(target string) {
	key, err := crypto.GenerateKey()
	if err != nil {
		log.Fatal("could not generate key: %v", err)
	}
	b := crypto.FromECDSA(key)
	if target == "-" {
		fmt.Println(hex.EncodeToString(b))
	} else {
		if err := ioutil.WriteFile(target, b, 0600); err != nil {
			log.Fatal("write error: ", err)
		}
	}
}
Esempio n. 12
0
func (cfg *Config) nodeKey() (*ecdsa.PrivateKey, error) {
	// use explicit key from command line args if set
	if cfg.NodeKey != nil {
		return cfg.NodeKey, nil
	}
	// use persistent key if present
	keyfile := filepath.Join(cfg.DataDir, "nodekey")
	key, err := crypto.LoadECDSA(keyfile)
	if err == nil {
		return key, nil
	}
	// no persistent key, generate and store a new one
	if key, err = crypto.GenerateKey(); err != nil {
		return nil, fmt.Errorf("could not generate server key: %v", err)
	}
	if err := crypto.SaveECDSA(keyfile, key); err != nil {
		glog.V(logger.Error).Infoln("could not persist nodekey: ", err)
	}
	return key, nil
}
Esempio n. 13
0
func TestEnvelopeAnonymousOpenTargeted(t *testing.T) {
	key, err := crypto.GenerateKey()
	if err != nil {
		t.Fatalf("failed to generate test identity: %v", err)
	}

	payload := []byte("hello envelope")
	envelope, err := NewMessage(payload).Wrap(DefaultPoW, Options{
		To: &key.PublicKey,
	})
	if err != nil {
		t.Fatalf("failed to wrap message: %v", err)
	}
	opened, err := envelope.Open(nil)
	if err != nil {
		t.Fatalf("failed to open envelope: %v", err)
	}
	if opened.To != nil {
		t.Fatalf("recipient mismatch: have 0x%x, want nil", opened.To)
	}
	if bytes.Compare(opened.Payload, payload) == 0 {
		t.Fatalf("payload match, should have been encrypted: 0x%x", opened.Payload)
	}
}
Esempio n. 14
0
func testEncHandshake(token []byte) error {
	type result struct {
		side string
		id   discover.NodeID
		err  error
	}
	var (
		prv0, _  = crypto.GenerateKey()
		prv1, _  = crypto.GenerateKey()
		fd0, fd1 = net.Pipe()
		c0, c1   = newRLPX(fd0).(*rlpx), newRLPX(fd1).(*rlpx)
		output   = make(chan result)
	)

	go func() {
		r := result{side: "initiator"}
		defer func() { output <- r }()

		dest := &discover.Node{ID: discover.PubkeyID(&prv1.PublicKey)}
		r.id, r.err = c0.doEncHandshake(prv0, dest)
		if r.err != nil {
			return
		}
		id1 := discover.PubkeyID(&prv1.PublicKey)
		if r.id != id1 {
			r.err = fmt.Errorf("remote ID mismatch: got %v, want: %v", r.id, id1)
		}
	}()
	go func() {
		r := result{side: "receiver"}
		defer func() { output <- r }()

		r.id, r.err = c1.doEncHandshake(prv1, nil)
		if r.err != nil {
			return
		}
		id0 := discover.PubkeyID(&prv0.PublicKey)
		if r.id != id0 {
			r.err = fmt.Errorf("remote ID mismatch: got %v, want: %v", r.id, id0)
		}
	}()

	// wait for results from both sides
	r1, r2 := <-output, <-output
	if r1.err != nil {
		return fmt.Errorf("%s side error: %v", r1.side, r1.err)
	}
	if r2.err != nil {
		return fmt.Errorf("%s side error: %v", r2.side, r2.err)
	}

	// compare derived secrets
	if !reflect.DeepEqual(c0.rw.egressMAC, c1.rw.ingressMAC) {
		return fmt.Errorf("egress mac mismatch:\n c0.rw: %#v\n c1.rw: %#v", c0.rw.egressMAC, c1.rw.ingressMAC)
	}
	if !reflect.DeepEqual(c0.rw.ingressMAC, c1.rw.egressMAC) {
		return fmt.Errorf("ingress mac mismatch:\n c0.rw: %#v\n c1.rw: %#v", c0.rw.ingressMAC, c1.rw.egressMAC)
	}
	if !reflect.DeepEqual(c0.rw.enc, c1.rw.enc) {
		return fmt.Errorf("enc cipher mismatch:\n c0.rw: %#v\n c1.rw: %#v", c0.rw.enc, c1.rw.enc)
	}
	if !reflect.DeepEqual(c0.rw.dec, c1.rw.dec) {
		return fmt.Errorf("dec cipher mismatch:\n c0.rw: %#v\n c1.rw: %#v", c0.rw.dec, c1.rw.dec)
	}
	return nil
}
Esempio n. 15
0
func TestProtocolHandshake(t *testing.T) {
	var (
		prv0, _ = crypto.GenerateKey()
		node0   = &discover.Node{ID: discover.PubkeyID(&prv0.PublicKey), IP: net.IP{1, 2, 3, 4}, TCP: 33}
		hs0     = &protoHandshake{Version: 3, ID: node0.ID, Caps: []Cap{{"a", 0}, {"b", 2}}}

		prv1, _ = crypto.GenerateKey()
		node1   = &discover.Node{ID: discover.PubkeyID(&prv1.PublicKey), IP: net.IP{5, 6, 7, 8}, TCP: 44}
		hs1     = &protoHandshake{Version: 3, ID: node1.ID, Caps: []Cap{{"c", 1}, {"d", 3}}}

		fd0, fd1 = net.Pipe()
		wg       sync.WaitGroup
	)

	wg.Add(2)
	go func() {
		defer wg.Done()
		rlpx := newRLPX(fd0)
		remid, err := rlpx.doEncHandshake(prv0, node1)
		if err != nil {
			t.Errorf("dial side enc handshake failed: %v", err)
			return
		}
		if remid != node1.ID {
			t.Errorf("dial side remote id mismatch: got %v, want %v", remid, node1.ID)
			return
		}

		phs, err := rlpx.doProtoHandshake(hs0)
		if err != nil {
			t.Errorf("dial side proto handshake error: %v", err)
			return
		}
		if !reflect.DeepEqual(phs, hs1) {
			t.Errorf("dial side proto handshake mismatch:\ngot: %s\nwant: %s\n", spew.Sdump(phs), spew.Sdump(hs1))
			return
		}
		rlpx.close(DiscQuitting)
	}()
	go func() {
		defer wg.Done()
		rlpx := newRLPX(fd1)
		remid, err := rlpx.doEncHandshake(prv1, nil)
		if err != nil {
			t.Errorf("listen side enc handshake failed: %v", err)
			return
		}
		if remid != node0.ID {
			t.Errorf("listen side remote id mismatch: got %v, want %v", remid, node0.ID)
			return
		}

		phs, err := rlpx.doProtoHandshake(hs1)
		if err != nil {
			t.Errorf("listen side proto handshake error: %v", err)
			return
		}
		if !reflect.DeepEqual(phs, hs0) {
			t.Errorf("listen side proto handshake mismatch:\ngot: %s\nwant: %s\n", spew.Sdump(phs), spew.Sdump(hs0))
			return
		}

		if err := ExpectMsg(rlpx, discMsg, []DiscReason{DiscQuitting}); err != nil {
			t.Errorf("error receiving disconnect: %v", err)
		}
	}()
	wg.Wait()
}