Esempio n. 1
0
// Verify verifies the signature in r, s of hash using the public key, pub. It
// returns true iff the signature is valid.
func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
	// See [NSA] 3.4.2
	c := pub.Curve

	if r.Sign() == 0 || s.Sign() == 0 {
		return false
	}
	if r.Cmp(c.N) >= 0 || s.Cmp(c.N) >= 0 {
		return false
	}
	e := hashToInt(hash, c)
	w := new(big.Int).ModInverse(s, c.N)

	u1 := e.Mul(e, w)
	u2 := w.Mul(r, w)

	x1, y1 := c.ScalarBaseMult(u1.Bytes())
	x2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes())
	if x1.Cmp(x2) == 0 {
		return false
	}
	x, _ := c.Add(x1, y1, x2, y2)
	x.Mod(x, c.N)
	return x.Cmp(r) == 0
}
Esempio n. 2
0
// Precompute performs some calculations that speed up private key operations
// in the future.
func (priv *PrivateKey) Precompute() {
	if priv.Precomputed.Dp != nil {
		return
	}

	priv.Precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne)
	priv.Precomputed.Dp.Mod(priv.D, priv.Precomputed.Dp)

	priv.Precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne)
	priv.Precomputed.Dq.Mod(priv.D, priv.Precomputed.Dq)

	priv.Precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0])

	r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1])
	priv.Precomputed.CRTValues = make([]CRTValue, len(priv.Primes)-2)
	for i := 2; i < len(priv.Primes); i++ {
		prime := priv.Primes[i]
		values := &priv.Precomputed.CRTValues[i-2]

		values.Exp = new(big.Int).Sub(prime, bigOne)
		values.Exp.Mod(priv.D, values.Exp)

		values.R = new(big.Int).Set(r)
		values.Coeff = new(big.Int).ModInverse(r, prime)

		r.Mul(r, prime)
	}
}
Esempio n. 3
0
File: rsa.go Progetto: richlowe/gcc
// Generate3PrimeKey generates a 3-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 3-prime private keys in certain formats or to
// subsequently import them into other code.
//
// Table 1 in [2] suggests that size should be >= 1024 when using 3 primes.
//
// [1] US patent 4405829 (1972, expired)
// [2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
func Generate3PrimeKey(rand io.Reader, bits int) (priv *PrivateKey, err os.Error) {
	priv = new(PrivateKey)
	priv.E = 3

	pminus1 := new(big.Int)
	qminus1 := new(big.Int)
	rminus1 := new(big.Int)
	totient := new(big.Int)

	for {
		p, err := randomPrime(rand, bits/3)
		if err != nil {
			return nil, err
		}

		todo := bits - p.BitLen()
		q, err := randomPrime(rand, todo/2)
		if err != nil {
			return nil, err
		}

		todo -= q.BitLen()
		r, err := randomPrime(rand, todo)
		if err != nil {
			return nil, err
		}

		if p.Cmp(q) == 0 ||
			q.Cmp(r) == 0 ||
			r.Cmp(p) == 0 {
			continue
		}

		n := new(big.Int).Mul(p, q)
		n.Mul(n, r)
		pminus1.Sub(p, bigOne)
		qminus1.Sub(q, bigOne)
		rminus1.Sub(r, bigOne)
		totient.Mul(pminus1, qminus1)
		totient.Mul(totient, rminus1)

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

		if g.Cmp(bigOne) == 0 {
			priv.D.Add(priv.D, totient)
			priv.P = p
			priv.Q = q
			priv.R = r
			priv.N = n

			break
		}
	}

	return
}
Esempio n. 4
0
/**
 * Store partial product result lines in the Calculator output lines.
 */
