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


Golang rand.Int函数代码示例

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


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

示例1: RandomString

func RandomString(n int) string {

	randInt, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
	if err != nil {
		panic(err)
	}

	buf := make([]byte, n)

	for n, cache, remaining := n-1, randInt.Int64(), charMax; n >= 0; {
		if remaining == 0 {

			randInt, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
			if err != nil {
				panic(err)
			}

			cache, remaining = randInt.Int64(), charMax
		}
		if idx := int(cache & charMask); idx < len(charBytes) {
			buf[n] = charBytes[idx]
			n--
		}
		cache >>= charBits
		remaining--
	}

	return string(buf)
}
开发者ID:FlamesRunner,项目名称:webauth-ssh-go,代码行数:29,代码来源:main.go

示例2: TestTripartiteDiffieHellman

func TestTripartiteDiffieHellman(t *testing.T) {
	a, _ := rand.Int(rand.Reader, Order)
	b, _ := rand.Int(rand.Reader, Order)
	c, _ := rand.Int(rand.Reader, Order)

	pa := new(G1).ScalarBaseMult(a)
	qa := new(G2).ScalarBaseMult(a)
	pb := new(G1).ScalarBaseMult(b)
	qb := new(G2).ScalarBaseMult(b)
	pc := new(G1).ScalarBaseMult(c)
	qc := new(G2).ScalarBaseMult(c)

	k1 := Pair(pb, qc)
	k1.ScalarMult(k1, a)
	k1Bytes := k1.Marshal()

	k2 := Pair(pc, qa)
	k2.ScalarMult(k2, b)
	k2Bytes := k2.Marshal()

	k3 := Pair(pa, qb)
	k3.ScalarMult(k3, c)
	k3Bytes := k3.Marshal()

	if !bytes.Equal(k1Bytes, k2Bytes) || !bytes.Equal(k2Bytes, k3Bytes) {
		t.Errorf("keys didn't agree")
	}
}
开发者ID:Bobberino,项目名称:musings,代码行数:28,代码来源:bn256_test.go

示例3: GeneratePrivateKey

func (self *DHGroup) GeneratePrivateKey(randReader io.Reader) (key *DHKey, err error) {
	if randReader == nil {
		randReader = rand.Reader
	}

	// x should be in (0, p).
	// alternative approach:
	// x, err := big.Add(rand.Int(randReader, big.Sub(p, big.NewInt(1))), big.NewInt(1))
	//
	// However, since x is highly unlikely to be zero if p is big enough,
	// we would rather use an iterative approach below,
	// which is more efficient in terms of exptected running time.
	x, err := rand.Int(randReader, self.p)
	if err != nil {
		return
	}

	zero := big.NewInt(0)
	for x.Cmp(zero) == 0 {
		x, err = rand.Int(randReader, self.p)
		if err != nil {
			return
		}
	}
	key = new(DHKey)
	key.x = x

	// y = g ^ x mod p
	key.y = new(big.Int).Exp(self.g, x, self.p)
	key.group = self
	return
}
开发者ID:gfphoenix,项目名称:dhkx,代码行数:32,代码来源:dhgroup.go

示例4: ExamplePair

func ExamplePair() {
	// This implements the tripartite Diffie-Hellman algorithm from "A One
	// Round Protocol for Tripartite Diffie-Hellman", A. Joux.
	// http://www.springerlink.com/content/cddc57yyva0hburb/fulltext.pdf

	// Each of three parties, a, b and c, generate a private value.
	a, _ := rand.Int(rand.Reader, Order)
	b, _ := rand.Int(rand.Reader, Order)
	c, _ := rand.Int(rand.Reader, Order)

	// Then each party calculates g₁ and g₂ times their private value.
	pa := new(G1).ScalarBaseMult(a)
	qa := new(G2).ScalarBaseMult(a)

	pb := new(G1).ScalarBaseMult(b)
	qb := new(G2).ScalarBaseMult(b)

	pc := new(G1).ScalarBaseMult(c)
	qc := new(G2).ScalarBaseMult(c)

	// Now each party exchanges its public values with the other two and
	// all parties can calculate the shared key.
	k1 := Pair(pb, qc)
	k1.ScalarMult(k1, a)

	k2 := Pair(pc, qa)
	k2.ScalarMult(k2, b)

	k3 := Pair(pa, qb)
	k3.ScalarMult(k3, c)

	// k1, k2 and k3 will all be equal.
}
开发者ID:Bobberino,项目名称:musings,代码行数:33,代码来源:example_test.go

