当前位置: 首页>>代码示例>>Golang>>正文


Golang rand.Read函数代码示例

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


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

示例1: TestEthash

func TestEthash(t *testing.T) {
	seedHash := make([]byte, 32)
	_, err := rand.Read(seedHash)
	if err != nil {
		panic(err)
	}

	e := New(seedHash)

	miningHash := make([]byte, 32)
	if _, err := rand.Read(miningHash); err != nil {
		panic(err)
	}
	diff := big.NewInt(10000)
	log.Println("difficulty", diff)

	nonce := uint64(0)

	ghash_full := e.full(nonce, miningHash)
	log.Println("ethhash full (on nonce):", ghash_full, nonce)

	ghash_light := e.light(nonce, miningHash)
	log.Println("ethash light (on nonce)", ghash_light, nonce)

	if bytes.Compare(ghash_full, ghash_light) != 0 {
		t.Fatal(fmt.Sprintf("full: %x, light: %x", ghash_full, ghash_light))
	}
}
开发者ID:anush3070,项目名称:c-ethash,代码行数:28,代码来源:ethash_test.go

示例2: TestExportKeysByID

func TestExportKeysByID(t *testing.T) {
	setUp(t)
	tempBaseDir, err := ioutil.TempDir("", "notary-test-")
	require.NoError(t, err)
	defer os.RemoveAll(tempBaseDir)
	output, err := ioutil.TempFile("", "notary-test-import-")
	require.NoError(t, err)
	defer os.RemoveAll(output.Name())
	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			return v, nil
		},
	}
	k.outFile = output.Name()
	err = output.Close() // close so export can open
	require.NoError(t, err)
	k.exportKeyIDs = []string{"one", "three"}

	b := &pem.Block{}
	b.Bytes = make([]byte, 1000)
	rand.Read(b.Bytes)

	b2 := &pem.Block{}
	b2.Bytes = make([]byte, 1000)
	rand.Read(b2.Bytes)

	c := &pem.Block{}
	c.Bytes = make([]byte, 1000)
	rand.Read(c.Bytes)

	bBytes := pem.EncodeToMemory(b)
	b2Bytes := pem.EncodeToMemory(b2)
	cBytes := pem.EncodeToMemory(c)

	fileStore, err := store.NewPrivateKeyFileStorage(tempBaseDir, notary.KeyExtension)
	require.NoError(t, err)
	err = fileStore.Set("one", bBytes)
	require.NoError(t, err)
	err = fileStore.Set("two", b2Bytes)
	require.NoError(t, err)
	err = fileStore.Set("three", cBytes)
	require.NoError(t, err)

	err = k.exportKeys(&cobra.Command{}, nil)
	require.NoError(t, err)

	outRes, err := ioutil.ReadFile(k.outFile)
	require.NoError(t, err)

	block, rest := pem.Decode(outRes)
	require.Equal(t, b.Bytes, block.Bytes)
	require.Equal(t, "one", block.Headers["path"])

	block, rest = pem.Decode(rest)
	require.Equal(t, c.Bytes, block.Bytes)
	require.Equal(t, "three", block.Headers["path"])
	require.Len(t, rest, 0)
}
开发者ID:jfrazelle,项目名称:notary,代码行数:60,代码来源:keys_test.go

示例3: commandCreateUser

func commandCreateUser() cli.Command {
	return cli.Command{
		Name:        "createuser",
		Usage:       "createuser",
		Description: "Create a new user account. The email address and password are prompted to enter.",
		Action: func(c *cli.Context) {
			failOnError(c, checkZeroArgument(c))
			key := make([]byte, 32)
			salt := make([]byte, 10)
			if _, err := rand.Read(key); err != nil {
				failOnError(c, err)
			}
			if _, err := rand.Read(salt); err != nil {
				failOnError(c, err)
			}
			fmt.Print("Email: ")
			var email string
			fmt.Scanf("%s\n", &email)
			fmt.Print("Password: ")
			password := string(gopass.GetPasswd())
			u, err := generateUser(email, password, key, salt)
			failOnError(c, err)
			failOnError(c, client.UploadUsers([]*gitkit.User{u}, "HMAC_SHA1", key, nil))
			u, err = getUserByIdentifier(u.Email)
			failOnError(c, err)
			fmt.Println(">> user created:")
			printUser(u)
		},
	}
}
开发者ID:crossbreeze,项目名称:identity-toolkit-go,代码行数:30,代码来源:gitkitcli.go

