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


Golang Int.BitLen方法代码示例

本文整理汇总了Golang中math/big.Int.BitLen方法的典型用法代码示例。如果您正苦于以下问题:Golang Int.BitLen方法的具体用法?Golang Int.BitLen怎么用?Golang Int.BitLen使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在math/big.Int的用法示例。


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

示例1: New

// Creates a new STS session, ready to initiate or accept key exchanges. The group/generator pair defines the
// cyclic group on which STS will operate. cipher and bits are used during the authentication token's symmetric
// encryption, whilst hash is needed during RSA signing.
func New(random io.Reader, group, generator *big.Int, cipher func([]byte) (cipher.Block, error),
	bits int, hash crypto.Hash) (*Session, error) {
	// Generate a random secret exponent
	expbits := group.BitLen()
	secret := make([]byte, (expbits+7)/8)
	n, err := io.ReadFull(random, secret)
	if n != len(secret) || err != nil {
		return nil, err
	}

	// Clear top bits if non-power was requested
	clear := uint(expbits % 8)
	if clear == 0 {
		clear = 8
	}
	secret[0] &= uint8(int(1<<clear) - 1)

	exp := new(big.Int).SetBytes(secret)
	ses := new(Session)
	ses.group = group
	ses.generator = generator
	ses.exponent = exp
	ses.hash = hash
	ses.crypter = cipher
	ses.keybits = bits

	return ses, nil
}
开发者ID:ibmendoza,项目名称:project-iris,代码行数:31,代码来源:sts.go

示例2: main

func main() {
	c := exec.Command("ft", "1000000", "2", `17/91 78/85 19/51 23/38
        29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1`)
	c.Stderr = os.Stderr
	r, err := c.StdoutPipe()
	if err != nil {
		log.Fatal(err)
	}
	if err = c.Start(); err != nil {
		log.Fatal(err)
	}
	var n big.Int
	for primes := 0; primes < 20; {
		if _, err = fmt.Fscan(r, &n); err != nil {
			log.Fatal(err)
		}
		l := n.BitLen() - 1
		n.SetBit(&n, l, 0)
		if n.BitLen() == 0 && l > 1 {
			fmt.Printf("%d ", l)
			primes++
		}
	}
	fmt.Println()
}
开发者ID:travis1230,项目名称:RosettaCodeData,代码行数:25,代码来源:fractran-2.go

示例3: HideEncode

// HideEncode a Int such that it appears indistinguishable
// from a HideLen()-byte string chosen uniformly at random,
// assuming the Int contains a uniform integer modulo M.
// For a Int this always succeeds and returns non-nil.
func (i *Int) HideEncode(rand cipher.Stream) []byte {

	// Lengh of required encoding
	hidelen := i.HideLen()

	// Bit-position of the most-significant bit of the modular integer
	// in the most-significant byte of its encoding.
	highbit := uint((i.M.BitLen() - 1) & 7)

	var enc big.Int
	for {
		// Pick a random multiplier of a suitable bit-length.
		var b [1]byte
		rand.XORKeyStream(b[:], b[:])
		mult := int64(b[0] >> highbit)

		// Multiply, and see if we end up with
		// a Int of the proper byte-length.
		// Reroll if we get a result larger than HideLen(),
		// to ensure uniformity of the resulting encoding.
		enc.SetInt64(mult).Mul(&i.V, &enc)
		if enc.BitLen() <= hidelen*8 {
			break
		}
	}

	b := enc.Bytes() // may be shorter than l
	if ofs := hidelen - len(b); ofs != 0 {
		b = append(make([]byte, ofs), b...)
	}
	return b
}
开发者ID:Liamsi,项目名称:crypto,代码行数:36,代码来源:int.go

示例4: SmallPrimeTest

