Beispiel #1
0
// ProbablyPrimeBigInt returns true if n is prime or n is a pseudoprime to base
// a. It implements the Miller-Rabin primality test for one specific value of
// 'a' and k == 1.  See also ProbablyPrimeUint32.
func ProbablyPrimeBigInt(n, a *big.Int) bool {
	var d big.Int
	d.Set(n)
	d.Sub(&d, _1) // d <- n-1
	s := 0
	for ; d.Bit(s) == 0; s++ {
	}
	nMinus1 := big.NewInt(0).Set(&d)
	d.Rsh(&d, uint(s))

	x := ModPowBigInt(a, &d, n)
	if x.Cmp(_1) == 0 || x.Cmp(nMinus1) == 0 {
		return true
	}

	for ; s > 1; s-- {
		if x = x.Mod(x.Mul(x, x), n); x.Cmp(_1) == 0 {
			return false
		}

		if x.Cmp(nMinus1) == 0 {
			return true
		}
	}
	return false
}
Beispiel #2
0
func q2() {
	n := new(big.Int)
	a := new(big.Int)
	asquared := new(big.Int)
	one := new(big.Int)
	x := new(big.Int)
	xsquared := new(big.Int)
	p := new(big.Int)
	q := new(big.Int)
	candidate := new(big.Int)

	n.SetString("648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877", 10)
	one.SetString("1", 10)

	a = mathutil.SqrtBig(n)
	for {
		a.Add(a, one)
		asquared.Mul(a, a)
		xsquared.Sub(asquared, n)
		x = mathutil.SqrtBig(xsquared)
		p.Sub(a, x)
		q.Add(a, x)
		if candidate.Mul(p, q).Cmp(n) == 0 {
			fmt.Println(p.String())
			break
		}
	}
}
Beispiel #3
0
// CalcGasLimit computes the gas limit of the next block after parent.
// The result may be modified by the caller.
// This is miner strategy, not consensus protocol.
func CalcGasLimit(parent *types.Block) *big.Int {
	// contrib = (parentGasUsed * 3 / 2) / 1024
	contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
	contrib = contrib.Div(contrib, big.NewInt(2))
	contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)

	// decay = parentGasLimit / 1024 -1
	decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
	decay.Sub(decay, big.NewInt(1))

	/*
		strategy: gasLimit of block-to-mine is set based on parent's
		gasUsed value.  if parentGasUsed > parentGasLimit * (2/3) then we
		increase it, otherwise lower it (or leave it unchanged if it's right
		at that usage) the amount increased/decreased depends on how far away
		from parentGasLimit * (2/3) parentGasUsed is.
	*/
	gl := new(big.Int).Sub(parent.GasLimit(), decay)
	gl = gl.Add(gl, contrib)
	gl.Set(common.BigMax(gl, params.MinGasLimit))

	// however, if we're now below the target (TargetGasLimit) we increase the
	// limit as much as we can (parentGasLimit / 1024 -1)
	if gl.Cmp(params.TargetGasLimit) < 0 {
		gl.Add(parent.GasLimit(), decay)
		gl.Set(common.BigMin(gl, params.TargetGasLimit))
	}
	return gl
}
Beispiel #4
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
}
Beispiel #5
0
func main() {
	var s string
	var n, two, tmp big.Int
	two.SetInt64(2)

	in, _ := os.Open("10519.in")
	defer in.Close()
	out, _ := os.Create("10519.out")
	defer out.Close()

	for {
		if _, err := fmt.Fscanf(in, "%s", &s); err != nil {
			break
		}
		if s == "0" {
			fmt.Fprintln(out, 1)
			continue
		}
		n.SetString(s, 10)
		tmp.Mul(&n, &n)
		tmp.Sub(&tmp, &n)
		tmp.Add(&tmp, &two)
		fmt.Fprintln(out, &tmp)
	}
}
Beispiel #6
0
func (block *Block) PayFee(addr []byte, fee *big.Int) bool {
	contract := block.state.GetContract(addr)
	// If we can't pay the fee return
	if contract == nil || contract.Amount.Cmp(fee) < 0 /* amount < fee */ {
		fmt.Println("Contract has insufficient funds", contract.Amount, fee)

		return false
	}

	base := new(big.Int)
	contract.Amount = base.Sub(contract.Amount, fee)
	block.state.trie.Update(string(addr), string(contract.RlpEncode()))

	data := block.state.trie.Get(string(block.Coinbase))

	// Get the ether (Coinbase) and add the fee (gief fee to miner)
	ether := NewAccountFromData([]byte(data))

	base = new(big.Int)
	ether.Amount = base.Add(ether.Amount, fee)

	block.state.trie.Update(string(block.Coinbase), string(ether.RlpEncode()))

	return true
}
Beispiel #7
0
// signRFC6979 generates a deterministic ECDSA signature according to RFC 6979
// and BIP 62.
func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) {

	privkey := privateKey.ToECDSA()
	N := order
	k := NonceRFC6979(privkey.D, hash, nil, nil)
	inv := new(big.Int).ModInverse(k, N)
	r, _ := privkey.Curve.ScalarBaseMult(k.Bytes())
	if r.Cmp(N) == 1 {
		r.Sub(r, N)
	}

	if r.Sign() == 0 {
		return nil, errors.New("calculated R is zero")
	}

	e := hashToInt(hash, privkey.Curve)
	s := new(big.Int).Mul(privkey.D, r)
	s.Add(s, e)
	s.Mul(s, inv)
	s.Mod(s, N)

	if s.Cmp(halforder) == 1 {
		s.Sub(N, s)
	}
	if s.Sign() == 0 {
		return nil, errors.New("calculated S is zero")
	}
	return &Signature{R: r, S: s}, nil
}
Beispiel #8
0
func (d *DHTNode) lookup(hash string) *DHTNode {

	if between([]byte(d.id), []byte(d.successor.id), []byte(hash)) {
		return d
	}

	dist := distance(d.id, hash, len(d.finger))
	index := dist.BitLen() - 1
	if index < 0 {
		return d
	}
	fmt.Println("INDEX", index)

	// scroll down until your finger is not pointing at himself
	for ; index > 0 && d.finger[index].node == d; index-- {

	}
	// Viewing so we do not end up too far
	diff := big.Int{}
	diff.Sub(dist, distance(d.id, d.finger[index].node.id, len(d.finger)))
	for index > 0 && diff.Sign() < 0 {
		index--
		diff.Sub(dist, distance(d.id, d.finger[index].node.id, len(d.finger)))
	}
	//check so we do not point at ourselves
	if d.finger[index].node == d || diff.Sign() < 0 {
		fmt.Println("ERROR ERROR alles gebort auf the baut")
		return d.successor.lookup(hash)

	}

	return d.finger[index].node.lookup(hash)

	//	return d.successor.lookup(hash)
}
Beispiel #9
0
func (d *DatasourceDerive) CalculatePdpPrep(newValue string, interval float64) (float64, error) {
	if float64(d.Heartbeat) < interval {
		d.LastValue = Undefined
	}

	rate := math.NaN()
	newPdp := math.NaN()
	if newValue != Undefined && float64(d.Heartbeat) >= interval {
		newInt := new(big.Int)
		_, err := fmt.Sscan(newValue, newInt)
		if err != nil {
			return math.NaN(), errors.Errorf("not a simple signed integer: %s", newValue)
		}
		if d.LastValue != "U" {
			prevInt := new(big.Int)
			_, err := fmt.Sscan(d.LastValue, prevInt)
			if err != nil {
				return math.NaN(), errors.Wrap(err, 0)
			}
			diff := new(big.Int)
			diff.Sub(newInt, prevInt)

			newPdp = float64(diff.Uint64())
			rate = newPdp / interval
		}
	}

	if !d.checkRateBounds(rate) {
		newPdp = math.NaN()
	}

	d.LastValue = newValue

	return newPdp, nil
}
Beispiel #10
0
// ComputeKey computes the session key given the salt and the value of B.
func (cs *ClientSession) ComputeKey(salt, B []byte) ([]byte, error) {
	cs.salt = salt

	err := cs.setB(B)
	if err != nil {
		return nil, err
	}

	// x = H(s, p)                 (user enters password)
	x := new(big.Int).SetBytes(cs.SRP.KeyDerivationFunc(cs.salt, cs.password))

	// S = (B - kg^x) ^ (a + ux)   (computes session key)
	// t1 = g^x
	t1 := new(big.Int).Exp(cs.SRP.Group.Generator, x, cs.SRP.Group.Prime)
	// unblind verifier
	t1.Sub(cs.SRP.Group.Prime, t1)
	t1.Mul(cs.SRP._k, t1)
	t1.Add(t1, cs._B)
	t1.Mod(t1, cs.SRP.Group.Prime)

	// t2 = ux
	t2 := new(big.Int).Mul(cs._u, x)
	// t2 = a + ux
	t2.Add(cs._a, t2)

	// t1 = (B - kg^x) ^ (a + ux)
	t3 := new(big.Int).Exp(t1, t2, cs.SRP.Group.Prime)
	// K = H(S)
	cs.key = quickHash(cs.SRP.HashFunc, t3.Bytes())

	return cs.key, nil
}
Beispiel #11
0
// decBigInt2C sets the value of n to the big-endian two's complement
// value stored in the given data. If data[0]&80 != 0, the number
// is negative. If data is empty, the result will be 0.
func decBigInt2C(data []byte) *big.Int {
	n := new(big.Int).SetBytes(data)
	if len(data) > 0 && data[0]&0x80 > 0 {
		n.Sub(n, new(big.Int).Lsh(bigOne, uint(len(data))*8))
	}
	return n
}
Beispiel #12
0
// Try to generate a point on this curve from a chosen x-coordinate,
// with a random sign.
func (p *curvePoint) genPoint(x *big.Int, rand cipher.Stream) bool {

	// Compute the corresponding Y coordinate, if any
	y2 := new(big.Int).Mul(x, x)
	y2.Mul(y2, x)
	threeX := new(big.Int).Lsh(x, 1)
	threeX.Add(threeX, x)
	y2.Sub(y2, threeX)
	y2.Add(y2, p.c.p.B)
	y2.Mod(y2, p.c.p.P)
	y := p.c.sqrt(y2)

	// Pick a random sign for the y coordinate
	b := make([]byte, 1)
	rand.XORKeyStream(b, b)
	if (b[0] & 0x80) != 0 {
		y.Sub(p.c.p.P, y)
	}

	// Check that it's a valid point
	y2t := new(big.Int).Mul(y, y)
	y2t.Mod(y2t, p.c.p.P)
	if y2t.Cmp(y2) != 0 {
		return false // Doesn't yield a valid point!
	}

	p.x = x
	p.y = y
	return true
}
Beispiel #13
0
func (self *Decoder) unsigned_to_signed(x *big.Int, bits uint) *big.Int {
	// return x - ((x >> (bits - 1)) << bits)
	temp := new(big.Int)
	temp.Rsh(x, bits-1)
	temp.Lsh(temp, bits)
	return temp.Sub(x, temp)
}
Beispiel #14
0
func makeBigInt(n *big.Int) (encoder, error) {
	if n == nil {
		return nil, StructuralError{"empty integer"}
	}

	if n.Sign() < 0 {
		// A negative number has to be converted to two's-complement
		// form. So we'll invert and subtract 1. If the
		// most-significant-bit isn't set then we'll need to pad the
		// beginning with 0xff in order to keep the number negative.
		nMinus1 := new(big.Int).Neg(n)
		nMinus1.Sub(nMinus1, bigOne)
		bytes := nMinus1.Bytes()
		for i := range bytes {
			bytes[i] ^= 0xff
		}
		if len(bytes) == 0 || bytes[0]&0x80 == 0 {
			return multiEncoder([]encoder{byteFFEncoder, bytesEncoder(bytes)}), nil
		}
		return bytesEncoder(bytes), nil
	} else if n.Sign() == 0 {
		// Zero is written as a single 0 zero rather than no bytes.
		return byte00Encoder, nil
	} else {
		bytes := n.Bytes()
		if len(bytes) > 0 && bytes[0]&0x80 != 0 {
			// We'll have to pad this with 0x00 in order to stop it
			// looking like a negative number.
			return multiEncoder([]encoder{byte00Encoder, bytesEncoder(bytes)}), nil
		}
		return bytesEncoder(bytes), nil
	}
}
Beispiel #15
0
// privateEncrypt implements OpenSSL's RSA_private_encrypt function
func privateEncrypt(key *rsa.PrivateKey, data []byte) (enc []byte, err error) {
	k := (key.N.BitLen() + 7) / 8
	tLen := len(data)

	// rfc2313, section 8:
	// The length of the data D shall not be more than k-11 octets
	if tLen > k-11 {
		err = errors.New("Data too long")
		return
	}
	em := make([]byte, k)
	em[1] = 1
	for i := 2; i < k-tLen-1; i++ {
		em[i] = 0xff
	}
	copy(em[k-tLen:k], data)
	c := new(big.Int).SetBytes(em)
	if c.Cmp(key.N) > 0 {
		err = nil
		return
	}
	var m *big.Int
	var ir *big.Int
	if key.Precomputed.Dp == nil {
		m = new(big.Int).Exp(c, key.D, key.N)
	} else {
		// We have the precalculated values needed for the CRT.
		m = new(big.Int).Exp(c, key.Precomputed.Dp, key.Primes[0])
		m2 := new(big.Int).Exp(c, key.Precomputed.Dq, key.Primes[1])
		m.Sub(m, m2)
		if m.Sign() < 0 {
			m.Add(m, key.Primes[0])
		}
		m.Mul(m, key.Precomputed.Qinv)
		m.Mod(m, key.Primes[0])
		m.Mul(m, key.Primes[1])
		m.Add(m, m2)

		for i, values := range key.Precomputed.CRTValues {
			prime := key.Primes[2+i]
			m2.Exp(c, values.Exp, prime)
			m2.Sub(m2, m)
			m2.Mul(m2, values.Coeff)
			m2.Mod(m2, prime)
			if m2.Sign() < 0 {
				m2.Add(m2, prime)
			}
			m2.Mul(m2, values.R)
			m.Add(m, m2)
		}
	}

	if ir != nil {
		// Unblind.
		m.Mul(m, ir)
		m.Mod(m, key.N)
	}
	enc = m.Bytes()
	return
}
Beispiel #16
0
// Sign creates a signature on the hash under the given secret key.
func Sign(sk *eckey.SecretKey, hash []byte) (*Signature, error) {
	// Generate random nonce
nonce:
	k, kG, err := eckey.GenerateKeyPair()
	if err != nil {
		return nil, err
	}
	// Try again if kG is nil (point at infinity)
	if kG == nil {
		goto nonce
	}
	// Clear nonce after completion
	defer k.Zero()

	// Compute non-interactive challenge
	e := util.Hash256d(append([]byte(hash), kG[:]...))

	kInt := new(big.Int).SetBytes(k[:])
	eInt := new(big.Int).SetBytes(e[:])
	rInt := new(big.Int).SetBytes(sk[:])

	// Compute s = k - er
	s := new(big.Int)
	s.Mul(eInt, rInt)
	s.Sub(kInt, s)
	s.Mod(s, eckey.S256.N)

	// Serialize signature
	sig := new(Signature)
	copy(sig[:SignatureSize/2], e[:])
	util.PaddedCopy(sig[SignatureSize/2:], s.Bytes(), SignatureSize/2)

	return sig, nil
}
Beispiel #17
0
func main() {
	raw, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		log.Fatalln(err)
	}

	raw_strs := strings.Fields(strings.Replace(string(raw), "\n", " ", -1))

	ctext, _ := new(big.Int).SetString(raw_strs[0], 0)
	N, _ := new(big.Int).SetString(raw_strs[1], 0)
	e := big.NewInt(65537)

	p, q := get_factor(N)
	if p == nil || q == nil {
		log.Fatalln("Didn't get factor")
	}

	f := new(big.Int).Sub(N, p)
	f.Sub(f, q).Add(f, big.NewInt(1))

	d := new(big.Int).ModInverse(e, f)

	pkcs1 := new(big.Int).Exp(ctext, d, N).Bytes()
	for i, bt := range pkcs1 {
		if bt == 0x00 {
			fmt.Printf("%s\n", pkcs1[i+1:])
			break
		}
	}
}
Beispiel #18
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
}
Beispiel #19
0
func Sub11(xx *big.Int) big.Int {
	mm := new(big.Int)
	kk := big.NewInt(10)
	yy := new(big.Int)
	yy.DivMod(xx, kk, mm)
	yy.Sub(yy, mm)
	return *yy
}
Beispiel #20
0
func fact(n *big.Int) *big.Int {
	one := big.NewInt(1)
	r := big.NewInt(1)
	for n.Cmp(one) > 0 {
		r = r.Mul(r, n)
		n = n.Sub(n, one)
	}
	return r
}
Beispiel #21
0
// Simple go routine function that updates the list of peers in the GUI
func (ui *Gui) update() {
	txChan := make(chan ethchain.TxMsg, 1)
	ui.eth.TxPool().Subscribe(txChan)

	account := ui.eth.StateManager().GetAddrState(ui.addr).Account
	unconfirmedFunds := new(big.Int)
	ui.win.Root().Call("setWalletValue", fmt.Sprintf("%v", ethutil.CurrencyToString(account.Amount)))
	for {
		select {
		case txMsg := <-txChan:
			tx := txMsg.Tx

			if txMsg.Type == ethchain.TxPre {
				if bytes.Compare(tx.Sender(), ui.addr) == 0 {
					ui.win.Root().Call("addTx", NewTxFromTransaction(tx))
					ui.txDb.Put(tx.Hash(), tx.RlpEncode())

					ui.eth.StateManager().GetAddrState(ui.addr).Nonce += 1
					unconfirmedFunds.Sub(unconfirmedFunds, tx.Value)
				} else if bytes.Compare(tx.Recipient, ui.addr) == 0 {
					ui.win.Root().Call("addTx", NewTxFromTransaction(tx))
					ui.txDb.Put(tx.Hash(), tx.RlpEncode())

					unconfirmedFunds.Add(unconfirmedFunds, tx.Value)
				}

				pos := "+"
				if unconfirmedFunds.Cmp(big.NewInt(0)) >= 0 {
					pos = "-"
				}
				val := ethutil.CurrencyToString(new(big.Int).Abs(ethutil.BigCopy(unconfirmedFunds)))
				str := fmt.Sprintf("%v (%s %v)", ethutil.CurrencyToString(account.Amount), pos, val)

				ui.win.Root().Call("setWalletValue", str)
			} else {
				amount := account.Amount
				if bytes.Compare(tx.Sender(), ui.addr) == 0 {
					amount.Sub(account.Amount, tx.Value)
				} else if bytes.Compare(tx.Recipient, ui.addr) == 0 {
					amount.Add(account.Amount, tx.Value)
				}

				ui.win.Root().Call("setWalletValue", fmt.Sprintf("%v", ethutil.CurrencyToString(amount)))
			}
		}

		/*
			accountAmount := ui.eth.BlockManager.GetAddrState(ui.addr).Account.Amount
			ui.win.Root().Call("setWalletValue", fmt.Sprintf("%v", accountAmount))

			ui.win.Root().Call("setPeers", fmt.Sprintf("%d / %d", ui.eth.Peers().Len(), ui.eth.MaxPeers))

			time.Sleep(1 * time.Second)
		*/

	}
}
Beispiel #22
0
func UseGas(gas, amount *big.Int) bool {
	if gas.Cmp(amount) < 0 {
		return false
	}

	// Sub the amount of gas from the remaining
	gas.Sub(gas, amount)
	return true
}
Beispiel #23
0
func NewRSA(p, q *big.Int) RSA {
	n := new(big.Int).Mul(p, q)
	t := new(big.Int).Sub(n, p)
	t.Sub(t, q)
	t.Add(t, big.NewInt(1))
	e := big.NewInt(65537)
	d := new(big.Int).ModInverse(e, t)
	return &rsa{d, e, n}
}
Beispiel #24
0
// GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit
// size, as suggested in [1]. Although the public keys are compatible
// (actually, indistinguishable) from the 2-prime case, the private keys are
// not. Thus it may not be possible to export multi-prime private keys in
// certain formats or to subsequently import them into other code.
//
// Table 1 in [2] suggests maximum numbers of primes for a given size.
//
// [1] US patent 4405829 (1972, expired)
// [2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err error) {
	priv = new(PrivateKey)
	priv.E = 65537

	if nprimes < 2 {
		return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2")
	}

	primes := make([]*big.Int, nprimes)