示例4: TestInit

func TestInit(t *testing.T) {
	AccessKeyId = DefaultAccessKeyId
	if os.Getenv("ACCESS_KEY_ID") != "" {
		AccessKeyId = os.Getenv("ACCESS_KEY_ID")
	}

	SecretAccessKey = DefaultSecretAccessKey
	if os.Getenv("SECRET_ACCESS_KEY") != "" {
		SecretAccessKey = os.Getenv("SECRET_ACCESS_KEY")
	}

	DebugHost = DefaultDebugHost
	if os.Getenv("DEBUG_HOST") != "" {
		DebugHost = os.Getenv("DEBUG_HOST")
	}

	fileSize := 256
	content := make([]byte, fileSize)
	rand.Read(content)
	err := ioutil.WriteFile(TestObjectName, content, 0644)
	if err != nil {
		t.Errorf("Write TestFile failed.")
	}

	fileSize = 1024*1024*5 + 1
	content = make([]byte, fileSize)
	rand.Read(content)
	err = ioutil.WriteFile(TestObjectName1, content, 0644)
	if err != nil {
		t.Errorf("Write TestFile failed.")
	}

}
开发者ID:WilliamKyle,项目名称:baidubce,代码行数:33,代码来源:bos_client_test.go

示例5: TestDeterministicWalletType2

func TestDeterministicWalletType2(t *testing.T) {
	secret := make([]byte, 32)
	rand.Read(secret)

	private_key := make([]byte, 32)
	rand.Read(private_key)

	public_key := PublicFromPrivate(private_key, true)
	for i := 0; i < 50; i++ {
		private_key = DeriveNextPrivate(private_key, secret)
		if private_key == nil {
			t.Fatal("DeriveNextPrivate fail")
		}

		public_key = DeriveNextPublic(public_key, secret)
		if public_key == nil {
			t.Fatal("DeriveNextPublic fail")
		}

		// verify the public key matching the private key
		pub2 := PublicFromPrivate(private_key, true)
		if !bytes.Equal(public_key, pub2) {
			t.Error(i, "public key mismatch", hex.EncodeToString(pub2), hex.EncodeToString(public_key))
		}

		// make sure that you can sign and verify with it
		if e := VerifyKeyPair(private_key, public_key); e != nil {
			t.Error(i, "verify key failed", e.Error())
		}
	}
}
开发者ID:vipwzw,项目名称:gocoin,代码行数:31,代码来源:wallet_test.go

示例6: benchmarkEncrypt

func benchmarkEncrypt(
	b *testing.B,
	size int) {
	var err error

	// Generate the appropriate amount of random data.
	plaintext := make([]byte, size)
	_, err = rand.Read(plaintext)
	if err != nil {
		b.Fatalf("rand.Read: %v", err)
	}

	// Create a random key.
	const keyLen = 32
	key := make([]byte, keyLen)

	_, err = rand.Read(key)
	if err != nil {
		b.Fatalf("rand.Read: %v", err)
	}

	// Repeatedly encrypt.
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_, err = siv.Encrypt(nil, key, plaintext, nil)
		if err != nil {
			b.Fatalf("Encrypt: %v", err)
		}
	}

	b.SetBytes(int64(size))
}
开发者ID:itiserik,项目名称:crypto,代码行数:32,代码来源:encrypt_test.go

示例7: TestExportKeysByID

func TestExportKeysByID(t *testing.T) {
	s := NewTestExportStore()

	b := &pem.Block{}
	b.Bytes = make([]byte, 1000)
	rand.Read(b.Bytes)

	c := &pem.Block{}
	c.Bytes = make([]byte, 1000)
	rand.Read(c.Bytes)

	bBytes := pem.EncodeToMemory(b)
	cBytes := pem.EncodeToMemory(c)

	s.data["ankh"] = bBytes
	s.data["morpork/identifier"] = cBytes

	buf := bytes.NewBuffer(nil)

	err := ExportKeysByID(buf, s, []string{"identifier"})
	require.NoError(t, err)

	out, err := ioutil.ReadAll(buf)
	require.NoError(t, err)

	cFinal, rest := pem.Decode(out)
	require.Equal(t, c.Bytes, cFinal.Bytes)
	require.Equal(t, "morpork/identifier", cFinal.Headers["path"])
	require.Len(t, rest, 0)
}
开发者ID:jfrazelle,项目名称:notary,代码行数:30,代码来源:keys_test.go