// SmallPrimeTest determins if N is a small prime
// or divisible by a small prime.
func SmallPrimeTest(N *big.Int) int {
	if N.Sign() <= 0 {
		panic("SmallPrimeTest for positive integers only")
	}
	if N.BitLen() <= 10 {
		n := uint16(N.Uint64())
		i := sort.Search(len(primes10), func(i int) bool {
			return primes10[i] >= n
		})
		if i >= len(primes10) || n != primes10[i] {
			return IsComposite
		}
		return IsPrime
	}
	// quick test for N even
	if N.Bits()[0]&1 == 0 {
		return IsComposite
	}
	// compare several small gcds for efficency
	z := new(big.Int)
	if z.GCD(nil, nil, N, prodPrimes10A).Cmp(one) == 1 {
		return IsComposite
	}
	if z.GCD(nil, nil, N, prodPrimes10B).Cmp(one) == 1 {
		return IsComposite
	}
	if z.GCD(nil, nil, N, prodPrimes10C).Cmp(one) == 1 {
		return IsComposite
	}
	if z.GCD(nil, nil, N, prodPrimes10D).Cmp(one) == 1 {
		return IsComposite
	}
	return Undetermined
}
开发者ID:tscholl2,项目名称:prime,代码行数:36,代码来源:tests.go

示例5: ComputeKey

// ComputeKey computes the session key given the value of A.
func (ss *ServerSession) ComputeKey(A []byte) ([]byte, error) {
	err := ss.setA(A)
	if err != nil {
		return nil, err
	}

	// S = (Av^u) mod N
	S := new(big.Int).Exp(ss._v, ss._u, ss.SRP.Group.Prime)
	S.Mul(ss._A, S).Mod(S, ss.SRP.Group.Prime)

	// Reject A*v^u == 0,1 (mod N)
	one := big.NewInt(1)
	if S.Cmp(one) <= 0 {
		return nil, fmt.Errorf("Av^u) mod N <= 0")
	}

	// Reject A*v^u == -1 (mod N)
	t1 := new(big.Int).Add(S, one)
	if t1.BitLen() == 0 {
		return nil, fmt.Errorf("Av^u) mod N == -1")
	}

	// S = (S ^ b) mod N              (computes session key)
	S.Exp(S, ss._b, ss.SRP.Group.Prime)
	// K = H(S)
	ss.key = quickHash(ss.SRP.HashFunc, S.Bytes())
	return ss.key, nil
}
开发者ID:tjbx,项目名称:X10Bridge,代码行数:29,代码来源:srp.go

示例6: findBucketLoop

func (this *Bucket) findBucketLoop(nodeInt *big.Int, targetLevel int) *Bucket {
	//---------------------------------
	//  深度为0,则找到最小深度的子节点
	//---------------------------------
	if this.level == 0 || this.level == targetLevel {
		return this
	}
	//---------------------------------
	//  没有子节点了
	//---------------------------------
	if this.left == nil && this.right == nil {
		return this
	}
	//---------------------------------
	//  截取最高位
	//---------------------------------
	tempInt := big.NewInt(1)
	tempInt = tempInt.Lsh(tempInt, uint(this.level-1))
	findInt := new(big.Int).AndNot(nodeInt, tempInt)
	//判断最高位是1还是0
	if nodeInt.BitLen() == this.level {
		//最高位是1
		left := this.left.findBucketLoop(findInt, targetLevel)
		return left
	} else {
		//最高位是0
		right := this.right.findBucketLoop(findInt, targetLevel)
		return right
	}
}
开发者ID:cokeboL,项目名称:mandela,代码行数:30,代码来源:kademlia.go

示例7: FindRecentNode

