• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang box.GenerateKey函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中golang.org/x/crypto/nacl/box.GenerateKey函数的典型用法代码示例。如果您正苦于以下问题:Golang GenerateKey函数的具体用法?Golang GenerateKey怎么用?Golang GenerateKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了GenerateKey函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestReadWriter2Read

func TestReadWriter2Read(t *testing.T) {
	pubAlice, privAlice, errA := box.GenerateKey(rand.Reader)
	pubBob, privBob, errB := box.GenerateKey(rand.Reader)
	if errA != nil || errB != nil {
		t.Fatal(errA, errB)
	}

	r, w := io.Pipe()
	secureW := NewSecureWriter(w, privAlice, pubBob)
	secureR := NewSecureReader(r, privBob, pubAlice)

	// Encrypt hello world
	go func() {
		fmt.Fprintf(secureW, "h")
		fmt.Fprintf(secureW, "ello world\n")
		w.Close()
	}()

	// Decrypt message
	buf := make([]byte, len("hello world\n"))
	if _, err := io.ReadFull(secureR, buf[:len("hello")]); err != nil {
		t.Fatal(err)
	}
	if _, err := io.ReadFull(secureR, buf[len("hello"):]); err != nil {
		t.Fatal(err)
	}

	// Make sure we have hello world back
	if res := string(buf); res != "hello world\n" {
		t.Fatalf("Unexpected result: %s != %s", res, "hello world")
	}
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:32,代码来源:secureconn_test.go


示例2: TestEncryptDecrypt

func TestEncryptDecrypt(t *testing.T) {
	peerPubKey, _, err := box.GenerateKey(rand.Reader)
	if err != nil {
		t.Errorf("failed key gen %s", err)
		return
	}

	_, ownPrivKey, err := box.GenerateKey(rand.Reader)
	if err != nil {
		t.Errorf("failed key gen %s", err)
		return
	}

	var sharedKey [32]byte
	box.Precompute(&sharedKey, peerPubKey, ownPrivKey)

	msg := []byte("|wtf am i doing|")

	cipher, err := node.Encrypt(msg, &sharedKey)

	if err != nil {
		t.Errorf("failed to encrypt %s", err)
		return
	}

	plain, err := node.Decrypt(cipher, &sharedKey)
	if err != nil {
		t.Errorf("failed to decrypt: %s", err)
		return
	}

	if !bytes.Equal(msg, plain) {
		t.Errorf("expected %s doesn't equal actual %s", string(msg), string(plain))
	}
}
开发者ID:qq40660,项目名称:bluntly,代码行数:35,代码来源:node_test.go


示例3: runHandshake

func runHandshake(t *testing.T, haveClient bool) (c1 *Conn, c2 *Conn) {
	ch1, ch2 := make(chan struct{}), make(chan struct{})
	p1, p2 := net.Pipe()
	pk1, sk1, err1 := box.GenerateKey(rand.Reader)
	pk2, sk2, err2 := box.GenerateKey(rand.Reader)
	if err1 != nil || err2 != nil {
		t.Fatal("key generation failed")
	}
	var pk2_1, pk1_2, expectedPK *[32]byte
	if haveClient {
		expectedPK = pk2
	}
	go func() { c1, pk2_1, err1 = Handshake(p1, pk1, sk1, expectedPK, 1<<12); close(ch1) }()
	go func() { c2, pk1_2, err2 = Handshake(p2, pk2, sk2, nil, 1<<12); defer close(ch2) }()
	<-ch1
	<-ch2
	if err1 != nil {
		t.Fatal(err1)
	}
	if !bytes.Equal(pk2_1[:], pk2[:]) {
		t.Error("1 observed wrong pk")
	}
	if err2 != nil {
		t.Fatal(err2)
	}
	if !bytes.Equal(pk1_2[:], pk1[:]) {
		t.Error("2 observed wrong pk")
	}
	return c1, c2
}
开发者ID:andres-erbsen,项目名称:chatterbox,代码行数:30,代码来源:transport_test.go


示例4: TestKeyUploadDownload

func TestKeyUploadDownload(t *testing.T) {
	dir, err := ioutil.TempDir("", "testdb")
	handleError(err, t)

	defer os.RemoveAll(dir)
	db, err := leveldb.OpenFile(dir, nil)
	handleError(err, t)

	defer db.Close()

	server, conn, inBuf, outBuf, pkp := setUpServerTest(db, t)
	defer conn.Close()

	createAccount(conn, inBuf, outBuf, t)

	pk1, _, err := box.GenerateKey(rand.Reader)
	handleError(err, t)

	pk2, _, err := box.GenerateKey(rand.Reader)
	handleError(err, t)

	keyList := make([][]byte, 0, 64) //TODO: Make this a reasonable size
	keyList = append(keyList, pk1[:])
	keyList = append(keyList, pk2[:])

	uploadKeys(conn, inBuf, outBuf, t, keyList)
	numKeys := getNumKeys(conn, inBuf, outBuf, t, pkp)

	if numKeys != 2 {
		t.Error(fmt.Sprintf("Returned %d keys instead of 2.", numKeys))
	}
	server.StopServer()
}
开发者ID:andres-erbsen,项目名称:chatterbox,代码行数:33,代码来源:server_test.go


示例5: TestReadWriterPing

func TestReadWriterPing(t *testing.T) {
	pub1, priv1, _ := box.GenerateKey(rand.Reader)
	pub2, priv2, _ := box.GenerateKey(rand.Reader)

	r, w := io.Pipe()
	secureR := NewSecureReader(r, priv1, pub2)
	secureW := NewSecureWriter(w, priv2, pub1)

	// Encrypt hello world
	go func() {
		fmt.Fprintf(secureW, "hello world\n")
		w.Close()
	}()

	// Decrypt message
	buf := make([]byte, 1024)
	n, err := secureR.Read(buf)
	if err != nil && err != io.EOF {
		t.Fatal(err)
	}
	buf = buf[:n]

	// Make sure we have hello world back
	if res := string(buf); res != "hello world\n" {
		t.Fatalf("Unexpected result: %s != %s", res, "hello world")
	}
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:27,代码来源:main_test.go


示例6: TestReadWriterEOF

func TestReadWriterEOF(t *testing.T) {
	pubAlice, privAlice, errA := box.GenerateKey(rand.Reader)
	pubBob, privBob, errB := box.GenerateKey(rand.Reader)
	if errA != nil || errB != nil {
		t.Fatal(errA, errB)
	}

	r, w := io.Pipe()
	secureW := NewSecureWriter(w, privAlice, pubBob)
	secureR := NewSecureReader(r, privBob, pubAlice)

	// Encrypt hello world
	go func() {
		fmt.Fprintf(secureW, "hello world\n")
		w.Close()
	}()

	// Decrypt message
	buf := make([]byte, len("hello world\n"))
	if _, err := io.ReadFull(secureR, buf); err != nil {
		t.Fatal(err)
	}

	if n, err := secureR.Read(buf); err != io.EOF || n != 0 {
		t.Fatal(err)
	}
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:27,代码来源:secureconn_test.go


示例7: generateKeypair

func generateKeypair(sk *[kexPrvSize]byte, pk *[kexPubSize]byte) bool {
	if sk == nil || pk == nil {
		return false
	}

	pub, priv, err := box.GenerateKey(prng)
	if err != nil {
		return false
	}

	copy(sk[:], priv[:])
	zero(priv[:], 0)
	copy(pk[:], pub[:])

	pub, priv, err = box.GenerateKey(prng)
	if err != nil {
		zero(sk[:], 0)
		return false
	}

	copy(sk[32:], priv[:])
	zero(priv[:], 0)
	copy(pk[32:], pub[:])
	return true
}
开发者ID:jmptrader,项目名称:go-schannel,代码行数:25,代码来源:schannel.go


示例8: TestAsymmetricalDecryption

func TestAsymmetricalDecryption(t *testing.T) {
	cpub, cpriv, _ := box.GenerateKey(rand.Reader)
	spub, spriv, _ := box.GenerateKey(rand.Reader)

	r, w := io.Pipe()
	secureW := NewSecureWriter(w, cpriv, spub)
	secureR := NewSecureReader(r, spriv, cpub)

	go func() {
		fmt.Fprintf(secureW, "hello world\n")
		w.Close()
	}()

	// Decrypt message
	buf := make([]byte, 1024)
	n, err := secureR.Read(buf)
	if err != nil {
		t.Fatal(err)
	}
	buf = buf[:n]

	if res := string(buf); res != "hello world\n" {
		t.Fatalf("Unexpected result: %s != %s", res, "hello world")
	}
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:25,代码来源:main_test.go


示例9: BenchmarkSeal

func BenchmarkSeal(b *testing.B) {
	_, myPrivate, _ := box.GenerateKey(rand.Reader)
	theirPublic, _, _ := box.GenerateKey(rand.Reader)
	message := make([]byte, 256)
	nonce := new([24]byte)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		box.Seal(nil, message, nonce, theirPublic, myPrivate)
	}
}
开发者ID:ak-67,项目名称:vuvuzela,代码行数:10,代码来源:box_test.go


示例10: BenchmarkSealAfterPrecomputation

func BenchmarkSealAfterPrecomputation(b *testing.B) {
	_, myPrivate, _ := box.GenerateKey(rand.Reader)
	theirPublic, _, _ := box.GenerateKey(rand.Reader)
	message := make([]byte, 256)
	nonce := new([24]byte)
	sharedKey := new([32]byte)
	box.Precompute(sharedKey, theirPublic, myPrivate)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		box.SealAfterPrecomputation(nil, message, nonce, sharedKey)
	}
}
开发者ID:ak-67,项目名称:vuvuzela,代码行数:12,代码来源:box_test.go


示例11: TestGenerateKeys

func TestGenerateKeys(t *testing.T) {
	var err error

	alicePub, alicePriv, err = box.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}

	bobPub, bobPriv, err = box.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}
}
开发者ID:jmptrader,项目名称:gocrypto,代码行数:13,代码来源:session_test.go