示例5: TestConcurrentSameData

// TestConcurrentSameData tests between 100 and 200 concurrent writes of
// identical data to the API.
func (s *TestSuite) TestConcurrentSameData(c *C) {
	b, err := rand.Int(rand.Reader, big.NewInt(int64(100)))
	c.Assert(err, IsNil)
	count := 100 + int(b.Int64())
	wg := sync.WaitGroup{}
	wg.Add(count)
	bi, err := rand.Int(rand.Reader, big.NewInt(int64(int(MiB)-1)))
	c.Assert(err, IsNil)
	size := int(bi.Int64()) + 1
	value := make([]byte, size)
	_, err = rand.Read(value)
	c.Assert(err, IsNil)
	writer := func() {
		resp, err := http.Post(s.url, "", bytes.NewBuffer(value))
		defer resp.Body.Close()
		c.Assert(err, IsNil)
		if resp.StatusCode != 200 && resp.StatusCode != 201 {
			c.Fatal("Expected status 200 or 201, but got", resp.StatusCode)
		}
		// Done
		wg.Done()
	}
	for i := 0; i < count; i++ {
		go writer()
	}
	wg.Wait()
}
开发者ID:jmcvetta,项目名称:blocker,代码行数:29,代码来源:main_test.go

示例6: VoteOne

func VoteOne(c elliptic.Curve, px *big.Int, py *big.Int) *Checkbox {
	var err error
	h := new(Checkbox)
	h.s, err = rand.Int(rand.Reader, c.Params().N)
	if err != nil {
		panic("this shouldn't happen")
	}
	h.ax, h.ay = c.ScalarBaseMult(h.s.Bytes())
	tx, ty := c.ScalarMult(px, py, h.s.Bytes())
	h.bx, h.by = c.Add(tx, ty, c.Params().Gx, c.Params().Gy)
	//TODO: refactor: lots of similar logic here but parts very
	//c2, r2 fake, c1 r1 genuine
	//Form the faked challenge
	h.c2, err = rand.Int(rand.Reader, c.Params().N)
	if err != nil {
		panic("this shouldn't happen")
	}
	h.r2, err = rand.Int(rand.Reader, c.Params().N)
	if err != nil {
		panic("this shouldn't happen")
	}
	//Compute the commitments v3, v4 as the verifier will
	v3x, v3y := doublescalarmult(c, c.Params().Gx, c.Params().Gy, h.r2.Bytes(),
		h.ax, h.ay, h.c2.Bytes())
	v4x, v4y := doublescalarmult(c, px, py, h.r2.Bytes(),
		h.bx, h.by, h.c2.Bytes())
	//Commit to other side
	s1, err := rand.Int(rand.Reader, c.Params().N)
	if err != nil {
		panic("something deeply wrong")
	}
	v1x, v1y := c.ScalarBaseMult(s1.Bytes())
	v2x, v2y := c.ScalarMult(px, py, s1.Bytes())
	//Compute the total challenge
	var entries [6][]byte
	entries[0] = elliptic.Marshal(c, h.ax, h.ay)
	entries[1] = elliptic.Marshal(c, h.bx, h.by)
	entries[2] = elliptic.Marshal(c, v1x, v1y)
	entries[3] = elliptic.Marshal(c, v2x, v2y)
	entries[4] = elliptic.Marshal(c, v3x, v3y)
	entries[5] = elliptic.Marshal(c, v4x, v4y)
	challenge := sha256.Sum256(bytes.Join(entries[:], []byte{}))
	ctot := big.NewInt(0)
	ctot.SetBytes(challenge[:])
	ctot.Mod(ctot, c.Params().N)
	h.c1 = big.NewInt(0)
	h.c1.Sub(ctot, h.c2)
	h.c1.Mod(h.c1, c.Params().N)
	//r=s1-c1*h.s
	t := big.NewInt(0)
	t.Mul(h.c1, h.s)
	t.Mod(t, c.Params().N)
	t.Sub(s1, t)
	t.Mod(t, c.Params().N)
	h.r1 = t
	return h
}
开发者ID:wbl,项目名称:mozvote,代码行数:57,代码来源:checkbox.go

示例7: testSingleProposerUpdateKey

/**
 * Tests that the key is correctly updated in each node's storage system.
 */
func testSingleProposerUpdateKey(doneChan chan bool) {
	key := "b"

	// send first proposal
	randint, _ := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	rand.Seed(randint.Int64())
	value := rand.Uint32()
	if _, ok := pt.cliMap[1]; !ok {
		LOGE.Println("FAIL: missing node 1")
		doneChan <- false
		return
	}

	pnum, err := pt.GetNextProposalNumber(key, 1)
	reply, err := pt.Propose(key, value, pnum.N, 1)

	if err != nil {
		printFailErr("Propose", err)
		doneChan <- false
		return
	}

	// send second proposal
	randint, _ = crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	rand.Seed(randint.Int64())
	value = rand.Uint32()

	pnum2, err := pt.GetNextProposalNumber(key, 1)
	// the proposal numbers should be monotonically increasing
	if pnum.N >= pnum2.N {
		LOGE.Println("FAIL: newer proposal number is less than or equal to older proposal number")
		doneChan <- false
		return
	}

	reply, err = pt.Propose(key, value, pnum2.N, 1)
	if err != nil {
		printFailErr("Propose", err)
		doneChan <- false
		return
	}

	if !checkProposeReply(reply, key, value) {
		doneChan <- false
		return
	}

	if !checkGetValueAll(key, value) {
		doneChan <- false
		return
	}

	doneChan <- true
}
开发者ID:thuhujin,项目名称:Paxos,代码行数:57,代码来源:paxostest.go

示例8: getNewIds

func getNewIds() (dlId, cookieName string) {
	dlId = ""
	for {
		_, ex := currentBounces[dlId]
		if !ex && (len(dlId) > 0) {
			break
		}

		r, _ := rand.Int(rand.Reader, big.NewInt(maxRand))
		dlId = fmt.Sprintf("%s", hex.EncodeToString(r.Bytes()))
	}
	r, _ := rand.Int(rand.Reader, big.NewInt(maxRand))
	cookieName = fmt.Sprintf("Dl-%s", hex.EncodeToString(r.Bytes()))
	return
}
开发者ID:fsufitch,项目名称:fwooshfile,代码行数:15,代码来源:arbiter.go

示例9: TempFile

// Generates and opens a temporary file with a defined prefix and suffix
// This is the same api as ioutil.TempFile accept it accepts a suffix
//  TODO: see if this is too slow
func TempFile(dir, prefix string, suffix string) (f *os.File, err error) {
	if dir == "" {
		dir = os.TempDir()
	}

	// The maximum size of random file count
	// TODO: see if we can do this at package scope somehow
	var maxRand *big.Int = big.NewInt(0)
	maxRand.SetString("FFFFFFFFFFFFFFFF", 16)

	var randNum *big.Int

	for i := 0; i < 10000; i++ {
		// Generate random part of the path name
		randNum, err = rand.Int(rand.Reader, maxRand)

		if err != nil {
			return
		}

		// Transform to an int
		randString := hex.EncodeToString(randNum.Bytes())

		// Attempt to open file and fail if it already exists
		name := filepath.Join(dir, prefix+randString+suffix)
		f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
		if os.IsExist(err) {
			continue
		}
		break
	}
	return
}
开发者ID:jlisee,项目名称:cbd,代码行数:36,代码来源:util.go

示例10: Begin

func (s *Sessions) Begin(userid string, displayName, photoUrl *string) (
	*http.Cookie, error) {
	n, err := rand.Int(rand.Reader, big.NewInt(1<<62))
	if err != nil {
		return nil, err
	}
	sid := n.String()

	var uv userView
	uv.Id = userid
	if displayName != nil {
		uv.Name = *displayName
	} else {
		uv.Name = ""
	}
	if photoUrl != nil {
		uv.PhotoUrl = *photoUrl
	} else {
		uv.PhotoUrl = "/images/unknown_avatar.png"
	}

	s.lock.Lock()
	s.sidToUser[sid] = uv
	s.lock.Unlock()

	cookie := http.Cookie{
		Name:  sidCookie,
		Value: sid,
	}
	return &cookie, nil
}
开发者ID:tstranex,项目名称:carpcomm,代码行数:31,代码来源:sessions.go

示例11: Encrypt