//找到某个节点最近的节点
//@nodeId  节点id的10进制字符串
func (this *Bucket) FindRecentNode(nodeId string) Node {
	findInt, _ := new(big.Int).SetString(nodeId, 10)
	rootInt, _ := new(big.Int).SetString(this.Bucket[0].NodeId, 10)
	targetLevelInt := new(big.Int).Xor(rootInt, findInt)

	bucket := this.findBucketLoop(findInt, targetLevelInt.BitLen())
	//这个k桶为空
	if len(bucket.Bucket) == 0 {
		//找子节点中的k桶
		childBucket := bucket.findRecentChildBucketLoop()
		if childBucket != nil {
			bucket = childBucket
		} else {
			bucket = bucket.findRecentParentBucketLoop()
		}
	}

	for _, node := range bucket.Bucket {
		if node.NodeId == nodeId {
			return node
		}
	}
	//如果是父节点k桶
	if bucket.Bucket[0].NodeId == this.GetRootId() {
		return Node{}
	}
	return bucket.Bucket[0]
}
开发者ID:cokeboL,项目名称:mandela,代码行数:30,代码来源:kademlia.go

示例8: ISqrt

// ISqrt returns the greatest number x such that x^2 <= n. n must be
// non-negative.
//
// See https://www.akalin.com/computing-isqrt for an analysis.
func ISqrt(n *big.Int) *big.Int {
	s := n.Sign()
	if s < 0 {
		panic("negative radicand")
	}
	if s == 0 {
		return &big.Int{}
	}

	// x = 2^ceil(Bits(n)/2)
	var x big.Int
	x.Lsh(big.NewInt(1), (uint(n.BitLen())+1)/2)
	for {
		// y = floor((x + floor(n/x))/2)
		var y big.Int
		y.Div(n, &x)
		y.Add(&y, &x)
		y.Rsh(&y, 1)

		if y.Cmp(&x) >= 0 {
			return &x
		}
		x = y
	}
}
开发者ID:akalin,项目名称:iroot,代码行数:29,代码来源:isqrt.go

示例9: randomNumber

// randomNumber returns a uniform random value in [0, max).
func randomNumber(rand io.Reader, max *big.Int) (n *big.Int, err error) {
	k := (max.BitLen() + 7) / 8

	// r is the number of bits in the used in the most significant byte of
	// max.
	r := uint(max.BitLen() % 8)
	if r == 0 {
		r = 8
	}

	bytes := make([]byte, k)
	n = new(big.Int)

	for {
		_, err = io.ReadFull(rand, bytes)
		if err != nil {
			return
		}

		// Clear bits in the first byte to increase the probability
		// that the candidate is < max.
		bytes[0] &= uint8(int(1<<r) - 1)

		n.SetBytes(bytes)
		if n.Cmp(max) < 0 {
			return
		}
	}
}
开发者ID:zaker,项目名称:EcDSA--EcDH-in-Go,代码行数:30,代码来源:eccdsa.go

示例10: setBignum

func setBignum(rv reflect.Value, x *big.Int) error {
	switch rv.Kind() {
	case reflect.Ptr:
		return setBignum(reflect.Indirect(rv), x)
	case reflect.Interface:
		rv.Set(reflect.ValueOf(*x))
		return nil
	case reflect.Int32:
		if x.BitLen() < 32 {
			rv.SetInt(x.Int64())
			return nil
		} else {
			return fmt.Errorf("int too big for int32 target")
		}
	case reflect.Int, reflect.Int64:
		if x.BitLen() < 64 {
			rv.SetInt(x.Int64())
			return nil
		} else {
			return fmt.Errorf("int too big for int64 target")
		}
	default:
		return fmt.Errorf("cannot assign bignum into Kind=%s Type=%s %#v", rv.Kind().String(), rv.Type().String(), rv)
	}
}
开发者ID:jbenet,项目名称:go-cbor-incomplete,代码行数:25,代码来源:cbor.go

示例11: Int

// Int returns a uniform random value in [0, max). It panics if max <= 0.
func Int(rand io.Reader, max *big.Int) (n *big.Int, err error) {
	if max.Sign() <= 0 {
		panic("crypto/rand: argument to Int is <= 0")
	}
	k := (max.BitLen() + 7) / 8

	// Jeffrey hack
	return big.NewInt(1), nil

	// b is the number of bits in the most significant byte of max.
	b := uint(max.BitLen() % 8)
	if b == 0 {
		b = 8
	}

	bytes := make([]byte, k)
	n = new(big.Int)

	for {
		_, err = io.ReadFull(rand, bytes)
		if err != nil {
			return nil, err
		}

		// Clear bits in the first byte to increase the probability
		// that the candidate is < max.
		bytes[0] &= uint8(int(1<<b) - 1)

		n.SetBytes(bytes)
		if n.Cmp(max) < 0 {
			return
		}
	}
}
开发者ID:rachtsingh,项目名称:gogojuice,代码行数:35,代码来源:util.go

示例12: keyedPRFBig

/*
KeyedPRF is a psuedo random function. It hashes the input, pads it to
the correct output length, and then encrypts it with AES. Finally it
checks that the result is within the desired range. If it is it returns
 the value as a long integer, if it isn't, it increments a nonce in the
input and recalculates until it finds an integer in the given range
*/
func keyedPRFBig(key []byte, r *big.Int, x int) (*big.Int, error) {
	aesBlockEncrypter, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, make([]byte, aes.BlockSize))
	hash := sha256.New()
	var num big.Int
	result := make([]byte, r.BitLen()>>3)
	for nonce := 0; ; nonce++ {
		hash.Reset()
		hash.Write([]byte(strconv.Itoa(x + nonce)))
		h := hash.Sum(nil)
		if r.BitLen() > 32*8 {
			len := 32 - uint((r.BitLen()+7)>>3)
			h = append(h, make([]byte, len)...)
		}
		if r.BitLen() < 32*8 {
			len := uint((r.BitLen() + 7) >> 3)
			h = h[:len]
		}
		aesEncrypter.XORKeyStream(result, h)
		num.SetBytes(result)
		if num.Cmp(r) < 0 {
			break
		}
	}
	return &num, nil
}
开发者ID:utamaro,项目名称:go-heartbeat,代码行数:36,代码来源:swizzle.go

示例13: polyPowMod

// polyPowMod computes ``f**n`` in ``GF(p)[x]/(g)`` using repeated squaring.
// Given polynomials ``f`` and ``g`` in ``GF(p)[x]`` and a non-negative
// integer ``n``, efficiently computes ``f**n (mod g)`` i.e. the remainder
// of ``f**n`` from division by ``g``, using the repeated squaring algorithm.
// This function was ported from sympy.polys.galoistools.
func polyPowMod(f *Poly, n *big.Int, g *Poly) (h *Poly, err error) {
	zero := big.NewInt(int64(0))
	one := big.NewInt(int64(1))
	n = big.NewInt(int64(0)).Set(n)
	if n.BitLen() < 3 {
		// Small values of n not useful for recon
		err = powModSmallN
		return
	}
	h = NewPoly(Zi(f.p, 1))
	for {
		if n.Bit(0) > 0 {
			h = NewPoly().Mul(h, f)
			h, err = PolyMod(h, g)
			if err != nil {
				return
			}
			n.Sub(n, one)
		}
		n.Rsh(n, 1)
		if n.Cmp(zero) == 0 {
			break
		}
		f = NewPoly().Mul(f, f)
		f, err = PolyMod(f, g)
		if err != nil {
			return
		}
	}
	return
}
开发者ID:pruthvirajsinh,项目名称:symflux,代码行数:36,代码来源:decode.go

示例14: NewPaillierPrivateKey

