Exemple #1
1
// 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
}
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()
}
Exemple #3
0
// 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
}
Exemple #4
0
// 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
}
Exemple #5
0
// 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
}
Exemple #6
0
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
	}
}
Exemple #7
0
//找到某个节点最近的节点
//@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]
}
Exemple #8
0
// 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
	}
}
Exemple #9
0
// 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
		}
	}
}
Exemple #10
0
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)
	}
}
Exemple #11
0
// 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
		}
	}
}
Exemple #12
0
/*
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
}
Exemple #13
0
// 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
}
Exemple #14
0
// 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
}
Exemple #15
0
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}
}
Exemple #16
0
func findSetBit(s *big.Int, start int) int {
	for i := start; i < s.BitLen(); i++ {
		if s.Bit(i) == 1 {
			return i
		}
	}
	return -1
}
Exemple #17
0
func bigIlog10(x *big.Int) int {
	// Should be accurate up to as high as we can possibly report.
	r := int(((int64(x.BitLen()) + 1) * 0x268826A1) >> 31)
	if BigAbsCmp(*x, pow.BigTen(int64(r))) < 0 {
		return r
	}
	return r + 1
}
Exemple #18
0
// compute the position of the leading one of a bit vector
func rank(hv *big.Int) int {
	for i := 0; i < hv.BitLen(); i++ {
		if hv.Bit(i) > 0 {
			return i + 1
		}
	}
	return MAX_LEN
}
Exemple #19
0
func calcDegree(coeffs *big.Int) uint {
	deg := coeffs.BitLen() - 1
	if deg < 0 {
		// zero polynomial is degree 0.
		deg = 0
	}
	return uint(deg)
}
Exemple #20
0
func ScanLeftInt(x *big.Int) int {
	for k := 0; k < x.BitLen(); k += 1 {
		if x.Bit(k) != 0 {
			return k
		}
	}
	return -1
}
Exemple #21
0
func FirstBitSet(v *big.Int) int {
	for i := 0; i < v.BitLen(); i++ {
		if v.Bit(i) > 0 {
			return i
		}
	}

	return v.BitLen()
}
Exemple #22
0
// trailingZeros counts the number of trailing zeros in the
// big.Int value. It first attempts to use an unsigned integer
// representation of the big.Int to compute this because it is
// roughly 8x faster. If this unsigned integer would overflow,
// it falls back to formatting the big.Int itself.
func trailingZeros(bi *big.Int, tmp []byte) int {
	if bi.BitLen() <= 64 {
		i := bi.Uint64()
		bs := strconv.AppendUint(tmp, i, 10)
		return trailingZerosFromBytes(bs)
	}
	bs := bi.Append(tmp, 10)
	return trailingZerosFromBytes(bs)
}
// Set the public key for X and Y for Curve. The two
// values are just concatenated.
func dsaToBuf(_Q, _P, _G, _Y *big.Int) []byte {
	t := divRoundUp(divRoundUp(_G.BitLen(), 8)-64, 8)
	buf := []byte{byte(t)}
	buf = append(buf, intToBytes(_Q, 20)...)
	buf = append(buf, intToBytes(_P, 64+t*8)...)
	buf = append(buf, intToBytes(_G, 64+t*8)...)
	buf = append(buf, intToBytes(_Y, 64+t*8)...)
	return buf
}
func SumBig(n *big.Int, base int) (sum int) {
	i := new(big.Int).Set(n)
	b := new(big.Int).SetUint64(uint64(base))
	r := new(big.Int)
	for i.BitLen() > 0 {
		i.DivMod(i, b, r)
		sum += int(r.Uint64())
	}
	return
}
Exemple #25
0
// numDigits returns the number of decimal digits that make up
// big.Int value. The function first attempts to look this digit
// count up in the digitsLookupTable. If the value is not there,
// it defaults to constructing a string value for the big.Int and
// using this to determine the number of digits. If a string value
// is constructed, it will be returned so it can be used again.
func numDigits(bi *big.Int, tmp []byte) (int, []byte) {
	if val, ok := lookupBits(bi.BitLen()); ok {
		if bi.Cmp(&val.border) < 0 {
			return val.digits, nil
		}
		return val.digits + 1, nil
	}
	bs := bi.Append(tmp, 10)
	return len(bs), bs
}
Exemple #26
0
func modPowBigInt(b, e, m *big.Int) (r *big.Int) {
	r = big.NewInt(1)
	for i, n := 0, e.BitLen(); i < n; i++ {
		if e.Bit(i) != 0 {
			r.Mod(r.Mul(r, b), m)
		}
		b.Mod(b.Mul(b, b), m)
	}
	return
}
Exemple #27
0
// Choose a uniform random big.Int less than a given modulus
func Int(mod *big.Int, rand cipher.Stream) *big.Int {
	bitlen := uint(mod.BitLen())
	i := new(big.Int)
	for {
		i.SetBytes(Bits(bitlen, false, rand))
		if i.Sign() > 0 && i.Cmp(mod) < 0 {
			return i
		}
	}
}
Exemple #28
0
// counts the number of zeros at the end of the
// binary expansion. So 2=10 ---> 1, 4=100 ---> 2
// 3=111 ---> 0, see test for more examples
// also 0 ---> 0 and 1 ---> 0
func trailingZeroBits(x *big.Int) (i uint) {
	if x.Sign() < 0 {
		panic("unknown bits of negative")
	}
	if x.Sign() == 0 || x.Bit(0) == 1 {
		return 0
	}
	for i = 1; i < uint(x.BitLen()) && x.Bit(int(i)) != 1; i++ {
	}
	return
}
Exemple #29
0
// z.Int() returns a representation of z, truncated to be an int of
// length bits.  Valid values for bits are 8, 16, 32, 64. Result is
// otherwise undefined If a truncation occurs, the decimal part is
// dropped and the conversion continues as usual. truncation will be
// true If an overflow occurs, the result is equivelant to a cast of
// the form int32(x). overflow will be true.
func (z *BigComplex) Int(bits int) (_ int64, truncation, overflow bool) {
	var integer *BigComplex
	integer, truncation = z.Integer()
	res := new(big.Int).Set(integer.Re.Num())

	// Numerator must fit in bits - 1, with 1 bit left for sign
	if overflow = res.BitLen() > bits-1; overflow {
		var mask uint64 = ^uint64(0) >> uint(64-bits)
		res.And(res, new(big.Int).SetUint64(mask))
	}
	return res.Int64(), truncation, overflow
}
Exemple #30
0
func bitSetToString(n *big.Int) string {
	var b bytes.Buffer
	b.WriteRune('{')
	for i, bitsLen := 0, n.BitLen(); i < bitsLen; i++ {
		if n.Bit(i) == 0 {
			continue
		}
		fmt.Fprintf(&b, "%v, ", i)
	}
	b.WriteRune('}')
	return b.String()
}