// Encrypt encrypts the given message to the given public key. The result is a
// pair of integers. Errors can result from reading random, or because msg is
// too large to be encrypted to the public key.
func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err error) {
	pLen := (pub.P.BitLen() + 7) / 8
	if len(msg) > pLen-11 {
		err = errors.New("elgamal: message too long")
		return
	}

	// EM = 0x02 || PS || 0x00 || M
	em := make([]byte, pLen-1)
	em[0] = 2
	ps, mm := em[1:len(em)-len(msg)-1], em[len(em)-len(msg):]
	err = nonZeroRandomBytes(ps, random)
	if err != nil {
		return
	}
	em[len(em)-len(msg)-1] = 0
	copy(mm, msg)

	m := new(big.Int).SetBytes(em)

	k, err := rand.Int(random, pub.P)
	if err != nil {
		return
	}

	c1 = new(big.Int).Exp(pub.G, k, pub.P)
	s := new(big.Int).Exp(pub.Y, k, pub.P)
	c2 = s.Mul(s, m)
	c2.Mod(c2, pub.P)

	return
}
开发者ID:aubonbeurre,项目名称:gcc,代码行数:35,代码来源:elgamal.go

示例12: generateRandomName

func generateRandomName() string {
	n, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
	if err != nil {
		log.Fatalf("Unable to generate random container name: %v\n", err)
	}
	return fmt.Sprintf("image-inspector-%016x", n)
}
开发者ID:pombredanne,项目名称:image-inspector,代码行数:7,代码来源:image-inspector.go

示例13: generate

func (s realSource) generate() *big.Int {
	randInt, err := rand.Int(rand.Reader, maxBigInt)
	if err != nil {
		panic(err)
	}
	return randInt
}
开发者ID:andrewrothstein,项目名称:boulder,代码行数:7,代码来源:mailer.go

示例14: Handler

func Handler(rw http.ResponseWriter, req *http.Request) {

	requestLogId, err := rand.Int(rand.Reader, big.NewInt(999999))
	if err != nil {
		glog.Errorf("Failed to get a random number. Err:%s", err)
	}

	context.Set(req, RequestLogIdKey, fmt.Sprintf("%06d", requestLogId))
	if glog.V(2) {
		glog.Infof("Session request tagged %06d started with url: %s", requestLogId, req.URL)
	}

	checkCredentials(req)

	router := mux.NewRouter()
	router.HandleFunc("/session/users", doUser).Methods("PUT")
	router.HandleFunc("/session/user/{SysUserId}", doUser).Methods("POST")
	router.HandleFunc("/session/user/{EmailAddr}/token/{Token}", verifyEmail).Methods("GET")
	router.HandleFunc("/session/login", doLogin).Methods("POST")
	router.HandleFunc("/session/login", getLogin).Methods("GET")
	router.HandleFunc("/session/reset/{EmailAddr}", getResetToken).Methods("GET")
	router.HandleFunc("/session/reset/{EmailAddr}/token/{Token}", useResetToken).Methods("GET")
	router.HandleFunc("/session/logout", doLogout).Methods("POST")

	router.ServeHTTP(rw, req)
}
开发者ID:Grant-Murray,项目名称:session,代码行数:26,代码来源:session.go

示例15: generateServerKeyExchange

func (ka *dheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
	var q *big.Int
	if p := config.Bugs.DHGroupPrime; p != nil {
		ka.p = p
		ka.g = big.NewInt(2)
		q = p
	} else {
		// 2048-bit MODP Group with 256-bit Prime Order Subgroup (RFC
		// 5114, Section 2.3)
		ka.p, _ = new(big.Int).SetString("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597", 16)
		ka.g, _ = new(big.Int).SetString("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659", 16)
		q, _ = new(big.Int).SetString("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3", 16)
	}

	var err error
	ka.xOurs, err = rand.Int(config.rand(), q)
	if err != nil {
		return nil, err
	}
	yOurs := new(big.Int).Exp(ka.g, ka.xOurs, ka.p)

	// http://tools.ietf.org/html/rfc5246#section-7.4.3
	pBytes := ka.p.Bytes()
	gBytes := ka.g.Bytes()
	yBytes := yOurs.Bytes()
	serverDHParams := make([]byte, 0, 2+len(pBytes)+2+len(gBytes)+2+len(yBytes))
	serverDHParams = append(serverDHParams, byte(len(pBytes)>>8), byte(len(pBytes)))
	serverDHParams = append(serverDHParams, pBytes...)
	serverDHParams = append(serverDHParams, byte(len(gBytes)>>8), byte(len(gBytes)))
	serverDHParams = append(serverDHParams, gBytes...)
	serverDHParams = append(serverDHParams, byte(len(yBytes)>>8), byte(len(yBytes)))
	serverDHParams = append(serverDHParams, yBytes...)

	return ka.auth.signParameters(config, cert, clientHello, hello, serverDHParams)
}
开发者ID:caiolima,项目名称:webkit,代码行数:35,代码来源:key_agreement.go


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