// NewPaillierPrivateKey generates a new Paillier private key (key pair).
//
// The key used in the Paillier crypto system consists of four integer
// values. The public key has two parameters; the private key has three
// parameters (one parameter is shared between the keys). As in RSA it
// starts with two random primes 'p' and 'q'; the public key parameter
// are computed as:
//
//   n := p * q
//   g := random number from interval [0,n^2[
//
// The private key parameters are computed as:
//
//   n := p * q
//   l := lcm (p-1,q-1)
//   u := (((g^l mod n^2)-1)/n) ^-1 mod n
//
// N.B. The division by n is integer based and rounds toward zero!
func NewPaillierPrivateKey(bits int) (key *PaillierPrivateKey, err error) {

	// generate primes 'p' and 'q' and their factor 'n'
	// repeat until the requested factor bitsize is reached
	var p, q, n *big.Int
	for {
		bitsP := (bits - 5) / 2
		bitsQ := bits - bitsP

		p, err = rand.Prime(rand.Reader, bitsP)
		if err != nil {
			return nil, err
		}
		q, err = rand.Prime(rand.Reader, bitsQ)
		if err != nil {
			return nil, err
		}

		n = new(big.Int).Mul(p, q)
		if n.BitLen() == bits {
			break
		}
	}

	// initialize variables
	one := big.NewInt(1)
	n2 := new(big.Int).Mul(n, n)

	// compute public key parameter 'g' (generator)
	g, err := rand.Int(rand.Reader, n2)
	if err != nil {
		return nil, err
	}

	// compute private key parameters
	p1 := new(big.Int).Sub(p, one)
	q1 := new(big.Int).Sub(q, one)
	l := new(big.Int).Mul(q1, p1)
	l.Div(l, new(big.Int).GCD(nil, nil, p1, q1))

	a := new(big.Int).Exp(g, l, n2)
	a.Sub(a, one)
	a.Div(a, n)
	u := new(big.Int).ModInverse(a, n)

	// return key pair
	pubkey := &PaillierPublicKey{
		N: n,
		G: g,
	}
	prvkey := &PaillierPrivateKey{
		PaillierPublicKey: pubkey,
		L:                 l,
		U:                 u,
		P:                 p,
		Q:                 q,
	}
	return prvkey, nil
}
开发者ID:bfix,项目名称:gospel,代码行数:77,代码来源:paillier.go

示例15: makeSubtree

func makeSubtree(maskIncl, maskExcl *big.Int, charTab CharTable,
	taxa []string) tree.Edge {
	// fmt.Printf("makeSubtree\n.incl=%b\n.excl=%b\n", maskIncl, maskExcl)

	if maskIncl.BitLen() == 0 {
		panic("Empty mask")
	}
	setBit1 := findSetBit(maskIncl, 0)
	setBit2 := findSetBit(maskIncl, setBit1+1)
	if setBit2 < 0 {
		e := tree.Edge{Node: &tree.Node{Label: taxa[setBit1]}}
		return e
	}

	setBit3 := findSetBit(maskIncl, setBit2+1)
	if setBit3 < 0 {
		f := tree.Edge{Node: &tree.Node{Label: taxa[setBit1]}}
		g := tree.Edge{Node: &tree.Node{Label: taxa[setBit2]}}
		e := tree.Edge{Node: &tree.Node{Children: []tree.Edge{f, g}}}
		return e
	}

	for _, a := range charTab {
		b := &big.Int{}
		b.And(a, maskIncl)
		b.AndNot(b, maskExcl)
		if numSetBits(b) == 1 {
			in := &big.Int{}
			in.AndNot(maskIncl, b)
			out := &big.Int{}
			out.Or(maskExcl, b)
			f := makeSubtree(in, out, charTab, taxa)
			i := b.BitLen() - 1
			g := tree.Edge{Node: &tree.Node{Label: taxa[i]}}
			e := tree.Edge{Node: &tree.Node{Children: []tree.Edge{f, g}}}
			return e
		}
	}

	i, j := findComplements(charTab, maskIncl, maskExcl)
	if i < 0 || j < 0 {
		panic("No complements found")
	}

	n := &tree.Node{}
	s := i + j
	for _, k := range []int{i, j} {
		in := &big.Int{}
		in.And(maskIncl, charTab[k])
		notIn := &big.Int{}
		notIn.Not(in)
		out := &big.Int{}
		out.And(maskIncl, charTab[s-k])
		out.Or(out, maskExcl)
		t := makeSubtree(in, out, charTab, taxa)
		n.Children = append(n.Children, t)
	}
	return tree.Edge{Node: n}
}
开发者ID:nkitchen,项目名称:rosalind,代码行数:59,代码来源:chbp.go


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