示例12: TestReplayAttack

// TestReplayAttack tries to perform an attack where messages from Alice to Bob
// are sent back to Alice by an active MitM attacker. This would mean that
// parties have no way to distinguish the other, like with even/odd sequence
// numbers for high/low public keys.
func TestReplayAttack(t *testing.T) {
	pubA, privA, err := box.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	pubB, privB, err := box.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	buf := &bytes.Buffer{}

	// Instantiate Alice's writer
	wr := NewSecureWriter(buf, privA, pubB)

	// Write and capture two messages
	if _, err := wr.Write([]byte("message1")); err != nil {
		t.Fatal(err)
	}
	message1 := buf.String()
	buf.Reset()
	if _, err := wr.Write([]byte("message2")); err != nil {
		t.Fatal(err)
	}
	message2 := buf.String()

	t.Log("\n" + hex.Dump([]byte(message1)))
	t.Log("\n" + hex.Dump([]byte(message2)))

	// Check that Bob's reader can read the messages correctly
	buf = bytes.NewBufferString(message1 + message2)
	rd := NewSecureReader(buf, privB, pubA)
	res, err := ioutil.ReadAll(rd)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(res, []byte("message1message2")) {
		t.Fatalf("Bob read the wrong message: %s", res)
	}

	// Check that Alice's reader refuses to read the messages
	buf = bytes.NewBufferString(message2 + message1)
	rd = NewSecureReader(buf, privA, pubB)
	res, err = ioutil.ReadAll(rd)
	if err == nil {
		t.Fatalf("Alice read the messages she sent: %s", res)
	}
	t.Logf("The replayed messages error is: %v", err)
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:54,代码来源:attacks_test.go


示例13: TestAsymmetricalDecryptionWithBox

func TestAsymmetricalDecryptionWithBox(t *testing.T) {
	cpub, cpriv, _ := box.GenerateKey(rand.Reader)
	spub, spriv, _ := box.GenerateKey(rand.Reader)

	nonce := &[24]byte{'a'}
	message := []byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\n'}

	encrypted := box.Seal([]byte{}, message, nonce, spub, cpriv)
	buf, _ := box.Open([]byte{}, encrypted, nonce, cpub, spriv)

	if res := string(buf); res != "hello world\n" {
		t.Fatalf("Unexpected result: %s != %s", res, "hello world")
	}
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:14,代码来源:main_test.go


示例14: TestGetNumberOfKeys

func TestGetNumberOfKeys(t *testing.T) {
	dir, err := ioutil.TempDir("", "testdb")
	handleError(err, t)

	defer os.RemoveAll(dir)
	db, err := leveldb.OpenFile(dir, nil)
	handleError(err, t)

	defer db.Close()

	server, conn, inBuf, outBuf, pkp := setUpServerTest(db, t)
	defer conn.Close()

	createAccount(conn, inBuf, outBuf, t)

	pk1, _, err := box.GenerateKey(rand.Reader)
	handleError(err, t)

	pk2, _, err := box.GenerateKey(rand.Reader)
	handleError(err, t)

	// NOTE: the keys are note signed here, but they will be in real use
	keyList := make([][]byte, 0, 64) //TODO: Make this a reasonable size
	keyList = append(keyList, pk1[:])
	keyList = append(keyList, pk2[:])

	uploadKeys(conn, inBuf, outBuf, t, keyList)
	newKey1 := getKey(conn, inBuf, outBuf, t, pkp)

	if newKey1 == nil {
		t.Error("No keys in server")
	}
	if !(containsByteSlice(keyList, newKey1)) {
		t.Error("Non-uploaded key returned")
	}

	newKey2 := getKey(conn, inBuf, outBuf, t, pkp)
	if newKey2 == nil {
		t.Fatal("No keys in server")
	}
	if !(containsByteSlice(keyList, newKey2)) {
		t.Error("Non-uploaded key returned")
	}
	if bytes.Equal(newKey1, newKey2) {
		t.Error("Key not deleted from server")
	}

	server.StopServer()
}
开发者ID:andres-erbsen,项目名称:chatterbox,代码行数:49,代码来源:server_test.go


示例15: Seal

func Seal(out, message []byte, peersPublicKey *[32]byte) []byte {
	otk_pub, otk_priv, err := box.GenerateKey(rand.Reader)
	if err != nil {
		panic(err)
	}
	return box.Seal(append(out, otk_pub[:]...), message, &n, peersPublicKey, otk_priv)
}
开发者ID:AdamColton,项目名称:anonBox,代码行数:7,代码来源:anonBox.go


示例16: NewSecureConn

// NewSecureConn performs the key exchange over the passed net.Conn and then
// returns a SecureConn wrapping it.
func NewSecureConn(co net.Conn) (*SecureConn, error) {
	c := &SecureConn{co: co}

	// Generate a local keypair
	pub, priv, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return nil, err
	}
	c.priv = priv

	// Send the public key to the other party
	if _, err := c.co.Write(pub[:]); err != nil {
		return nil, err
	}

	// Receive the other party's public key
	var key [32]byte
	if _, err := io.ReadFull(c.co, key[:]); err != nil {
		return nil, err
	}
	c.pub = &key

	// Initialize the SecureReader and SecureWriter
	c.wr = NewSecureWriter(c.co, c.priv, c.pub)
	c.rd = NewSecureReader(c.co, c.priv, c.pub)

	return c, nil
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:30,代码来源:secureconn.go


示例17: swapKeys

// swapKeys generates a public/private key pair and swaps the public key with
// a corresponding call to swapKeys over the given ReadWriter.
//
// swapKeys returns the private key generated locally and the public key of it's
// counterpart.
func swapKeys(rw io.ReadWriter) (priv, peer *[32]byte, err error) {
	// Always return nil for the keys if there is an error
	defer func() {
		if err != nil {
			priv, peer = nil, nil
		}
	}()
	pub, priv, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return
	}

	// Write our public key
	werr := make(chan error)
	go func() {
		_, err := rw.Write(pub[:])
		werr <- err
	}()
	defer func() {
		if err == nil {
			err = <-werr
		}
	}()

	// Read their public key
	peer = new([32]byte)
	_, err = io.ReadFull(rw, peer[:])
	return
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:34,代码来源:main.go


示例18: Serve

// Serve starts a secure echo server on the given listener. Sending an empty
// message will quit the server.
func Serve(l net.Listener) error {

	for {
		conn, err := l.Accept()
		if err != nil {
			return err
		}
		defer conn.Close()

		pub, priv, err := box.GenerateKey(rand.Reader)
		if err != nil {
			return err
		}

		peer, err := exchangeKeys(conn, pub)
		if err != nil {
			return err
		}
		secure := NewSecureConn(conn, priv, peer)

		// If nothing is copied then the server will end. This allows the client to
		// send an empty message to kill the server.
		if n, err := io.Copy(secure, secure); n == 0 {
			if err != nil {
				return err
			}
			return fmt.Errorf("Server ending.")
		}
	}
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:32,代码来源:server.go


示例19: Serve

// Serve starts a secure echo server on the given listener.
func Serve(l net.Listener) error {
	defer l.Close()
	pub, priv, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return err
	}

	for {
		rawConn, err := l.Accept()
		if err != nil {
			return err
		}
		conn := &Conn{rawConn: rawConn, pub: pub, priv: priv}
		go func(c *Conn) {
			defer c.Close()
			buf := make([]byte, 1024*32)
			n, err := c.Read(buf)
			if err != nil {
				fmt.Println(err)
			}
			got := string(buf[:n])
			log.Print(got)
			// echo the message
			n, err = c.Write([]byte(got))
			if err != nil {
				fmt.Println(err)
			}
		}(conn)
	}

}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:32,代码来源:main.go


示例20: Dial

// Dial generates a private/public key pair,
// connects to the server, perform the handshake
// and return a reader/writer.
func Dial(addr string) (io.ReadWriteCloser, error) {
	pub, priv, err := box.GenerateKey(rand.Reader)
	if nil != err {
		return nil, err
	}

	conn, err := net.Dial("tcp", addr)
	if nil != err {
		return nil, err
	}

	// Send client public key
	pubSlice := pub[:]
	_, err = conn.Write(pubSlice)
	if nil != err {
		return nil, err
	}

	// Get server public key
	var serverKey [32]byte
	serverKeySlice := serverKey[:]
	_, err = conn.Read(serverKeySlice)
	if nil != err {
		return nil, err
	}

	rwc := readWriteCloser{
		NewSecureReader(conn, priv, &serverKey),
		NewSecureWriter(conn, priv, &serverKey),
		conn,
	}
	return rwc, nil
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:36,代码来源:main.go



注:本文中的golang.org/x/crypto/nacl/box.GenerateKey函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang box.Open函数代码示例发布时间:2022-05-28
下一篇:
Golang hkdf.New函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap