Example #1
0
// powerOffset computes the offset by (n + 2^exp) % (2^mod)
func powerOffset(id []byte, exp int, mod int) []byte {
	// Copy the existing slice
	off := make([]byte, len(id))
	copy(off, id)

	// Convert the ID to a bigint
	idInt := big.Int{}
	idInt.SetBytes(id)

	// Get the offset
	two := big.NewInt(2)
	offset := big.Int{}
	offset.Exp(two, big.NewInt(int64(exp)), nil)

	// Sum
	sum := big.Int{}
	sum.Add(&idInt, &offset)

	// Get the ceiling
	ceil := big.Int{}
	ceil.Exp(two, big.NewInt(int64(mod)), nil)

	// Apply the mod
	idInt.Mod(&sum, &ceil)

	// Add together
	return idInt.Bytes()
}
Example #2
0
func (c *Conversation) processSMP1(mpis []*big.Int) error {
	if len(mpis) != 6 {
		return errors.New("otr: incorrect number of arguments in SMP1 message")
	}
	g2a := mpis[0]
	c2 := mpis[1]
	d2 := mpis[2]
	g3a := mpis[3]
	c3 := mpis[4]
	d3 := mpis[5]
	h := sha256.New()

	r := new(big.Int).Exp(g, d2, p)
	s := new(big.Int).Exp(g2a, c2, p)
	r.Mul(r, s)
	r.Mod(r, p)
	t := new(big.Int).SetBytes(hashMPIs(h, 1, r))
	if c2.Cmp(t) != 0 {
		return errors.New("otr: ZKP c2 incorrect in SMP1 message")
	}
	r.Exp(g, d3, p)
	s.Exp(g3a, c3, p)
	r.Mul(r, s)
	r.Mod(r, p)
	t.SetBytes(hashMPIs(h, 2, r))
	if c3.Cmp(t) != 0 {
		return errors.New("otr: ZKP c3 incorrect in SMP1 message")
	}

	c.smp.g2a = g2a
	c.smp.g3a = g3a
	return nil
}
Example #3
0
func plus(z *big.Int, x *big.Int, y *big.Int) *big.Int {
	var lim big.Int
	lim.Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
	z.Add(x, y)
	return z.Mod(z, &lim)

}
Example #4
0
// Validate performs basic sanity checks on the key.
// It returns nil if the key is valid, or else an error describing a problem.
func (priv *PrivateKey) Validate() error {
	if err := checkPub(&priv.PublicKey); err != nil {
		return err
	}

	// 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 errors.New("crypto/rsa: invalid modulus")
	}

	// Check that de ≡ 1 mod p-1, for each prime.
	// This implies that e is coprime to each p-1 as e has a multiplicative
	// inverse. Therefore e is coprime to lcm(p-1,q-1,r-1,...) =
	// exponent(ℤ/nℤ). It also implies that a^de ≡ a mod p as a^(p-1) ≡ 1
	// mod p. Thus a^de ≡ a mod n for all a coprime to n, as required.
	congruence := new(big.Int)
	de := new(big.Int).SetInt64(int64(priv.E))
	de.Mul(de, priv.D)
	for _, prime := range priv.Primes {
		pminus1 := new(big.Int).Sub(prime, bigOne)
		congruence.Mod(de, pminus1)
		if congruence.Cmp(bigOne) != 0 {
			return errors.New("crypto/rsa: invalid exponents")
		}
	}
	return nil
}
Example #5
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
}
Example #6
0
func gcd2(a, b *big.Int) *big.Int {
	b = newB.Set(b)
	for b.Sign() != 0 {
		a, b = b, a.Mod(a, b)
	}
	return a
}
Example #7
0
// schnorrCombineSigs combines a list of partial Schnorr signatures s values
// into a complete signature s for some group public key. This is achieved
// by simply adding the s values of the partial signatures as scalars.
func schnorrCombineSigs(curve *secp256k1.KoblitzCurve, sigss [][]byte) (*big.Int,
	error) {
	combinedSigS := new(big.Int).SetInt64(0)
	for i, sigs := range sigss {
		sigsBI := EncodedBytesToBigInt(copyBytes(sigs))
		if sigsBI.Cmp(bigZero) == 0 {
			str := fmt.Sprintf("sig s %v is zero", i)
			return nil, schnorrError(ErrInputValue, str)
		}
		if sigsBI.Cmp(curve.N) >= 0 {
			str := fmt.Sprintf("sig s %v is out of bounds", i)
			return nil, schnorrError(ErrInputValue, str)
		}

		combinedSigS.Add(combinedSigS, sigsBI)
		combinedSigS.Mod(combinedSigS, curve.N)
	}

	if combinedSigS.Cmp(bigZero) == 0 {
		str := fmt.Sprintf("combined sig s %v is zero", combinedSigS)
		return nil, schnorrError(ErrZeroSigS, str)
	}

	return combinedSigS, nil
}
Example #8
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
}
Example #9
0
// Adapted from from crypto/rsa decrypt
func blind(random io.Reader, key *rsa.PublicKey, c *big.Int) (blinded, unblinder *big.Int, err error) {
	// 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 multiplying by the multiplicative inverse of r.

	var r *big.Int

	for {
		r, err = rand.Int(random, key.N)
		if err != nil {
			return
		}
		if r.Cmp(bigZero) == 0 {
			r = bigOne
		}
		ir, ok := modInverse(r, key.N)
		if ok {
			bigE := big.NewInt(int64(key.E))
			rpowe := new(big.Int).Exp(r, bigE, key.N)
			cCopy := new(big.Int).Set(c)
			cCopy.Mul(cCopy, rpowe)
			cCopy.Mod(cCopy, key.N)
			return cCopy, ir, nil
		}
	}
}
Example #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
}
Example #11
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 #12
0
func main() {
	lim := 1000
	primes := allPrimes(lim)
	mx_cyc := 0
	mx_len := 0

	for _, i := range primes {
		j := 1
		for j < i {
			p := new(big.Int)
			*p = bigPow(10, j)
			res := new(big.Int)
			res.Mod(p, big.NewInt(int64(i)))
			if res.Int64() == 1 {
				if mx_len < j {
					mx_len = i
					mx_cyc = j
				}
				break
			}
			j++
		}
	}
	fmt.Printf("Found: 1/%d yields %d cycles\n", mx_len, mx_cyc)
}
Example #13
0
func main() {
	filename := "rosalind_pper.txt"
	b, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Printf("Error is %s", err.Error())
		os.Exit(1)
	}

	input := string(b)
	lines := strings.Split(input, "\n")[0]

	tokens := strings.Split(lines, " ")
	fmt.Println(tokens)

	totalVals, _ := strconv.ParseInt(tokens[0], 10, 64)
	numSelections, _ := strconv.ParseInt(tokens[1], 10, 64)

	min = totalVals - numSelections + 1

	result := Factorial(big.NewInt(totalVals))
	//fmt.Println(result)

	var mod big.Int

	mod.Mod(result, big.NewInt(1000000))

	fmt.Println(&mod)
}
Example #14
0
/*
	The Join function
	The first fuction to be executed
	Alaows it gives the hash and id and request the finger table for the boost node
*/
func Join(test bool) { //

	//generate id
	me.nodeId = Index(generateNodeId(), BITS)
	nodeIdInt := me.nodeId
	me.storage = map[string]string{}

	//prepare finger table
	if test { //firstnode in the ring
		me.offset = 0
		for i, _ := range me.FingerTable {
			//compute the ith node
			two := big.NewInt(2)
			dist := big.Int{}
			dist.Exp(two, big.NewInt(int64(i)), nil)
			var ithNode big.Int
			ithNode.Add(&dist, &nodeIdInt)
			x := ringSize(BITS)
			ithNode.Mod(&ithNode, &x)
			//fill the fingr table row
			me.FingerTable[i][0] = ithNode.String()
			me.FingerTable[i][1] = me.nodeId.String()
			me.FingerTable[i][2] = me.address //this node address
		}
	} else { //not first node in the ring
		//initialize offset
		GetOffsetClient(me.target)
		updateFingerTable(nodeIdInt, me.target) //target server required
		go infornMySuccessor()
		go AutoUpdate() // initialize auto update
	}

}
Example #15
0
// (n + 2^(k-1)) mod (2^m)
func calcFinger(n []byte, k int, m int) (string, []byte) {

	// convert the n to a bigint
	nBigInt := big.Int{}
	nBigInt.SetBytes(n)

	// get the right addend, i.e. 2^(k-1)
	two := big.NewInt(2)
	addend := big.Int{}
	addend.Exp(two, big.NewInt(int64(k-1)), nil)

	// calculate sum
	sum := big.Int{}
	sum.Add(&nBigInt, &addend)

	// calculate 2^m
	ceil := big.Int{}
	ceil.Exp(two, big.NewInt(int64(m)), nil)

	// apply the mod
	result := big.Int{}
	result.Mod(&sum, &ceil)

	resultBytes := result.Bytes()
	resultHex := fmt.Sprintf("%x", resultBytes)

	return resultHex, resultBytes
}
Example #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
}
Example #17
0
// (n - 2^(k-1)) mod 2^m
func calcLastFinger(n []byte, k int) (string, []byte) {

	// convert the n to a bigint
	nBigInt := big.Int{}
	nBigInt.SetBytes(n)

	// get the right addend, i.e. 2^(k-1)
	two := big.NewInt(2)
	addend := big.Int{}
	addend.Exp(two, big.NewInt(int64(k-1)), nil)

	addend.Mul(&addend, big.NewInt(-1))
	//Soustraction
	neg := big.Int{}
	neg.Add(&addend, &nBigInt)

	// calculate 2^m
	m := 160
	ceil := big.Int{}
	ceil.Exp(two, big.NewInt(int64(m)), nil)

	// apply the mod
	result := big.Int{}
	result.Mod(&neg, &ceil)

	resultBytes := result.Bytes()
	resultHex := fmt.Sprintf("%x", resultBytes)

	return resultHex, resultBytes
}
Example #18
0
// schnorrCombineSigs combines a list of partial Schnorr signatures s values
// into a complete signature s for some group public key. This is achieved
// by simply adding the s values of the partial signatures as scalars.
func schnorrCombineSigs(curve *TwistedEdwardsCurve, sigss [][]byte) (*big.Int,
	error) {
	combinedSigS := new(big.Int).SetInt64(0)
	for i, sigs := range sigss {
		sigsBI := EncodedBytesToBigInt(copyBytes(sigs))
		if sigsBI.Cmp(zero) == 0 {
			str := fmt.Sprintf("sig s %v is zero", i)
			return nil, fmt.Errorf("%v", str)
		}
		if sigsBI.Cmp(curve.N) >= 0 {
			str := fmt.Sprintf("sig s %v is out of bounds", i)
			return nil, fmt.Errorf("%v", str)
		}

		combinedSigS = ScalarAdd(combinedSigS, sigsBI)
		combinedSigS.Mod(combinedSigS, curve.N)
	}

	if combinedSigS.Cmp(zero) == 0 {
		str := fmt.Sprintf("combined sig s %v is zero", combinedSigS)
		return nil, fmt.Errorf("%v", str)
	}

	return combinedSigS, nil
}
Example #19
0
// GenerateKey generates a public and private key pair using random source rand.
func GenerateKey(rand io.Reader) (priv PrivateKey, err error) {
	/* See Certicom's SEC1 3.2.1, pg.23 */
	/* See NSA's Suite B Implementer’s Guide to FIPS 186-3 (ECDSA) A.1.1, pg.18 */

	/* Select private key d randomly from [1, n) */

	/* Read N bit length random bytes + 64 extra bits  */
	b := make([]byte, secp256k1.N.BitLen()/8+8)
	_, err = io.ReadFull(rand, b)
	if err != nil {
		return priv, fmt.Errorf("Reading random reader: %v", err)
	}

	d := new(big.Int).SetBytes(b)

	/* Mod n-1 to shift d into [0, n-1) range */
	d.Mod(d, new(big.Int).Sub(secp256k1.N, big.NewInt(1)))
	/* Add one to shift d to [1, n) range */
	d.Add(d, big.NewInt(1))

	priv.D = d

	/* Derive public key from private key */
	priv.derive()

	return priv, nil
}
Example #20
0
func (d *ecdsa) Sign(m []byte) (*big.Int, *big.Int) {
	h := sha1.New()
	if n, err := h.Write(m); n != len(m) || err != nil {
		log.Fatal("Error calculating hash")
	}
	e := h.Sum(nil)
	r, s := new(big.Int), new(big.Int)
	n := d.g.Size()
	z := new(big.Int).SetBytes(e)
	z.Mod(z, n)
	for r.Cmp(new(big.Int)) == 0 || s.Cmp(new(big.Int)) == 0 {
		k := new(big.Int).Rand(rnd, n)
		if k.Cmp(new(big.Int)) == 0 {
			continue
		}
		p := d.g.Pow(d.g.Generator(), k)
		r.Mod(p.(*ellipticCurveElement).x, n)

		k.ModInverse(k, n)
		s.Mul(r, d.key)
		s.Add(s, z)
		s.Mul(s, k)
		s.Mod(s, n)
	}
	return r, s
}
Example #21
0
func (E *EccKeyPair) EccdsaVerify(md *big.Int, S *Signature) bool {

	v := false

	if S.r.Cmp(E.C.p) >= 0 || S.s.Cmp(E.C.p) >= 0 {

		return v
	}

	w := new(big.Int).ModInverse(S.s, E.C.n)

	u1 := new(big.Int).Mul(w, md)
	u1.Mod(u1, E.C.n)

	u2 := new(big.Int).Mul(w, S.r)
	u2.Mod(u2, E.C.n)

	Gv := new(Point)
	Qv := new(Point)

	Gv.Mul(u1, E.C.G, E.C)
	Qv.Mul(u2, E.Q, E.C)

	Qv.Add(Gv, Qv, E.C)

	if S.r.Cmp(Qv.x) == 0 {
		v = true
	}
	return v
}
Example #22
0
func transform(msg []byte, r, s, q *big.Int, bias uint) (*big.Int, *big.Int) {
	h := sha1.New()
	if n, err := h.Write(msg); n != len(msg) || err != nil {
		log.Fatal("Error calculating hash")
	}
	e := h.Sum(nil)
	z := new(big.Int).SetBytes(e)
	z.Mod(z, q)

	t := big.NewInt(1 << bias)
	t.Mul(t, new(big.Int).Set(s))
	t.ModInverse(t, q)
	t.Mul(r, t)
	t.Mod(t, q)

	u := big.NewInt(1 << bias)
	u.Mul(u, s)
	u.Mod(u, q)
	u.ModInverse(u, q)
	u.Mul(z, u)
	u.Mod(u, q)
	u.Sub(q, u)

	return t, u
}
Example #23
0
func Unblind(key *rsa.PublicKey, blindedSig, unblinder []byte) []byte {
	m := new(big.Int).SetBytes(blindedSig)
	unblinderBig := new(big.Int).SetBytes(unblinder)
	m.Mul(m, unblinderBig)
	m.Mod(m, key.N)
	return m.Bytes()
}
Example #24
0
File: dsa.go Project: 2thetop/go
// Verify verifies the signature in r, s of hash using the public key, pub. It
// reports whether the signature is valid.
//
// Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated
// to the byte-length of the subgroup. This function does not perform that
// truncation itself.
func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
	// FIPS 186-3, section 4.7

	if pub.P.Sign() == 0 {
		return false
	}

	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
	}
	z := new(big.Int).SetBytes(hash)

	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
}
Example #25
0
func (c *Conversation) processSMP4(mpis []*big.Int) error {
	if len(mpis) != 3 {
		return errors.New("otr: incorrect number of arguments in SMP4 message")
	}
	rb := mpis[0]
	cr := mpis[1]
	d7 := mpis[2]
	h := sha256.New()

	r := new(big.Int).Exp(c.smp.qaqb, d7, p)
	s := new(big.Int).Exp(rb, cr, p)
	r.Mul(r, s)
	r.Mod(r, p)

	s.Exp(g, d7, p)
	t := new(big.Int).Exp(c.smp.g3b, cr, p)
	s.Mul(s, t)
	s.Mod(s, p)
	t.SetBytes(hashMPIs(h, 8, s, r))
	if t.Cmp(cr) != 0 {
		return errors.New("otr: ZKP cR failed in SMP4 message")
	}

	r.Exp(rb, c.smp.a3, p)
	if r.Cmp(c.smp.papb) != 0 {
		return smpFailureError
	}

	return nil
}
Example #26
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
}
//Hardened child key derivation (private key parent and child)
func (parent *ExtendedKey) HCKDpriv(index uint32) (*ExtendedKey, error) {
	//update w errors
	if len(parent.PrivateKey) != 32 {
		return nil, nil
	}
	//update w errors
	if len(parent.Chaincode) != 32 {
		return nil, nil
	}
	data := make([]byte, 37)
	copy(data[1:], parent.PrivateKey)
	binary.BigEndian.PutUint32(data[33:], index)
	hmac512 := hmac.New(sha512.New, parent.Chaincode)
	hmac512.Write(data)
	raw := hmac512.Sum(nil)
	//child Chaincode is the right 32 bytes of the result
	childChaincode := raw[32:]
	// child Private Key = parse256(left 32 bits) + parent key (mod n)
	// where n is the order of the curve
	// n is defined here on page 13: http://www.secg.org/sec2-v2.pdf
	leftInt := new(big.Int).SetBytes(raw[:32])
	parentKeyInt := new(big.Int).SetBytes(parent.PrivateKey)
	leftInt.Add(leftInt, parentKeyInt)
	leftInt.Mod(leftInt, btcec.S256().N)
	ParentFingerPrint := parent.GetFingerPrint()
	depthBytes := []byte{parent.Depth}
	depthInt := new(big.Int).SetBytes(depthBytes)
	depthInt.Add(depthInt, big.NewInt(1))
	depth := depthInt.Bytes()
	childExtendedKey := NewExtendedKey(depth[len(depth)-1], ParentFingerPrint, index, childChaincode, leftInt.Bytes())

	return childExtendedKey, nil
}
Example #28
0
File: p256.go Project: ArtemL/GCC
// p256FromBig sets out = R*in.
func p256FromBig(out *[p256Limbs]uint32, in *big.Int) {
	tmp := new(big.Int).Lsh(in, 257)
	tmp.Mod(tmp, p256.P)

	for i := 0; i < p256Limbs; i++ {
		if bits := tmp.Bits(); len(bits) > 0 {
			out[i] = uint32(bits[0]) & bottom29Bits
		} else {
			out[i] = 0
		}
		tmp.Rsh(tmp, 29)

		i++
		if i == p256Limbs {
			break
		}

		if bits := tmp.Bits(); len(bits) > 0 {
			out[i] = uint32(bits[0]) & bottom28Bits
		} else {
			out[i] = 0
		}
		tmp.Rsh(tmp, 28)
	}
}
Example #29
0
func (curve *rcurve) fromTwisted(tx, ty *big.Int) (*big.Int, *big.Int) {
	var x, y big.Int
	x.Mul(tx, curve.zinv2)
	x.Mod(&x, curve.params.P)
	y.Mul(ty, curve.zinv3)
	y.Mod(&y, curve.params.P)
	return &x, &y
}
Example #30
0
func (curve *rcurve) toTwisted(x, y *big.Int) (*big.Int, *big.Int) {
	var tx, ty big.Int
	tx.Mul(x, curve.z2)
	tx.Mod(&tx, curve.params.P)
	ty.Mul(y, curve.z3)
	ty.Mod(&ty, curve.params.P)
	return &tx, &ty
}