func (calc *Calculator) setPartialLines() {
	var (
		opDigits = calc.operands[1].String()
		opLength = len(opDigits)
	)

	// From largest to smallest place values (i.e., last to first partial result
	// lines)
	for index, digit := range opDigits {
		var (
			placeValue big.Int
			buffer     bytes.Buffer

			// Amount of right indentation this line has and also the position
			// relative to the first partial result line (right after the first
			// ruler)
			offset = opLength - index - 1
		)

		placeValue.SetString(fmt.Sprintf("%c", digit), 10)
		placeValue.Mul(&placeValue, &calc.operands[0])

		// We're right-padding with spaces, but these will be stripped out later
		buffer.WriteString(placeValue.String())
		buffer.WriteString(strings.Repeat(" ", offset))

		calc.lines[3+offset] = buffer.String()
	}
}
Esempio n. 5
0
// 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
}
Esempio n. 6
0
// Verify verifies the signature in r, s of hash using the public key, pub. It
// returns true iff the signature is valid.
func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
	// FIPS 186-3, section 4.7

	if r.Sign() < 1 || r.Cmp(pub.Q) >= 0 {
		return false
	}
	if s.Sign() < 1 || s.Cmp(pub.Q) >= 0 {
		return false
	}

	w := new(big.Int).ModInverse(s, pub.Q)

	n := pub.Q.BitLen()
	if n&7 != 0 {
		return false
	}
	n >>= 3

	if n > len(hash) {
		n = len(hash)
	}
	z := new(big.Int).SetBytes(hash[:n])

	u1 := new(big.Int).Mul(z, w)
	u1.Mod(u1, pub.Q)
	u2 := w.Mul(r, w)
	u2.Mod(u2, pub.Q)
	v := u1.Exp(pub.G, u1, pub.P)
	u2.Exp(pub.Y, u2, pub.P)
	v.Mul(v, u2)
	v.Mod(v, pub.P)
	v.Mod(v, pub.Q)

	return v.Cmp(r) == 0
}
Esempio n. 7
0
// Decrypt takes two integers, resulting from an ElGamal encryption, and
// returns the plaintext of the message. An error can result only if the
// ciphertext is invalid. Users should keep in mind that this is a padding
// oracle and thus, if exposed to an adaptive chosen ciphertext attack, can
// be used to break the cryptosystem.  See ``Chosen Ciphertext Attacks
// Against Protocols Based on the RSA Encryption Standard PKCS #1'', Daniel
// Bleichenbacher, Advances in Cryptology (Crypto '98),
func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err error) {
	s := new(big.Int).Exp(c1, priv.X, priv.P)
	s.ModInverse(s, priv.P)
	s.Mul(s, c2)
	s.Mod(s, priv.P)
	em := s.Bytes()

	firstByteIsTwo := subtle.ConstantTimeByteEq(em[0], 2)

	// The remainder of the plaintext must be a string of non-zero random
	// octets, followed by a 0, followed by the message.
	//   lookingForIndex: 1 iff we are still looking for the zero.
	//   index: the offset of the first zero byte.
	var lookingForIndex, index int
	lookingForIndex = 1

	for i := 1; i < len(em); i++ {
		equals0 := subtle.ConstantTimeByteEq(em[i], 0)
		index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index)
		lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex)
	}

	if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 {
		return nil, errors.New("elgamal: decryption error")
	}
	return em[index+1:], nil
}
Esempio n. 8
0
// Zjisti a0, b0, z tak aby: a0*x + b0*y = z (mod n)
func Euklid(x, y, n *big.Int) (a0, b0, z *big.Int) {
	a0 = big1
	a := big0
	b0 = big0
	b := big1
	g := new(big.Int)
	t := new(big.Int) // tmp

	if x.Cmp(y) < 0 {
		x, y = y, x
		a0, a, b0, b = b0, b, a0, a
	}

	for {
		z = y
		_, y = g.Div(x, y)
		x = z

		a0, a = a, _Euklid_sub(a0, t.Mul(a, g), n)
		b0, b = b, _Euklid_sub(b0, t.Mul(b, g), n)

		if y.Cmp(big0) == 0 {
			break
		}
	}
	return
}
Esempio n. 9
0
// Vrati cisla n, e, d, p, q takova ze, pro nahodne vygenerovana ln-bitova
// prvocisla p, q plati, ze e*d + (p-1)(q-1)*X = 1 (mod (p-1)(q-1)) a n = p*q.
func GenerateKeys(ln int) (n, e, d, p, q *big.Int) {
	e = big.NewInt(17) // mělo by stačit
	n = new(big.Int)
	m := new(big.Int)
	t := new(big.Int) // tmp
	var r *big.Int

	for {
		p = NewPrime(ln)
		q = NewPrime(ln)
		if p.Cmp(q) == 0 {
			continue
		}

		n.Mul(p, q)                           // n = p*q
		m.Mul(t.Sub(p, big1), m.Sub(q, big1)) // m = (p-1)*(q-1)
		_, d, r = Euklid(m, e, m)

		if r.Cmp(big1) != 0 {
			continue
		} // je GCD(e,m) = 1 ?
		break
	}
	return
}
Esempio n. 10
0
func (h *Hash) l3(m []byte, iter int) []byte {
	i := 0
	k1 := new(big.Int)
	k2 := new(big.Int)

	for need := iter + 1; need > 0; i++ {
		t := h.kdf(224, 128*(i+1))[16*i : 16*(i+1)]
		k1.SetBytes(t[:8])
		k2.SetBytes(t[8:])
		if k1.Cmp(p64) == -1 && k2.Cmp(p64) == -1 {
			need--
		}
	}

	mint := newInt(m)
	m1 := new(big.Int).Div(mint, p64p32)
	m2 := new(big.Int).Mod(mint, p64p32)

	y := new(big.Int).Add(m1, k1)
	y.Mul(y, new(big.Int).Add(m2, k2))
	y.Mod(y, p64)

	Y := make([]byte, 8)
	copy(Y[8-len(y.Bytes()):], y.Bytes())
	return Y
}
Esempio n. 11
0
func (b Base58) Base582Big() *big.Int {
	answer := new(big.Int)
	for i := 0; i < len(b); i++ {
		answer.Mul(answer, big.NewInt(58))                              //multiply current value by 58
		answer.Add(answer, big.NewInt(int64(revalp[string(b[i:i+1])]))) //add value of the current letter
	}
	return answer
}
Esempio n. 12
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("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))
		big.GcdInt(g, 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
}
Esempio n. 13
0
// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and
// returns its double, also in Jacobian form.
func (curve *Curve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
	// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
	delta := new(big.Int).Mul(z, z)
	delta.Mod(delta, curve.P)
	gamma := new(big.Int).Mul(y, y)
	gamma.Mod(gamma, curve.P)
	alpha := new(big.Int).Sub(x, delta)
	if alpha.Sign() == -1 {
		alpha.Add(alpha, curve.P)
	}
	alpha2 := new(big.Int).Add(x, delta)
	alpha.Mul(alpha, alpha2)
	alpha2.Set(alpha)
	alpha.Lsh(alpha, 1)
	alpha.Add(alpha, alpha2)

	beta := alpha2.Mul(x, gamma)

	x3 := new(big.Int).Mul(alpha, alpha)
	beta8 := new(big.Int).Lsh(beta, 3)
	x3.Sub(x3, beta8)
	for x3.Sign() == -1 {
		x3.Add(x3, curve.P)
	}
	x3.Mod(x3, curve.P)

	z3 := new(big.Int).Add(y, z)
	z3.Mul(z3, z3)
	z3.Sub(z3, gamma)
	if z3.Sign() == -1 {
		z3.Add(z3, curve.P)
	}
	z3.Sub(z3, delta)
	if z3.Sign() == -1 {
		z3.Add(z3, curve.P)
	}
	z3.Mod(z3, curve.P)

	beta.Lsh(beta, 2)
	beta.Sub(beta, x3)
	if beta.Sign() == -1 {
		beta.Add(beta, curve.P)
	}
	y3 := alpha.Mul(alpha, beta)

	gamma.Mul(gamma, gamma)
	gamma.Lsh(gamma, 3)
	gamma.Mod(gamma, curve.P)

	y3.Sub(y3, gamma)
	if y3.Sign() == -1 {
		y3.Add(y3, curve.P)
	}
	y3.Mod(y3, curve.P)

	return x3, y3, z3
}
func binomial(p *primes.Sieve, n, k uint64) *big.Int {

	var r big.Int
	if k > n {
		return &r
	}

	if k > n/2 {
		k = n - k
	}

	if k < 3 {
		switch k {
		case 0:
			return r.SetInt64(1)
		case 1:
			return r.SetInt64(int64(n))
		case 2:
			var n1 big.Int
			return r.Rsh(r.Mul(r.SetInt64(int64(n)), n1.SetInt64(int64(n-1))), 1)
		}
	}

	var i int
	rootN := xmath.FloorSqrt(n)
	factors := make([]uint64, n)

	p.IteratePrimes(2, rootN, func(p uint64) {
		var r, nn, kk uint64 = 0, n, k
		for nn > 0 {
			if nn%p < kk%p+r {
				r = 1
				factors[i] = p
				i++
			} else {
				r = 0
			}
			nn /= p
			kk /= p
		}
	})

	p.IteratePrimes(rootN+1, n/2, func(p uint64) {
		if n%p < k%p {
			factors[i] = p
			i++
		}
	})

	p.IteratePrimes(n-k+1, n, func(p uint64) {
		factors[i] = p
		i++
	})

	return xmath.Product(factors[0:i])
}
Esempio n. 15
0
// affineFromJacobian reverses the Jacobian transform. See the comment at the
// top of the file.
func (curve *Curve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) {
	zinv := new(big.Int).ModInverse(z, curve.P)
	zinvsq := new(big.Int).Mul(zinv, zinv)

	xOut = new(big.Int).Mul(x, zinvsq)
	xOut.Mod(xOut, curve.P)
	zinvsq.Mul(zinvsq, zinv)
	yOut = new(big.Int).Mul(y, zinvsq)
	yOut.Mod(yOut, curve.P)
	return
}
Esempio n. 16
0
// GenerateKeyPair generates an RSA keypair of the given bit size.
func GenerateKey(rand io.Reader, bits int) (priv *PrivateKey, err os.Error) {
	priv = new(PrivateKey)
	// Smaller public exponents lead to faster public key
	// operations. Since the exponent must be coprime to
	// (p-1)(q-1), the smallest possible value is 3. Some have
	// suggested that a larger exponent (often 2**16+1) be used
	// since previous implementation bugs[1] were avoided when this
	// was the case. However, there are no current reasons not to use
	// small exponents.
	// [1] http://marc.info/?l=cryptography&m=115694833312008&w=2
	priv.E = 3

	pminus1 := new(big.Int)
	qminus1 := new(big.Int)
	totient := new(big.Int)

	for {
		p, err := randomPrime(rand, bits/2)
		if err != nil {
			return nil, err
		}

		q, err := randomPrime(rand, bits/2)
		if err != nil {
			return nil, err
		}

		if p.Cmp(q) == 0 {
			continue
		}

		n := new(big.Int).Mul(p, q)
		pminus1.Sub(p, bigOne)
		qminus1.Sub(q, bigOne)
		totient.Mul(pminus1, qminus1)

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

		if g.Cmp(bigOne) == 0 {
			priv.D.Add(priv.D, totient)
			priv.P = p
			priv.Q = q
			priv.N = n

			break
		}
	}

	return
}
Esempio n. 17
0
/**
 * Store the solution in the Calculator output lines.
 */
func (calc *Calculator) setSolutionLine() {
	var solution big.Int

	if calc.operator == '+' {
		solution.Add(&calc.operands[0], &calc.operands[1])
	} else if calc.operator == '-' {
		solution.Sub(&calc.operands[0], &calc.operands[1])
	} else {
		solution.Mul(&calc.operands[0], &calc.operands[1])
	}

	calc.lines[len(calc.lines)-1] = solution.String()
}
// IsOnBitCurve returns true if the given (x,y) lies on the BitCurve.
func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool {
	// y² = x³ + b
	y2 := new(big.Int).Mul(y, y) //y²
	y2.Mod(y2, BitCurve.P)       //y²%P

	x3 := new(big.Int).Mul(x, x) //x²
	x3.Mul(x3, x)                //x³

	x3.Add(x3, BitCurve.B) //x³+B
	x3.Mod(x3, BitCurve.P) //(x³+B)%P

	return x3.Cmp(y2) == 0
}
// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and
// returns its double, also in Jacobian form.
func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
	// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l

	a := new(big.Int).Mul(x, x) //X1²
	b := new(big.Int).Mul(y, y) //Y1²
	c := new(big.Int).Mul(b, b) //B²

	d := new(big.Int).Add(x, b) //X1+B
	d.Mul(d, d)                 //(X1+B)²
	d.Sub(d, a)                 //(X1+B)²-A
	d.Sub(d, c)                 //(X1+B)²-A-C
	d.Mul(d, big.NewInt(2))     //2*((X1+B)²-A-C)

	e := new(big.Int).Mul(big.NewInt(3), a) //3*A
	f := new(big.Int).Mul(e, e)             //E²

	x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D
	x3.Sub(f, x3)                            //F-2*D
	x3.Mod(x3, BitCurve.P)

	y3 := new(big.Int).Sub(d, x3)                  //D-X3
	y3.Mul(e, y3)                                  //E*(D-X3)
	y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C
	y3.Mod(y3, BitCurve.P)

	z3 := new(big.Int).Mul(y, z) //Y1*Z1
	z3.Mul(big.NewInt(2), z3)    //3*Y1*Z1
	z3.Mod(z3, BitCurve.P)

	return x3, y3, z3
}
Esempio n. 20
0
File: rsa.go Progetto: richlowe/gcc
func (priv *PrivateKey) Validate() os.Error {
	// Check that p, q and, maybe, r are prime. Note that this is just a
	// sanity check. Since the random witnesses chosen by ProbablyPrime are
	// deterministic, given the candidate number, it's easy for an attack
	// to generate composites that pass this test.
	if !big.ProbablyPrime(priv.P, 20) {
		return os.ErrorString("P is composite")
	}
	if !big.ProbablyPrime(priv.Q, 20) {
		return os.ErrorString("Q is composite")
	}
	if priv.R != nil && !big.ProbablyPrime(priv.R, 20) {
		return os.ErrorString("R is composite")
	}

	// Check that p*q*r == n.
	modulus := new(big.Int).Mul(priv.P, priv.Q)
	if priv.R != nil {
		modulus.Mul(modulus, priv.R)
	}
	if modulus.Cmp(priv.N) != 0 {
		return os.ErrorString("invalid modulus")
	}
	// Check that e and totient(p, q, r) are coprime.
	pminus1 := new(big.Int).Sub(priv.P, bigOne)
	qminus1 := new(big.Int).Sub(priv.Q, bigOne)
	totient := new(big.Int).Mul(pminus1, qminus1)
	if priv.R != nil {
		rminus1 := new(big.Int).Sub(priv.R, bigOne)
		totient.Mul(totient, rminus1)
	}
	e := big.NewInt(int64(priv.E))
	gcd := new(big.Int)
	x := new(big.Int)
	y := new(big.Int)
	big.GcdInt(gcd, x, y, totient, e)
	if gcd.Cmp(bigOne) != 0 {
		return os.ErrorString("invalid public exponent E")
	}
	// Check that de ≡ 1 (mod totient(p, q, r))
	de := new(big.Int).Mul(priv.D, e)
	de.Mod(de, totient)
	if de.Cmp(bigOne) != 0 {
		return os.ErrorString("invalid private exponent D")
	}
	return nil
}
Esempio n. 21
0
// IsOnCurve returns true if the given (x,y) lies on the curve.
func (curve *Curve) IsOnCurve(x, y *big.Int) bool {
	// y² = x³ - 3x + b
	y2 := new(big.Int).Mul(y, y)
	y2.Mod(y2, curve.P)

	x3 := new(big.Int).Mul(x, x)
	x3.Mul(x3, x)

	threeX := new(big.Int).Lsh(x, 1)
	threeX.Add(threeX, x)

	x3.Sub(x3, threeX)
	x3.Add(x3, curve.B)
	x3.Mod(x3, curve.P)

	return x3.Cmp(y2) == 0
}
Esempio n. 22
0
func (curve *Curve) Add(p1, p2 *Point) *Point {
	fmt.Printf("a")
	if p1 == nil {
		return p2
	}
	if p2 == nil {
		return p1
	}
	lambda_numerator := new(big.Int)
	lambda_denominator := new(big.Int)
	lambda := new(big.Int)
	lambda_numerator.Sub(p2.Y, p1.Y)
	lambda_denominator.Sub(p2.X, p1.X)
	if lambda_denominator.Cmp(BigZero) == -1 { //if Y is negative
		lambda_denominator.Neg(lambda_denominator)
		lambda_denominator.Sub(curve.P, lambda_denominator)
	}
	lambda_denominator, ok := modInverse(lambda_denominator, curve.P)
	if !ok {
		fmt.Printf("Add : Not ok\n")
		return nil
	}
	lambda.Mul(lambda_numerator, lambda_denominator)
	lambda = lambda.Mod(lambda, curve.P)

	p3 := NewPoint()
	p3.X.Exp(lambda, BigTwo, curve.P)
	p3.X.Sub(p3.X, p1.X)
	p3.X.Sub(p3.X, p2.X)
	p3.X = p3.X.Mod(p3.X, curve.P)

	p3.Y.Sub(p1.X, p3.X)
	p3.Y.Mul(lambda, p3.Y)
	p3.Y.Sub(p3.Y, p1.Y)
	p3.Y = p3.Y.Mod(p3.Y, curve.P)

	if p3.X.Cmp(BigZero) == -1 { //if X is negative
		p3.X.Neg(p3.X)
		p3.X.Sub(curve.P, p3.X)
	}
	if p3.Y.Cmp(BigZero) == -1 { //if Y is negative
		p3.Y.Neg(p3.Y)
		p3.Y.Sub(curve.P, p3.Y)
	}
	return p3
}
Esempio n. 23
0
// decrypt performs an RSA decryption, resulting in a plaintext integer. If a
// random source is given, RSA blinding is used.
func decrypt(rand io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err os.Error) {
	// TODO(agl): can we get away with reusing blinds?
	if c.Cmp(priv.N) > 0 {
		err = DecryptionError{}
		return
	}

	var ir *big.Int
	if rand != nil {
		// Blinding enabled. Blinding involves multiplying c by r^e.
		// Then the decryption operation performs (m^e * r^e)^d mod n
		// which equals mr mod n. The factor of r can then be removed
		// by multipling by the multiplicative inverse of r.

		var r *big.Int

		for {
			r, err = randomNumber(rand, priv.N)
			if err != nil {
				return
			}
			if r.Cmp(bigZero) == 0 {
				r = bigOne
			}
			var ok bool
			ir, ok = modInverse(r, priv.N)
			if ok {
				break
			}
		}
		bigE := big.NewInt(int64(priv.E))
		rpowe := new(big.Int).Exp(r, bigE, priv.N)
		c.Mul(c, rpowe)
		c.Mod(c, priv.N)
	}

	m = new(big.Int).Exp(c, priv.D, priv.N)

	if ir != nil {
		// Unblind.
		m.Mul(m, ir)
		m.Mod(m, priv.N)
	}

	return
}
Esempio n. 24
0
func Pow(x *big.Int, y int64) *big.Int {
	var z *big.Int
	if y == 1 {
		return x
	}
	var q, r int64
	q = y / 2
	r = y % 2

	z = Pow(x, q)
	z.Mul(z, z)

	if r == 0 {
		return z
	}
	return z.Mul(z, x)

}
Esempio n. 25
0
func (priv *PrivateKey) Validate() os.Error {
	// Check that the prime factors are actually prime. Note that this is
	// just a sanity check. Since the random witnesses chosen by
	// ProbablyPrime are deterministic, given the candidate number, it's
	// easy for an attack to generate composites that pass this test.
	for _, prime := range priv.Primes {
		if !big.ProbablyPrime(prime, 20) {
			return os.ErrorString("Prime factor is composite")
		}
	}

	// Check that Πprimes == n.
	modulus := new(big.Int).Set(bigOne)
	for _, prime := range priv.Primes {
		modulus.Mul(modulus, prime)
	}
	if modulus.Cmp(priv.N) != 0 {
		return os.ErrorString("invalid modulus")
	}
	// Check that e and totient(Πprimes) are coprime.
	totient := new(big.Int).Set(bigOne)
	for _, prime := range priv.Primes {
		pminus1 := new(big.Int).Sub(prime, bigOne)
		totient.Mul(totient, pminus1)
	}
	e := big.NewInt(int64(priv.E))
	gcd := new(big.Int)
	x := new(big.Int)
	y := new(big.Int)
	big.GcdInt(gcd, x, y, totient, e)
	if gcd.Cmp(bigOne) != 0 {
		return os.ErrorString("invalid public exponent E")
	}
	// Check that de ≡ 1 (mod totient(Πprimes))
	de := new(big.Int).Mul(priv.D, e)
	de.Mod(de, totient)
	if de.Cmp(bigOne) != 0 {
		return os.ErrorString("invalid private exponent D")
	}
	return nil
}
Esempio n. 26
0
func number_multiply(x, y Obj) Obj {
	xfx := (uintptr(unsafe.Pointer(x)) & fixnum_mask) == fixnum_tag
	yfx := (uintptr(unsafe.Pointer(y)) & fixnum_mask) == fixnum_tag
	if xfx && yfx {
		i1 := int64(int(uintptr(unsafe.Pointer(x))))
		i2 := int64(int(uintptr(unsafe.Pointer(y))))
		r := (i1 >> fixnum_shift) * (i2 >> fixnum_shift)
		if r > int64(fixnum_min) && r < int64(fixnum_max) {
			return Make_fixnum(int(r))
		} else {
			return wrap(big.NewInt(r))
		}
	}

	if (!xfx && (uintptr(unsafe.Pointer(x))&heap_mask) != heap_tag) ||
		(!yfx && (uintptr(unsafe.Pointer(y))&heap_mask) != heap_tag) {
		panic("bad type")
	}

	if xfx {
		x = wrap(big.NewInt(int64(fixnum_to_int(x))))
	}
	if yfx {
		y = wrap(big.NewInt(int64(fixnum_to_int(y))))
	}

	switch vx := (*x).(type) {
	case *big.Int:
		var z *big.Int = big.NewInt(0)
		switch vy := (*y).(type) {
		case *big.Int:
			return simpBig(z.Mul(vx, vy))
		case *big.Rat:
			z := big.NewRat(1, 1)
			z.SetInt(vx)
			return simpRat(z.Mul(z, vy))
		default:
			panic("bad type")
		}
	case *big.Rat:
		z := big.NewRat(1, 1)
		switch vy := (*y).(type) {
		case *big.Int:
			z.SetInt(vy)
			return simpRat(z.Mul(vx, z))
		case *big.Rat:
			return simpRat(z.Mul(vx, vy))
		}
	}
	panic("bad type")
}
func (s *Sieve) Primorial(lo, hi uint64) *big.Int {

	if lo > hi {
		return big.NewInt(1)
	}

	if hi-lo < 200 {
		var r, t big.Int
		r.SetInt64(1)
		s.IteratePrimes(lo, hi, func(prime uint64) {
			r.Mul(&r, t.SetInt64(int64(prime)))
			return
		})
		return &r
	}

	h := (lo + hi) / 2
	r := s.Primorial(lo, h)

	return r.Mul(r, s.Primorial(h+1, hi))
}
Esempio n. 28
0
func binaryIntOp(x *big.Int, op token.Token, y *big.Int) interface{} {
	var z big.Int
	switch op {
	case token.ADD:
		return z.Add(x, y)
	case token.SUB:
		return z.Sub(x, y)
	case token.MUL:
		return z.Mul(x, y)
	case token.QUO:
		return z.Quo(x, y)
	case token.REM:
		return z.Rem(x, y)
	case token.AND:
		return z.And(x, y)
	case token.OR:
		return z.Or(x, y)
	case token.XOR:
		return z.Xor(x, y)
	case token.AND_NOT:
		return z.AndNot(x, y)
	case token.SHL:
		panic("unimplemented")
	case token.SHR:
		panic("unimplemented")
	case token.EQL:
		return x.Cmp(y) == 0
	case token.NEQ:
		return x.Cmp(y) != 0
	case token.LSS:
		return x.Cmp(y) < 0
	case token.LEQ:
		return x.Cmp(y) <= 0
	case token.GTR:
		return x.Cmp(y) > 0
	case token.GEQ:
		return x.Cmp(y) >= 0
	}
	panic("unreachable")
}
Esempio n. 29
0
func recursive(in int64, value *big.Int, v vector.IntVector, primeIndex int, primes []*big.Int, winner *big.Int, winner2 *vector.IntVector) {

	if in > 4000000 {

		if value.Cmp(winner) < 0 || winner.Cmp(big.NewInt(-1)) == 0 {
			winner.Set(value)
			*winner2 = v
			fmt.Println(in, winner, *winner2)
			//fmt.Print(in, winner, *winner2, " (")
			//for k, v := range *winner2 {
			//	fmt.Print(primes[k], "**", v, " * ")
			//}
			//fmt.Println(")")
		}

		return
	}

	for i := int64(15); i >= 1; i -= 1 {

		var factor big.Int

		factor.Exp(primes[primeIndex], big.NewInt(i), nil)

		//fmt.Println(factor, i, primes[primeIndex])

		newV := v.Copy()
		newV.Push(int(i))

		var newValue big.Int
		newValue.Mul(value, &factor)

		recursive(in*(2*i+1)-i, &newValue, newV, primeIndex+1, primes, winner, winner2)

	}
}
Esempio n. 30
0
func (curve *Curve) double(p *Point) *Point {
	fmt.Printf("d")
	lambda_numerator := new(big.Int)
	lambda_denominator := new(big.Int)
	lambda := new(big.Int)
	lambda_numerator.Exp(p.X, BigTwo, curve.P)
	lambda_numerator.Mul(lambda_numerator, BigThree)
	lambda_numerator.Add(lambda_numerator, curve.A)
	lambda_denominator.Mul(BigTwo, p.Y)
	lambda_denominator, ok := modInverse(lambda_denominator, curve.P)
	if !ok {
		fmt.Printf("Its not OKAY\n")
		return nil
	}
	lambda.Mul(lambda_numerator, lambda_denominator)
	lambda = lambda.Mod(lambda, curve.P)

	p3 := NewPoint()

	temp := new(big.Int)
	temp2 := new(big.Int)
	//temp3 := new(big.Int)
	//temp4 := new(big.Int)
	//temp5 := new(big.Int)
	//temp6 := new(big.Int)
	p3.X.Sub(temp.Exp(lambda, BigTwo, curve.P), temp2.Mul(BigTwo, p.X))
	p3.X = p3.X.Mod(p3.X, curve.P)

	p3.Y.Sub(p.X, p3.X)
	p3.Y.Mul(p3.Y, lambda)
	p3.Y = p3.Y.Sub(p3.Y, p.Y)
	p3.Y = p3.Y.Mod(p3.Y, curve.P)
	if p3.X.Cmp(BigZero) == -1 { //if X is negative
		p3.X.Neg(p3.X)
		p3.X.Sub(curve.P, p3.X)
	}
	if p3.Y.Cmp(BigZero) == -1 { //if Y is negative
		p3.Y.Neg(p3.Y)
		p3.Y.Sub(curve.P, p3.Y)
	}
	return p3
}