示例8: passgenHandler

func passgenHandler(w http.ResponseWriter, r *http.Request) {
	body := r.FormValue("body")

	if body == "" {
		renderTemplate(w, "html", "PASS GENERATOR")
		return
	}
	rand_bytes := make([]byte, len(body))
	rand_bytes2 := make([]byte, len(body))
	rand.Read(rand_bytes)
	rand.Read(rand_bytes2)

	reduced_ascii := make([]byte, 94)
	for i := 0; i < 94; i++ {
		var tmp byte
		tmp = byte('!' + i)
		reduced_ascii[i] = tmp
	}
	pass := make([]byte, len(body))
	for i := 0; i < len(body); i++ {
		tmp := rand_bytes[i] % 94
		if tmp == 0 {
			tmp = 94
		}
		pass[i] = reduced_ascii[(body[i]+rand_bytes2[i])%tmp]
	}
	templates.Execute(w, &Page{Title: "PASS GENERATOR", R: string(pass)})
}
开发者ID:yunyun13,项目名称:tools,代码行数:28,代码来源:tools.go

示例9: raw_passgenHandler

func raw_passgenHandler(w http.ResponseWriter, r *http.Request) {
	renderTemplate(w, "raw", "raw")
	body := r.FormValue("body")

	if body == "" {
		return
	}

	rand_bytes := make([]byte, len(body))
	rand.Read(rand_bytes)
	rand_bytes2 := make([]byte, len(body))
	rand.Read(rand_bytes2)

	reduced_ascii := make([]byte, 94)
	for i := 0; i < 94; i++ {
		var tmp byte
		tmp = byte('!' + i)
		reduced_ascii[i] = tmp
	}

	pass := make([]byte, len(body))
	for i := 0; i < len(body); i++ {
		tmp := rand_bytes[i] % 94
		if tmp == 0 {
			tmp = 94
		}
		pass[i] = reduced_ascii[(body[i]+rand_bytes2[i])%tmp]

	}
	fmt.Fprint(w, string(pass))
}
开发者ID:yunyun13,项目名称:tools,代码行数:31,代码来源:tools.go

示例10: AesEncrypt

// encrypts the given plaintext with the given key.
// It returns a base64-encoded string consisting of the nonce + aad + encryptedBytes
// Each piece is a single space delimited.
func AesEncrypt(secretKey []byte, plaintext []byte) (string, error) {
	aesCipher, err := aes.NewCipher(secretKey)
	if err != nil {
		log.Fatal("Error creating AES cipher" + err.Error())
	}

	gcm, err := cipher.NewGCM(aesCipher)
	if err != nil {
		log.Fatal("Error creating GCM cipher" + err.Error())
	}

	nonce := make([]byte, gcm.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		log.Fatal("Error generating AES nonce" + err.Error())
	}

	aad := make([]byte, 12)
	if _, err := rand.Read(aad); err != nil {
		log.Fatal("Error generating AES AAD" + err.Error())
	}

	ciphertext := gcm.Seal(nil, nonce, plaintext, aad)

	var buffer bytes.Buffer
	buffer.WriteString(base64.StdEncoding.EncodeToString(nonce))
	buffer.WriteString(aesDelimiter)
	buffer.WriteString(base64.StdEncoding.EncodeToString(aad))
	buffer.WriteString(aesDelimiter)
	buffer.WriteString(base64.StdEncoding.EncodeToString(ciphertext))

	return buffer.String(), nil
}
开发者ID:gravieinc,项目名称:aws-crypto-tools-go,代码行数:35,代码来源:aes.go

示例11: encryptDESCBC

func encryptDESCBC(content []byte) ([]byte, *encryptedContentInfo, error) {
	// Create DES key & CBC IV
	key := make([]byte, 8)
	iv := make([]byte, des.BlockSize)
	_, err := rand.Read(key)
	if err != nil {
		return nil, nil, err
	}
	_, err = rand.Read(iv)
	if err != nil {
		return nil, nil, err
	}

	// Encrypt padded content
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, nil, err
	}
	mode := cipher.NewCBCEncrypter(block, iv)
	plaintext, err := pad(content, mode.BlockSize())
	cyphertext := make([]byte, len(plaintext))
	mode.CryptBlocks(cyphertext, plaintext)

	// Prepare ASN.1 Encrypted Content Info
	eci := encryptedContentInfo{
		ContentType: oidData,
		ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{
			Algorithm:  oidEncryptionAlgorithmDESCBC,
			Parameters: asn1.RawValue{Tag: 4, Bytes: iv},
		},
		EncryptedContent: marshalEncryptedContent(cyphertext),
	}

	return key, &eci, nil
}
开发者ID:quixoten,项目名称:vault,代码行数:35,代码来源:pkcs7.go