NextSetOfPrimes:
	for {
		todo := bits
		for i := 0; i < nprimes; i++ {
			primes[i], err = rand.Prime(random, todo/(nprimes-i))
			if err != nil {
				return nil, err
			}
			todo -= primes[i].BitLen()
		}

		// Make sure that primes is pairwise unequal.
		for i, prime := range primes {
			for j := 0; j < i; j++ {
				if prime.Cmp(primes[j]) == 0 {
					continue NextSetOfPrimes
				}
			}
		}

		n := new(big.Int).Set(bigOne)
		totient := new(big.Int).Set(bigOne)
		pminus1 := new(big.Int)
		for _, prime := range primes {
			n.Mul(n, prime)
			pminus1.Sub(prime, bigOne)
			totient.Mul(totient, pminus1)
		}

		g := new(big.Int)
		priv.D = new(big.Int)
		y := new(big.Int)
		e := big.NewInt(int64(priv.E))
		g.GCD(priv.D, y, e, totient)

		if g.Cmp(bigOne) == 0 {
			priv.D.Add(priv.D, totient)
			priv.Primes = primes
			priv.N = n

			break
		}
	}

	priv.Precompute()
	return
}
Beispiel #25
0
func FindCoFactors(q, n *big.Int, G Group) map[int64]Element {
	j := new(big.Int)
	j.Sub(n, big.NewInt(1))
	j.Div(j, q)

	groupSize := new(big.Int).Sub(n, big.NewInt(1))

	return FindFactors(j, groupSize, q, G)
}
Beispiel #26
0
// Set z to one of the square roots of a modulo p if a square root exists.
// The modulus p must be an odd prime.
// Returns true on success, false if input a is not a square modulo p.
func Sqrt(z *big.Int, a *big.Int, p *big.Int) bool {

	if a.Sign() == 0 {
		z.SetInt64(0) // sqrt(0) = 0
		return true
	}
	if Jacobi(a, p) != 1 {
		return false // a is not a square mod M
	}

	// Break p-1 into s*2^e such that s is odd.
	var s big.Int
	var e int
	s.Sub(p, one)
	for s.Bit(0) == 0 {
		s.Div(&s, two)
		e++
	}

	// Find some non-square n
	var n big.Int
	n.SetInt64(2)
	for Jacobi(&n, p) != -1 {
		n.Add(&n, one)
	}

	// Heart of the Tonelli-Shanks algorithm.
	// Follows the description in
	// "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra Brown.
	var x, b, g, t big.Int
	x.Add(&s, one).Div(&x, two).Exp(a, &x, p)
	b.Exp(a, &s, p)
	g.Exp(&n, &s, p)
	r := e
	for {
		// Find the least m such that ord_p(b) = 2^m
		var m int
		t.Set(&b)
		for t.Cmp(one) != 0 {
			t.Exp(&t, two, p)
			m++
		}

		if m == 0 {
			z.Set(&x)
			return true
		}

		t.SetInt64(0).SetBit(&t, r-m-1, 1).Exp(&g, &t, p)
		// t = g^(2^(r-m-1)) mod p
		g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
		x.Mul(&x, &t).Mod(&x, p)
		b.Mul(&b, &g).Mod(&b, p)
		r = m
	}
}
Beispiel #27
0
// JacobiSymbol returns the jacobi symbol ( N / D ) of
// N (numerator) over D (denominator).
// See http://en.wikipedia.org/wiki/Jacobi_symbol
func JacobiSymbol(N *big.Int, D *big.Int) int {
	//Step 0: parse input / easy cases
	if D.Sign() <= 0 || D.Bit(0) == 0 {
		// we will assume D is positive
		// wolfram is ok with negative denominator
		// im not sure what is standard though
		panic("JacobiSymbol defined for positive odd denominator only")
	}
	var n, d, tmp big.Int
	n.Set(N)
	d.Set(D)
	j := 1
	for {
		// Step 1: Reduce the numerator mod the denominator
		n.Mod(&n, &d)
		if n.Sign() == 0 {
			// if n,d not relatively prime
			return 0
		}
		if len(n.Bits()) >= len(d.Bits())-1 {
			// n > d/2 so swap n with d-n
			// and multiply j by JacobiSymbol(-1 / d)
			n.Sub(&d, &n)
			if d.Bits()[0]&3 == 3 {
				// if d = 3 mod 4
				j = -1 * j
			}
		}

		// Step 2: extract factors of 2
		s := trailingZeroBits(&n)
		n.Rsh(&n, s)
		if s&1 == 1 {
			switch d.Bits()[0] & 7 {
			case 3, 5: // d = 3,5 mod 8
				j = -1 * j
			}
		}

		// Step 3: check numerator
		if len(n.Bits()) == 1 && n.Bits()[0] == 1 {
			// if n = 1 were done
			return j
		}

		// Step 4: flip and go back to step 1
		if n.Bits()[0]&3 != 1 { // n = 3 mod 4
			if d.Bits()[0]&3 != 1 { // d = 3 mod 4
				j = -1 * j
			}
		}
		tmp.Set(&n)
		n.Set(&d)
		d.Set(&tmp)
	}
}
Beispiel #28
0
// Compute the Legendre symbol of i, if modulus M is prime,
// using the Euler criterion (which involves exponentiation).
func (i *Int) legendre() int {
	var Pm1, v big.Int
	Pm1.Sub(i.M, one)
	v.Div(&Pm1, two)
	v.Exp(&i.V, &v, i.M)
	if v.Cmp(&Pm1) == 0 {
		return -1
	}
	return v.Sign()
}
Beispiel #29
0
// Calculates the signed distance between two ids on the circular ID space
func delta(a, b *big.Int) *big.Int {
	d := new(big.Int).Sub(b, a)
	switch {
	case posmid.Cmp(d) < 0:
		d.Sub(d, modulo)
	case negmid.Cmp(d) > 0:
		d.Add(d, modulo)
	}
	return d
}
func splitRangeString(start, end string, splits int) []string {
	results := []string{start}
	if start == end {
		return results
	}
	if end < start {
		tmp := start
		start = end
		end = tmp
	}

	// find longest common prefix between strings
	minLen := len(start)
	if len(end) < minLen {
		minLen = len(end)
	}
	prefix := ""
	for i := 0; i < minLen; i++ {
		if start[i] == end[i] {
			prefix = start[0 : i+1]
		} else {
			break
		}
	}

	// remove prefix from strings to split
	start = start[len(prefix):]
	end = end[len(prefix):]

	ordStart := stringToOrd(start)
	ordEnd := stringToOrd(end)

	tmp := new(big.Int)
	tmp.Sub(ordEnd, ordStart)

	stride := new(big.Float)
	stride.SetInt(tmp)
	stride.Quo(stride, big.NewFloat(float64(splits)))

	for i := 1; i <= splits; i++ {
		tmp := new(big.Float)
		tmp.Mul(stride, big.NewFloat(float64(i)))
		tmp.Add(tmp, new(big.Float).SetInt(ordStart))

		result, _ := tmp.Int(new(big.Int))

		value := prefix + ordToString(result, 0)

		if value != results[len(results)-1] {
			results = append(results, value)
		}
	}

	return results
}