Source File
util.go
Belonging Package
crypto/rand
// Copyright 2011 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package randimport ()// Prime returns a number of the given bit length that is prime with high probability.// Prime will return error for any error returned by rand.Read or if bits < 2.//// Since Go 1.26, a secure source of random bytes is always used, and the Reader is// ignored unless GODEBUG=cryptocustomrand=1 is set. This setting will be removed// in a future Go release. Instead, use [testing/cryptotest.SetGlobalRandom].func ( io.Reader, int) (*big.Int, error) {if fips140only.Enforced() {return nil, errors.New("crypto/rand: use of Prime is not allowed in FIPS 140-only mode")}if < 2 {return nil, errors.New("crypto/rand: prime size must be at least 2-bit")}= rand.CustomReader():= uint( % 8)if == 0 {= 8}:= make([]byte, (+7)/8):= new(big.Int)for {if , := io.ReadFull(, ); != nil {return nil,}// Clear bits in the first byte to make sure the candidate has a size <= bits.[0] &= uint8(int(1<<) - 1)// Don't let the value be too small, i.e, set the most significant two bits.// Setting the top two bits, rather than just the top bit,// means that when two of these values are multiplied together,// the result isn't ever one bit short.if >= 2 {[0] |= 3 << ( - 2)} else {// Here b==1, because b cannot be zero.[0] |= 1if len() > 1 {[1] |= 0x80}}// Make the value odd since an even number this large certainly isn't prime.[len()-1] |= 1.SetBytes()if .ProbablyPrime(20) {return , nil}}}// Int returns a uniform random value in [0, max). It panics if max <= 0, and// returns an error if rand.Read returns one.func ( io.Reader, *big.Int) ( *big.Int, error) {if .Sign() <= 0 {panic("crypto/rand: argument to Int is <= 0")}= new(big.Int).Sub(, .SetUint64(1))// bitLen is the maximum bit length needed to encode a value < max.:= .BitLen()if == 0 {// the only valid result is 0return}// k is the maximum byte length needed to encode a value < max.:= ( + 7) / 8// b is the number of bits in the most significant byte of max-1.:= uint( % 8)if == 0 {= 8}:= make([]byte, )for {_, = io.ReadFull(, )if != nil {return nil,}// Clear bits in the first byte to increase the probability// that the candidate is < max.[0] &= uint8(int(1<<) - 1).SetBytes()if .Cmp() < 0 {return}}}
The pages are generated with Golds v0.8.4. (GOOS=linux GOARCH=amd64)