示例12: ExportEncrypted

// ExportEncrypted encrypts the current state of the key manager with the
// specified password and returns it. The salt used as input to PBKDF2 as well
// as nonce for input to secretbox are randomly generated. The actual key used
// for encryption is derived from the salt and the passphrase using PBKDF2.
func (mgr *Manager) ExportEncrypted(pass []byte) ([]byte, error) {
	plain, err := mgr.ExportPlaintext()
	if err != nil {
		return nil, err
	}

	var nonce [nonceSize]byte
	_, err = rand.Read(nonce[:])
	if err != nil {
		return nil, err
	}

	salt := make([]byte, saltLength)
	_, err = rand.Read(salt)
	if err != nil {
		return nil, err
	}

	ret := make([]byte, nonceSize+saltLength)
	copy(ret[:nonceSize], nonce[:])
	copy(ret[nonceSize:], salt)
	ret = secretbox.Seal(ret, plain, &nonce, deriveKey(pass, salt))

	return ret, nil
}
开发者ID:DanielKrawisz,项目名称:bmagent,代码行数:29,代码来源:manager.go

示例13: BenchmarkVerify

func BenchmarkVerify(b *testing.B) {
	var entropy [32]byte
	_, err := rand.Read(entropy[:])
	if err != nil {
		panic(err)
	}
	sk, pk := GenerateKey(entropy)

	b.ResetTimer()
	message := make([]byte, 64)
	for i := 0; i < b.N; i++ {
		b.StopTimer()
		_, err := rand.Read(message)
		if err != nil {
			panic(err)
		}

		sig := Sign(sk, message)
		b.StartTimer()
		ver := Verify(pk, message, sig)
		if !ver {
			panic(err)
		}
	}
}
开发者ID:NebulousLabs,项目名称:ed25519,代码行数:25,代码来源:ed25519_test.go

示例14: newSession

func newSession(sessionRateLimit, globalRateLimit *ratelimit.Bucket) *session {
	serverkey := make([]byte, 32)
	_, err := rand.Read(serverkey)
	if err != nil {
		return nil
	}

	clientkey := make([]byte, 32)
	_, err = rand.Read(clientkey)
	if err != nil {
		return nil
	}

	ses := &session{
		serverkey: serverkey,
		clientkey: clientkey,
		rateLimit: makeRateLimitFunc(sessionRateLimit, globalRateLimit),
		conns:     make(chan net.Conn),
	}

	if debug {
		log.Println("New session", ses)
	}

	sessionMut.Lock()
	sessions[string(ses.serverkey)] = ses
	sessions[string(ses.clientkey)] = ses
	sessionMut.Unlock()

	return ses
}
开发者ID:rumpelsepp,项目名称:relaysrv,代码行数:31,代码来源:session.go

示例15: replyWithChallenge

func replyWithChallenge(w http.ResponseWriter, login string) {

	var defaultSaltRaw [32]byte
	rand.Read(defaultSaltRaw[:])
	salt := base64.StdEncoding.EncodeToString(defaultSaltRaw[:])

	u, ok := users[login]
	if ok {
		salt = u.Salt
	}

	var token [32]byte
	rand.Read(token[:])
	sig := ed25519.Sign(signingKey, token[:])

	signedTokenRaw := make([]byte, len(token)+len(sig))
	copy(signedTokenRaw, token[:])
	copy(signedTokenRaw[len(token):], sig[:])
	signedToken := base64.StdEncoding.EncodeToString(signedTokenRaw)

	err := json.NewEncoder(w).Encode(challenge{signedToken, salt})
	if err != nil {
		log.Println(err)
		http.Error(w, "Error with your request", http.StatusBadRequest)
	}
}
开发者ID:rakoo,项目名称:challengeauth,代码行数:26,代码来源:main.go


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