Example #1
0
// zForAffine returns a Jacobian Z value for the affine point (x, y). If x and
// y are zero, it assumes that they represent the point at infinity because (0,
// 0) is not on the any of the curves handled here.
func zForAffine(x, y *big.Int) *big.Int {
	z := new(big.Int)
	if x.Sign() != 0 || y.Sign() != 0 {
		z.SetInt64(1)
	}
	return z
}
Example #2
0
func (z *Polynomial) Mul(x, y *Polynomial) *Polynomial {
	var zCoeffs *big.Int
	if z == x || z == y {
		// Ensure that we do not modify z if it's a parameter.
		zCoeffs = new(big.Int)
	} else {
		zCoeffs = &z.coeffs
		zCoeffs.SetInt64(0)
	}

	small, large := x, y
	if y.degree < x.degree {
		small, large = y, x
	}

	// Walk through small coeffs, shift large by the corresponding amount,
	// and accumulate in z.
	coeffs := new(big.Int).Set(&small.coeffs)
	zero := new(big.Int)
	for coeffs.Cmp(zero) > 0 {
		deg := calcDegree(coeffs)
		factor := new(big.Int).Lsh(&large.coeffs, deg)
		zCoeffs.Xor(zCoeffs, factor)

		// Prepare for next iteration.
		coeffs.SetBit(coeffs, int(deg), 0)
	}

	z.degree = calcDegree(zCoeffs)
	z.coeffs = *zCoeffs
	return z
}
Example #3
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)
	}
}
Example #4
0
func DecodeBase58(ba []byte) []byte {
	if len(ba) == 0 {
		return nil
	}

	x := new(big.Int)
	y := big.NewInt(58)
	z := new(big.Int)
	for _, b := range ba {
		v := strings.IndexRune(base58, rune(b))
		z.SetInt64(int64(v))
		x.Mul(x, y)
		x.Add(x, z)
	}
	xa := x.Bytes()

	// Restore leading zeros
	i := 0
	for i < len(ba) && ba[i] == '1' {
		i++
	}
	ra := make([]byte, i+len(xa))
	copy(ra[i:], xa)
	return ra
}
Example #5
0
// Rat returns the rational number representation of z.
// If x is non-nil, Rat stores the result in x instead of
// allocating a new Rat.
func (z *Decimal) Rat(x *big.Rat) *big.Rat {
	// TODO(eric):
	// We use big.Ints here when technically we could use our
	// int64 with big.Rat's SetInt64 methoz.
	// I'm not sure if it'll be an optimization or not.
	var num, denom big.Int
	if z.compact != overflown {
		c := big.NewInt(z.compact)
		if z.scale >= 0 {
			num.Set(c)
			denom.Set(mulBigPow10(oneInt, z.scale))
		} else {
			num.Set(mulBigPow10(c, -z.scale))
			denom.SetInt64(1)
		}
	} else {
		if z.scale >= 0 {
			num.Set(&z.mantissa)
			denom.Set(mulBigPow10(oneInt, z.scale))
		} else {
			num.Set(mulBigPow10(&z.mantissa, -z.scale))
			denom.SetInt64(1)
		}
	}
	if x != nil {
		return x.SetFrac(&num, &denom)
	}
	return new(big.Rat).SetFrac(&num, &denom)
}
Example #6
0
func main() {

	var iban string
	var r, s, t, st []string
	u := new(big.Int)
	v := new(big.Int)
	w := new(big.Int)

	iban = "GB82 TEST 1234 5698 7654 32"
	r = strings.Split(iban, " ")
	s = strings.Split(r[0], "")
	t = strings.Split(r[1], "")

	st = []string{strconv.Itoa(sCode[t[0]]),
		strconv.Itoa(sCode[t[1]]),
		strconv.Itoa(sCode[t[2]]),
		strconv.Itoa(sCode[t[3]]),
		strings.Join(r[2:6], ""),
		strconv.Itoa(sCode[s[0]]),
		strconv.Itoa(sCode[s[1]]),
		strings.Join(s[2:4], ""),
	}

	u.SetString(strings.Join(st, ""), 10)
	v.SetInt64(97)
	w.Mod(u, v)

	if w.Uint64() == 1 && lCode[strings.Join(s[0:2], "")] == len(strings.Join(r, "")) {
		fmt.Printf("IBAN %s looks good!\n", iban)
	} else {
		fmt.Printf("IBAN %s looks wrong!\n", iban)
	}
}
Example #7
0
File: int.go Project: Liamsi/crypto
// 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
}
Example #8
0
// BigInt sets all bytes in the passed big int to zero and then sets the
// value to 0.  This differs from simply setting the value in that it
// specifically clears the underlying bytes whereas simply setting the value
// does not.  This is mostly useful to forcefully clear private keys.
func BigInt(x *big.Int) {
	b := x.Bits()
	for i := range b {
		b[i] = 0
	}
	x.SetInt64(0)
}
Example #9
0
func (ps *Swing) OddSwing(z *big.Int, k uint) *big.Int {
	if k < uint(len(SmallOddSwing)) {
		return z.SetInt64(SmallOddSwing[k])
	}
	rootK := xmath.FloorSqrt(k)
	ps.factors = ps.factors[:0] // reset length, reusing existing capacity
	ps.Sieve.Iterate(3, uint64(rootK), func(p uint64) (terminate bool) {
		q := uint64(k) / p
		for q > 0 {
			if q&1 == 1 {
				ps.factors = append(ps.factors, p)
			}
			q /= p
		}
		return
	})
	ps.Sieve.Iterate(uint64(rootK+1), uint64(k/3), func(p uint64) (term bool) {
		if (uint64(k) / p & 1) == 1 {
			ps.factors = append(ps.factors, p)
		}
		return
	})
	ps.Sieve.Iterate(uint64(k/2+1), uint64(k), func(p uint64) (term bool) {
		ps.factors = append(ps.factors, p)
		return
	})
	return xmath.Product(z, ps.factors)
}
Example #10
0
// EncodeBigInt returns the base62 encoding of an arbitrary precision integer
func (e *Encoding) EncodeBigInt(n *big.Int) string {
	var (
		b    = make([]byte, 0)
		rem  = new(big.Int)
		bse  = new(big.Int)
		zero = new(big.Int)
	)
	bse.SetInt64(base)
	zero.SetInt64(0)

	// Progressively divide by base, until we hit zero
	// store remainder each time
	// Prepend as an additional character is the higher power
	for n.Cmp(zero) == 1 {
		n, rem = n.DivMod(n, bse, rem)
		b = append([]byte{e.encode[rem.Int64()]}, b...)
	}

	s := string(b)
	if e.padding > 0 {
		s = e.pad(s, e.padding)
	}

	return s
}
Example #11
0
func main() {
	out, _ := os.Create("485.out")
	defer out.Close()

	for !done {
		var one big.Int
		one.SetInt64(1)
		p = append(p, one)
		l := len(p)

		fmt.Fprint(out, &p[l-1])
		for i := l - 2; i > 0; i-- {
			p[i].Add(&p[i], &p[i-1])
			fmt.Fprintf(out, " %v", &p[i])

			s = fmt.Sprint(&p[i])
			if len(s) > MAX {
				done = true
				break
			}
		}

		if !done && l > 1 {
			fmt.Fprintf(out, " %v", &p[0])
		}
		fmt.Fprintln(out)
	}
}
Example #12
0
// Decode decodes a modified base58 string to a byte slice.
func Decode(b string) []byte {
	answer := big.NewInt(0)
	j := big.NewInt(1)

	scratch := new(big.Int)
	for i := len(b) - 1; i >= 0; i-- {
		tmp := b58[b[i]]
		if tmp == 255 {
			return []byte("")
		}
		scratch.SetInt64(int64(tmp))
		scratch.Mul(j, scratch)
		answer.Add(answer, scratch)
		j.Mul(j, bigRadix)
	}

	tmpval := answer.Bytes()

	var numZeros int
	for numZeros = 0; numZeros < len(b); numZeros++ {
		if b[numZeros] != alphabetIdx0 {
			break
		}
	}
	flen := numZeros + len(tmpval)
	val := make([]byte, flen, flen)
	copy(val[numZeros:], tmpval)

	return val
}
Example #13
0
func (h *hasher) GetLoggregatorServerForAppId(appId string) string {
	var id, numberOfItems big.Int
	id.SetBytes([]byte(appId))
	numberOfItems.SetInt64(int64(len(h.items)))

	id.Mod(&id, &numberOfItems)
	return h.items[id.Int64()]
}
Example #14
0
func factorial(n int) string {
	var res big.Int
	res.SetInt64(1)
	for i := 1; i <= n; i++ {
		res.Mul(&res, big.NewInt(int64(i)))
	}
	return res.String()
}
Example #15
0
// nonceRFC6979 is a local instatiation of deterministic nonce generation
// by the standards of RFC6979.
func nonceRFC6979(privkey []byte, hash []byte, extra []byte,
	version []byte) []byte {
	pkD := new(big.Int).SetBytes(privkey)
	defer pkD.SetInt64(0)
	bigK := secp256k1.NonceRFC6979(pkD, hash, extra, version)
	defer bigK.SetInt64(0)
	k := BigIntToEncodedBytes(bigK)
	return k[:]
}
Example #16
0
File: p020.go Project: uluyol/misc
func main() {
	n := new(big.Int).SetInt64(int64(1))
	t := new(big.Int)
	for i := int64(1); i <= 100; i++ {
		t.SetInt64(i)
		n.Mul(n, t)
	}
	fmt.Printf("Problem 20: %d\n", SumOfBigIntDigits(n))
}
Example #17
0
File: ecdsa.go Project: decred/dcrd
// nonceRFC6979 is a local instatiation of deterministic nonce generation
// by the standards of RFC6979.
func nonceRFC6979(curve *TwistedEdwardsCurve, privkey []byte, hash []byte,
	extra []byte, version []byte) []byte {
	pkD := new(big.Int).SetBytes(privkey)
	defer pkD.SetInt64(0)
	bigK := NonceRFC6979(curve, pkD, hash, extra, version)
	defer bigK.SetInt64(0)
	k := BigIntToEncodedBytesNoReverse(bigK)
	return k[:]
}
Example #18
0
func f(n int) big.Int {
	var r, t big.Int
	r.SetInt64(1)
	for i := 2; i <= n; i++ {
		t.SetInt64(int64(i))
		r.Mul(&r, &t)
	}
	return r
}
Example #19
0
func TestModPow2(t *testing.T) {
	const N = 1e3
	data := []struct{ e, m uint32 }{
		// e == 0 -> x == 0
		{0, 2},
		{0, 3},
		{0, 4},

		{1, 2},
		{1, 3},
		{1, 4},
		{1, 5},

		{2, 2},
		{2, 3},
		{2, 4},
		{2, 5},

		{3, 2},
		{3, 3},
		{3, 4},
		{3, 5},
		{3, 6},
		{3, 7},
		{3, 8},
		{3, 9},

		{4, 2},
		{4, 3},
		{4, 4},
		{4, 5},
		{4, 6},
		{4, 7},
		{4, 8},
		{4, 9},
	}

	var got big.Int
	f := func(e, m uint32) {
		x := ModPow2(e, m)
		exp := ModPow(2, e, m)
		got.SetInt64(0)
		got.SetBit(&got, int(x), 1)
		if got.Cmp(exp) != 0 {
			t.Fatalf("\ne %d, m %d\ng: %s\ne: %s", e, m, &got, exp)
		}
	}

	for _, v := range data {
		f(v.e, v.m)
	}

	rg, _ := mathutil.NewFC32(2, 1<<10, true)
	for i := 0; i < N; i++ {
		f(uint32(rg.Next()), uint32(rg.Next()))
	}
}
Example #20
0
// Sets q = x / y.  Returns q and the remainder r.
func (q *Polynomial) Div(x, y *Polynomial) (*Polynomial, *Polynomial) {
	zero := new(big.Int)
	if y.degree == 0 {
		// y is 0 or 1.
		if y.coeffs.Cmp(zero) == 0 {
			panic("divide by 0")
		}
		q.Set(x)
		r := NewPolynomial(0, zero)
		return q, r
	}
	if x.degree == 0 {
		// 0 / y = 0.
		if x.coeffs.Cmp(zero) == 0 {
			q.degree = 0
			q.coeffs.Set(zero)

			r := NewPolynomial(0, zero)
			return q, r
		}
	}

	var qCoeffs *big.Int
	// Be careful not to modify any of the input parameters.
	if q == x || q == y {
		qCoeffs = new(big.Int)
	} else {
		// Re-use q to minimize allocations.
		qCoeffs = &q.coeffs
		qCoeffs.SetInt64(0)
	}

	// The remainder, which is x initially.
	r := new(Polynomial).Set(x)

	// This is just elementary long division in GF(2).
	for r.degree >= y.degree {
		// s(x) = y(x) * x^{shift_len}
		// Then, r'(x) = r(x) - s(x)

		// Record the new component in the quotient.
		shiftLen := int(r.degree - y.degree)
		qCoeffs.SetBit(qCoeffs, shiftLen, 1)

		sCoeffs := new(big.Int).Lsh(&y.coeffs, uint(shiftLen))

		// Determine r'(x) by subtracting s(x) from the remainder.
		r.coeffs.Xor(&r.coeffs, sCoeffs)
		r.degree = calcDegree(&r.coeffs)
	}
	// r.degree < y.degree at this point.

	q.coeffs = *qCoeffs
	q.degree = calcDegree(&q.coeffs)
	return q, r
}
Example #21
0
// UnaryOp does a unary operation on a unary expression.
func UnaryOp(op scan.Type, y Value, prec uint) Value {
	switch op {
	case scan.Plus:
		switch y.(type) {
		case unknownVal, int64Val, intVal:
			return y
		}

	case scan.Minus:
		switch y := y.(type) {
		case unknownVal:
			return y
		case int64Val:
			if z := -y; z != y {
				return z // no overflow
			}
			return normInt(new(big.Int).Neg(big.NewInt(int64(y))))
		case intVal:
			return normInt(new(big.Int).Neg(y.val))
		}

	case scan.Negate:
		var z big.Int
		switch y := y.(type) {
		case unknownVal:
			return y
		case int64Val:
			z.Not(big.NewInt(int64(y)))
		case intVal:
			z.Not(y.val)
		default:
			goto Error
		}
		return normInt(&z)

	case scan.Not:
		switch y := y.(type) {
		case unknownVal:
			return y
		case int64Val:
			if y == 0 {
				return int64Val(1)
			}
			return int64Val(0)
		case intVal:
			z := new(big.Int).SetInt64(0)
			if y.val.Sign() == 0 {
				z.SetInt64(1)
			}
			return normInt(z)
		}
	}

Error:
	panic(fmt.Sprintf("invalid unary operation %s%v", op, y))
}
Example #22
0
// ProductInt64 sets z to the product of the integers in s and returns z.
func ProductInt64(z *big.Int, s []int64) *big.Int {
	if len(s) == 0 {
		return z.SetInt64(1)
	}
	bs := make([]*big.Int, len(s))
	for i, v := range s {
		bs[i] = big.NewInt(v)
	}
	return Product(z, bs)
}
Example #23
0
func randint(max int) int {
	var bmax big.Int
	bmax.SetInt64(int64(max))
	n, err := rand.Int(rand.Reader, &bmax)
	if err != nil {
		log.Printf("unable to produce random number: %v", err)
		os.Exit(1)
	}
	return int(n.Int64())
}
Example #24
0
// BigInt sets all bytes in the passed big int to zero and then sets the
// value to 0.  This differs from simply setting the value in that it
// specifically clears the underlying bytes whereas simply setting the value
// does not.  This is mostly useful to forcefully clear private keys.
func BigInt(x *big.Int) {
	b := x.Bits()
	z := [16]big.Word{}
	n := uint(copy(b, z[:]))
	for n < uint(len(b)) {
		copy(b[n:], b[:n])
		n <<= 1
	}
	x.SetInt64(0)
}
func sqrt(n *big.Int) *big.Int {
	a := new(big.Int)
	for b := new(big.Int).Set(n); ; {
		a.Set(b)
		b.Rsh(b.Add(b.Quo(n, a), a), 1)
		if b.Cmp(a) >= 0 {
			return a
		}
	}
	return a.SetInt64(0)
}
Example #26
0
func factorial(n int64) *big.Int {
	if n < 0 {
		return nil
	}
	r := big.NewInt(1)
	var f big.Int
	for i := int64(2); i <= n; i++ {
		r.Mul(r, f.SetInt64(i))
	}
	return r
}
Example #27
0
func powBigInt(base int64, exp int64) *big.Int {
	big_base := new(big.Int)
	big_base.SetInt64(base)

	big_exp := new(big.Int)
	big_exp.SetInt64(exp)

	res := new(big.Int)
	res.Exp(big_base, big_exp, nil)
	return res
}
Example #28
0
// schnorrPartialSign creates a partial Schnorr signature which may be combined
// with other Schnorr signatures to create a valid signature for a group pubkey.
func schnorrPartialSign(curve *secp256k1.KoblitzCurve, msg []byte, priv []byte,
	privNonce []byte, pubSum *secp256k1.PublicKey,
	hashFunc func([]byte) []byte) (*Signature, error) {
	// Sanity checks.
	if len(msg) != scalarSize {
		str := fmt.Sprintf("wrong size for message (got %v, want %v)",
			len(msg), scalarSize)
		return nil, schnorrError(ErrBadInputSize, str)
	}
	if len(priv) != scalarSize {
		str := fmt.Sprintf("wrong size for privkey (got %v, want %v)",
			len(priv), scalarSize)
		return nil, schnorrError(ErrBadInputSize, str)
	}
	if len(privNonce) != scalarSize {
		str := fmt.Sprintf("wrong size for privnonce (got %v, want %v)",
			len(privNonce), scalarSize)
		return nil, schnorrError(ErrBadInputSize, str)
	}
	if pubSum == nil {
		str := fmt.Sprintf("nil pubkey")
		return nil, schnorrError(ErrInputValue, str)
	}

	privBig := new(big.Int).SetBytes(priv)
	if privBig.Cmp(bigZero) == 0 {
		str := fmt.Sprintf("priv scalar is zero")
		return nil, schnorrError(ErrInputValue, str)
	}
	if privBig.Cmp(curve.N) >= 0 {
		str := fmt.Sprintf("priv scalar is out of bounds")
		return nil, schnorrError(ErrInputValue, str)
	}
	privBig.SetInt64(0)

	privNonceBig := new(big.Int).SetBytes(privNonce)
	if privNonceBig.Cmp(bigZero) == 0 {
		str := fmt.Sprintf("privNonce scalar is zero")
		return nil, schnorrError(ErrInputValue, str)
	}
	if privNonceBig.Cmp(curve.N) >= 0 {
		str := fmt.Sprintf("privNonce scalar is out of bounds")
		return nil, schnorrError(ErrInputValue, str)
	}
	privNonceBig.SetInt64(0)

	if !curve.IsOnCurve(pubSum.GetX(), pubSum.GetY()) {
		str := fmt.Sprintf("public key sum is off curve")
		return nil, schnorrError(ErrInputValue, str)
	}

	return schnorrSign(curve, msg, priv, privNonce, pubSum.GetX(),
		pubSum.GetY(), hashFunc)
}
Example #29
0
func main() {
	var a, b big.Int
	b.SetInt64(1)

	var i int
	for i = 0; len(a.String()) < 1000; i++ {
		a, b = b, a
		b.Add(&a, &b)
	}
	fmt.Println(i)
}
Example #30
0
func Euler048b() Result {
	sum := new(big.Int)
	pow := new(big.Int)
	num := new(big.Int)
	for i := int64(1); i < 1001; i++ {
		num.SetInt64(i)
		pow.Exp(num, num, nil)
		sum.Add(sum, pow)
	}
	str := sum.String()
	return str[len(str)-10 : len(str)]
}