示例#1
2
// bigIntToNetIPv6 is a helper function that correctly returns a net.IP with the
// correctly padded values.
func bigIntToNetIPv6(bi *big.Int) *net.IP {
	x := make(net.IP, IPv6len)
	ipv6Bytes := bi.Bytes()

	// It's possibe for ipv6Bytes to be less than IPv6len bytes in size.  If
	// they are different sizes we to pad the size of response.
	if len(ipv6Bytes) < IPv6len {
		buf := new(bytes.Buffer)
		buf.Grow(IPv6len)

		for i := len(ipv6Bytes); i < IPv6len; i++ {
			if err := binary.Write(buf, binary.BigEndian, byte(0)); err != nil {
				panic(fmt.Sprintf("Unable to pad byte %d of input %v: %v", i, bi, err))
			}
		}

		for _, b := range ipv6Bytes {
			if err := binary.Write(buf, binary.BigEndian, b); err != nil {
				panic(fmt.Sprintf("Unable to preserve endianness of input %v: %v", bi, err))
			}
		}

		ipv6Bytes = buf.Bytes()
	}
	i := copy(x, ipv6Bytes)
	if i != IPv6len {
		panic("IPv6 wrong size")
	}
	return &x
}
示例#2
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
}
示例#3
0
// BigIntToEncodedBytes converts a big integer into its corresponding
// 32 byte little endian representation.
func BigIntToEncodedBytes(a *big.Int) *[32]byte {
	s := new([32]byte)
	if a == nil {
		return s
	}
	// Caveat: a can be longer than 32 bytes.
	aB := a.Bytes()

	// If we have a short byte string, expand
	// it so that it's long enough.
	aBLen := len(aB)
	if aBLen < fieldIntSize {
		diff := fieldIntSize - aBLen
		for i := 0; i < diff; i++ {
			aB = append([]byte{0x00}, aB...)
		}
	}

	for i := 0; i < fieldIntSize; i++ {
		s[i] = aB[i]
	}

	// Reverse the byte string --> little endian after
	// encoding.
	reverse(s)

	return s
}
示例#4
0
// parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
// The OID for the named curve may be provided from another source (such as
// the PKCS8 container) - if it is provided then use this instead of the OID
// that may exist in the EC private key structure.
func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) {
	var privKey ecPrivateKey
	if _, err := asn1.Unmarshal(der, &privKey); err != nil {
		return nil, errors.New("x509: failed to parse EC private key: " + err.Error())
	}
	if privKey.Version != ecPrivKeyVersion {
		return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version)
	}

	var curve elliptic.Curve
	if namedCurveOID != nil {
		curve = namedCurveFromOID(*namedCurveOID)
	} else {
		curve = namedCurveFromOID(privKey.NamedCurveOID)
	}
	if curve == nil {
		return nil, errors.New("x509: unknown elliptic curve")
	}

	k := new(big.Int).SetBytes(privKey.PrivateKey)
	if k.Cmp(curve.Params().N) >= 0 {
		return nil, errors.New("x509: invalid elliptic curve private key value")
	}
	priv := new(ecdsa.PrivateKey)
	priv.Curve = curve
	priv.D = k
	priv.X, priv.Y = curve.ScalarBaseMult(privKey.PrivateKey)

	return priv, nil
}
示例#5
0
文件: dec.go 项目: 40a/bootkube
func factor2(n *big.Int) int {
	// could be improved for large factors
	f := 0
	for ; n.Bit(f) == 0; f++ {
	}
	return f
}
示例#6
0
func factorial(x *big.Int) *big.Int {
	n := big.NewInt(1)
	if x.Cmp(big.NewInt(0)) == 0 {
		return n
	}
	return n.Mul(x, factorial(n.Sub(x, n)))
}
示例#7
0
// returns a formatted MIP mapped key by adding prefix, canonical number and level
//
// ex. fn(98, 1000) = (prefix || 1000 || 0)
func mipmapKey(num, level uint64) []byte {
	lkey := make([]byte, 8)
	binary.BigEndian.PutUint64(lkey, level)
	key := new(big.Int).SetUint64(num / level * level)

	return append(mipmapPre, append(lkey, key.Bytes()...)...)
}
示例#8
0
// Big max
//
// Returns the maximum size big integer
func BigMax(x, y *big.Int) *big.Int {
	if x.Cmp(y) < 0 {
		return y
	}

	return x
}
示例#9
0
文件: pool.go 项目: dakk/ethpool.py
func getWorkPackage(difficulty *big.Int) string {

	if currWork == nil {
		return getErrorResponse("Current work unavailable")
	}

	// Our response object
	response := &ResponseArray{
		Id:      currWork.Id,
		Jsonrpc: currWork.Jsonrpc,
		Result:  currWork.Result[:],
	}

	// Calculte requested difficulty
	diff := new(big.Int).Div(pow256, difficulty)
	diffBytes := string(common.ToHex(diff.Bytes()))

	// Adjust the difficulty for the miner
	response.Result[2] = diffBytes

	// Convert respone object to JSON
	b, _ := json.Marshal(response)

	return string(b)

}
示例#10
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)
	}
}
示例#11
0
// baseCheck checks for any stack error underflows
func baseCheck(op OpCode, stack *stack, gas *big.Int) error {
	// PUSH and DUP are a bit special. They all cost the same but we do want to have checking on stack push limit
	// PUSH is also allowed to calculate the same price for all PUSHes
	// DUP requirements are handled elsewhere (except for the stack limit check)
	if op >= PUSH1 && op <= PUSH32 {
		op = PUSH1
	}
	if op >= DUP1 && op <= DUP16 {
		op = DUP1
	}

	if r, ok := _baseCheck[op]; ok {
		err := stack.require(r.stackPop)
		if err != nil {
			return err
		}

		if r.stackPush > 0 && stack.len()-r.stackPop+r.stackPush > int(params.StackLimit.Int64()) {
			return fmt.Errorf("stack limit reached %d (%d)", stack.len(), params.StackLimit.Int64())
		}

		gas.Add(gas, r.gas)
	}
	return nil
}
示例#12
0
func bigAdd(IntSlice []big.Int) *big.Int {
	var sum *big.Int = big.NewInt(0)
	for i := 0; i < len(IntSlice); i++ {
		sum.Add(sum, &IntSlice[i])
	}
	return sum
}
示例#13
0
文件: amount.go 项目: robcat/ripple
func (v *Value) String() string {
	if v.IsZero() {
		return "0"
	}
	if v.Native && v.IsScientific() {
		value := strconv.FormatUint(v.Num, 10)
		offset := strconv.FormatInt(v.Offset, 10)
		if v.Negative {
			return "-" + value + "e" + offset
		}
		return value + "e" + offset
	}
	value := big.NewInt(int64(v.Num))
	if v.Negative {
		value.Neg(value)
	}
	var offset *big.Int
	if v.Native {
		offset = big.NewInt(-6)
	} else {
		offset = big.NewInt(v.Offset)
	}
	exp := offset.Exp(bigTen, offset.Neg(offset), nil)
	rat := big.NewRat(0, 1).SetFrac(value, exp)
	left := rat.FloatString(0)
	if rat.IsInt() {
		return left
	}
	length := len(left)
	if v.Negative {
		length -= 1
	}
	return strings.TrimRight(rat.FloatString(32-length), "0")
}
示例#14
0
func (c *StateObject) GetInstr(pc *big.Int) *common.Value {
	if int64(len(c.code)-1) < pc.Int64() {
		return common.NewValue(0)
	}

	return common.NewValueFromBytes([]byte{c.code[pc.Int64()]})
}
示例#15
0
func (p *PrivateKeys) addRemoteKey(remote []byte, clientPacket []byte, serverPacket []byte) SharedKeys {
	remote_be := new(big.Int)
	remote_be.SetBytes(remote)
	shared_key := powm(remote_be, p.privateKey, p.prime)

	data := make([]byte, 0, 100)
	mac := hmac.New(sha1.New, shared_key.Bytes())

	for i := 1; i < 6; i++ {
		mac.Write(clientPacket)
		mac.Write(serverPacket)
		mac.Write([]byte{uint8(i)})
		data = append(data, mac.Sum(nil)...)
		mac.Reset()
	}

	mac = hmac.New(sha1.New, data[0:0x14])
	mac.Write(clientPacket)
	mac.Write(serverPacket)

	return SharedKeys{
		challenge: mac.Sum(nil),
		sendKey:   data[0x14:0x34],
		recvKey:   data[0x34:0x54],
	}
}
示例#16
0
func SumOfBigIntDigits(n *big.Int) int64 {
	sum := int64(0)
	for _, v := range n.String() {
		sum += int64(RuneToInt(v))
	}
	return sum
}
示例#17
0
// CompactToBig converts a compact representation of a whole number N to an
// unsigned 32-bit number.  The representation is similar to IEEE754 floating
// point numbers.
//
// Like IEEE754 floating point, there are three basic components: the sign,
// the exponent, and the mantissa.  They are broken out as follows:
//
//	* the most significant 8 bits represent the unsigned base 256 exponent
// 	* bit 23 (the 24th bit) represents the sign bit
//	* the least significant 23 bits represent the mantissa
//
//	-------------------------------------------------
//	|   Exponent     |    Sign    |    Mantissa     |
//	-------------------------------------------------
//	| 8 bits [31-24] | 1 bit [23] | 23 bits [22-00] |
//	-------------------------------------------------
//
// The formula to calculate N is:
// 	N = (-1^sign) * mantissa * 256^(exponent-3)
//
// This compact form is only used in bitcoin to encode unsigned 256-bit numbers
// which represent difficulty targets, thus there really is not a need for a
// sign bit, but it is implemented here to stay consistent with bitcoind.
func CompactToBig(compact uint32) *big.Int {
	// Extract the mantissa, sign bit, and exponent.
	mantissa := compact & 0x007fffff
	isNegative := compact&0x00800000 != 0
	exponent := uint(compact >> 24)

	// Since the base for the exponent is 256, the exponent can be treated
	// as the number of bytes to represent the full 256-bit number.  So,
	// treat the exponent as the number of bytes and shift the mantissa
	// right or left accordingly.  This is equivalent to:
	// N = mantissa * 256^(exponent-3)
	var bn *big.Int
	if exponent <= 3 {
		mantissa >>= 8 * (3 - exponent)
		bn = big.NewInt(int64(mantissa))
	} else {
		bn = big.NewInt(int64(mantissa))
		bn.Lsh(bn, 8*(exponent-3))
	}

	// Make it negative if the sign bit is set.
	if isNegative {
		bn = bn.Neg(bn)
	}

	return bn
}
示例#18
0
func TestDecodeBigNumber(t *testing.T) {
	var value big.Int

	value.SetUint64(^uint64(0))

	value.Mul(&value, big.NewInt(32))

	b := bytes.Buffer{}
	e := NewEncoder(&b)

	err := e.Encode(value)
	if err != nil {
		t.Fatal(err)
	}

	t.Log(hex.Dump(b.Bytes()))

	d := NewDecoder(&b)

	found, err := d.DecodeNext()
	if err != nil {
		t.Fatal(err)
	}
	i := found.(big.Int)

	if i.Cmp(&value) != 0 {
		t.Fatalf("expected %v but %v found", value, found)
	}
}
示例#19
0
// Big min
//
// Returns the minimum size big integer
func BigMin(x, y *big.Int) *big.Int {
	if x.Cmp(y) > 0 {
		return y
	}

	return x
}
示例#20
0
// GenNV generates the signature blind/nonce. Copied from src/crypto/elliptic/elliptic.go GenerateKey
func (curve Curve) GenNV() (nv []byte, err error) {
	var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f}
	var x *big.Int
	var loopcount int
	bitSize := curve.Curve.Params().BitSize
	byteLen := (bitSize + 7) >> 3
	nv = make([]byte, byteLen)
	for x == nil {
		if loopcount > MaxLoopCount {
			return nil, ErrMaxLoop
		}
		loopcount++
		_, err = io.ReadFull(curve.Rand, nv)
		if err != nil {
			return
		}
		// We have to mask off any excess bits in the case that the size of the
		// underlying field is not a whole number of bytes.
		nv[0] &= mask[bitSize%8]
		// This is because, in tests, rand will return all zeros and we don't
		// want to get the point at infinity and loop forever.
		nv[1] ^= 0x42
		x, _ = curve.Curve.ScalarBaseMult(nv)
		if x.Cmp(big.NewInt(0)) == 0 { // This cannot really happen ever
			x = nil
		}
	}
	return
}
示例#21
0
文件: rsa.go 项目: serge-hulne/golang
// 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)
	}
}
示例#22
0
文件: base58.go 项目: robcat/ripple
// Base58Encode encodes a byte slice to a modified base58 string.
func Base58Encode(b []byte, alphabet string) string {
	x := new(big.Int)
	x.SetBytes(b)

	answer := make([]byte, 0)
	for x.Cmp(bigZero) > 0 {
		mod := new(big.Int)
		x.DivMod(x, bigRadix, mod)
		answer = append(answer, alphabet[mod.Int64()])
	}

	// leading zero bytes
	for _, i := range b {
		if i != 0 {
			break
		}
		answer = append(answer, alphabet[0])
	}

	// reverse
	alen := len(answer)
	for i := 0; i < alen/2; i++ {
		answer[i], answer[alen-1-i] = answer[alen-1-i], answer[i]
	}

	return string(answer)
}
示例#23
0
func (ka *dheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
	var q *big.Int
	if p := config.Bugs.DHGroupPrime; p != nil {
		ka.p = p
		ka.g = big.NewInt(2)
		q = p
	} else {
		// 2048-bit MODP Group with 256-bit Prime Order Subgroup (RFC
		// 5114, Section 2.3)
		ka.p, _ = new(big.Int).SetString("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597", 16)
		ka.g, _ = new(big.Int).SetString("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659", 16)
		q, _ = new(big.Int).SetString("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3", 16)
	}

	var err error
	ka.xOurs, err = rand.Int(config.rand(), q)
	if err != nil {
		return nil, err
	}
	yOurs := new(big.Int).Exp(ka.g, ka.xOurs, ka.p)

	// http://tools.ietf.org/html/rfc5246#section-7.4.3
	pBytes := ka.p.Bytes()
	gBytes := ka.g.Bytes()
	yBytes := yOurs.Bytes()
	serverDHParams := make([]byte, 0, 2+len(pBytes)+2+len(gBytes)+2+len(yBytes))
	serverDHParams = append(serverDHParams, byte(len(pBytes)>>8), byte(len(pBytes)))
	serverDHParams = append(serverDHParams, pBytes...)
	serverDHParams = append(serverDHParams, byte(len(gBytes)>>8), byte(len(gBytes)))
	serverDHParams = append(serverDHParams, gBytes...)
	serverDHParams = append(serverDHParams, byte(len(yBytes)>>8), byte(len(yBytes)))
	serverDHParams = append(serverDHParams, yBytes...)

	return ka.auth.signParameters(config, cert, clientHello, hello, serverDHParams)
}
示例#24
0
文件: marshal.go 项目: Gibheer/gocql
// 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
}
示例#25
0
func (calc Calculator) threeValueCalculation(a, b, c *big.Int, operator string) *big.Int {
	switch operator {
	case "&":
		return a.Exp(a, b, c)
	}
	return nil
}
示例#26
0
// number = int_lit [ "p" int_lit ] .
//
func (p *gcParser) parseNumber() Const {
	// mantissa
	sign, val := p.parseInt()
	mant, ok := new(big.Int).SetString(sign+val, 10)
	assert(ok)

	if p.lit == "p" {
		// exponent (base 2)
		p.next()
		sign, val = p.parseInt()
		exp64, err := strconv.ParseUint(val, 10, 0)
		if err != nil {
			p.error(err)
		}
		exp := uint(exp64)
		if sign == "-" {
			denom := big.NewInt(1)
			denom.Lsh(denom, exp)
			return Const{new(big.Rat).SetFrac(mant, denom)}
		}
		if exp > 0 {
			mant.Lsh(mant, exp)
		}
		return Const{new(big.Rat).SetInt(mant)}
	}

	return Const{mant}
}
示例#27
0
// mulBigPow10 returns 10 * x ^ n
func mulBigPow10(x *big.Int, n int64) *big.Int {
	if x.Sign() == 0 || n <= 0 {
		return x
	}
	b := bigPow10(n)
	return new(big.Int).Mul(x, &b)
}
示例#28
0
文件: ecdsa.go 项目: rgmabs19357/gcc
// Sign signs an arbitrary length hash (which should be the result of hashing a
// larger message) using the private key, priv. It returns the signature as a
// pair of integers. The security of the private key depends on the entropy of
// rand.
func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
	// See [NSA] 3.4.1
	c := priv.PublicKey.Curve
	N := c.Params().N

	var k, kInv *big.Int
	for {
		for {
			k, err = randFieldElement(c, rand)
			if err != nil {
				r = nil
				return
			}

			kInv = new(big.Int).ModInverse(k, N)
			r, _ = priv.Curve.ScalarBaseMult(k.Bytes())
			r.Mod(r, N)
			if r.Sign() != 0 {
				break
			}
		}

		e := hashToInt(hash, c)
		s = new(big.Int).Mul(priv.D, r)
		s.Add(s, e)
		s.Mul(s, kInv)
		s.Mod(s, N)
		if s.Sign() != 0 {
			break
		}
	}

	return
}
示例#29
0
// Implements the heat.Callback.Dead method, monitoring the death events of
// topic member nodes.
func (o *Overlay) Dead(id *big.Int) {
	// Split the id into topic and node parts
	topic := new(big.Int).Rsh(id, uint(config.PastrySpace))
	node := new(big.Int).Sub(id, new(big.Int).Lsh(topic, uint(config.PastrySpace)))

	log.Printf("scribe: %v topic member death report: %v.", o.pastry.Self(), node)

	o.lock.RLock()
	top, ok := o.topics[topic.String()]
	o.lock.RUnlock()
	if !ok {
		log.Printf("scribe: topic %v already dead.", topic)
		return
	}
	// Depending on whether it was the topic parent or a child reown or unsub
	parent := top.Parent()
	if parent != nil && parent.Cmp(node) == 0 {
		// Make sure it's out of the heartbeat mechanism
		if err := o.heart.Unmonitor(id); err != nil {
			log.Printf("scribe: failed to unmonitor dead parent: %v.", err)
		}
		// Reassign topic rendes-vous point
		top.Reown(nil)
	} else {
		if err := o.handleUnsubscribe(node, topic); err != nil {
			log.Printf("scribe: failed to unsubscribe dead node: %v.", err)
		}
	}
}
示例#30
0
func SumOfBigInts(nums []*big.Int) *big.Int {
	var sum *big.Int = big.NewInt(0)
	for _, i := range nums {
		sum.Add(sum, i)
	}
	return sum
}