Beispiel #1
1
// Appends to data the first (len(data) / 32)bits of the result of sha256(data)
// Currently only supports data up to 32 bytes
func addChecksum(data []byte) []byte {
	// Get first byte of sha256
	hasher := sha256.New()
	hasher.Write(data)
	hash := hasher.Sum(nil)
	firstChecksumByte := hash[0]

	// len() is in bytes so we divide by 4
	checksumBitLength := uint(len(data) / 4)

	// For each bit of check sum we want we shift the data one the left
	// and then set the (new) right most bit equal to checksum bit at that index
	// staring from the left
	dataBigInt := new(big.Int).SetBytes(data)
	for i := uint(0); i < checksumBitLength; i++ {
		// Bitshift 1 left
		dataBigInt.Mul(dataBigInt, BigTwo)

		// Set rightmost bit if leftmost checksum bit is set
		if uint8(firstChecksumByte&(1<<(7-i))) > 0 {
			dataBigInt.Or(dataBigInt, BigOne)
		}
	}

	return dataBigInt.Bytes()
}
Beispiel #2
0
// ComputeKey computes the session key given the value of A.
func (ss *ServerSession) ComputeKey(A []byte) ([]byte, error) {
	err := ss.setA(A)
	if err != nil {
		return nil, err
	}

	// S = (Av^u) mod N
	S := new(big.Int).Exp(ss._v, ss._u, ss.SRP.Group.Prime)
	S.Mul(ss._A, S).Mod(S, ss.SRP.Group.Prime)

	// Reject A*v^u == 0,1 (mod N)
	one := big.NewInt(1)
	if S.Cmp(one) <= 0 {
		return nil, fmt.Errorf("Av^u) mod N <= 0")
	}

	// Reject A*v^u == -1 (mod N)
	t1 := new(big.Int).Add(S, one)
	if t1.BitLen() == 0 {
		return nil, fmt.Errorf("Av^u) mod N == -1")
	}

	// S = (S ^ b) mod N              (computes session key)
	S.Exp(S, ss._b, ss.SRP.Group.Prime)
	// K = H(S)
	ss.key = quickHash(ss.SRP.HashFunc, S.Bytes())
	return ss.key, nil
}
Beispiel #3
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
	N := c.Params().N

	if r.Sign() == 0 || s.Sign() == 0 {
		return false
	}
	if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {
		return false
	}
	e := hashToInt(hash, c)
	w := new(big.Int).ModInverse(s, 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, N)
	return x.Cmp(r) == 0
}
Beispiel #4
0
func (t *lft) extr(x *big.Int) *big.Rat {
	var n, d big.Int
	var r big.Rat
	return r.SetFrac(
		n.Add(n.Mul(&t.q, x), &t.r),
		d.Add(d.Mul(&t.s, x), &t.t))
}
Beispiel #5
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
}
Beispiel #6
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
}
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 NetworkEmmit(e *tree_event.Event, path *tree_graph.Path) (err tree_lib.TreeError) {
	var (
		sdata []byte
		p     *big.Int
	)
	err.From = tree_lib.FROM_NETWORK_EMIT

	// Calling get value, because maybe some one will calculate this path before calling this functions
	// If path is not calculated yet, it will be automatically calculated in GetValue function
	p, err = path.GetValue()
	if !err.IsNull() {
		return
	}

	// If we emitting from API then we need to multiply path with connected node
	// For sending data through him
	if strings.Contains(node_info.CurrentNodeInfo.Name, tree_api.API_NAME_PREFIX) {
		p.Mul(p, node_info.ChildsNodeValue[path.From])
	}

	// If from not set, setting it before network sending
	if len(e.From) == 0 {
		e.From = node_info.CurrentNodeInfo.Name
	}

	sdata, err.Err = ffjson.Marshal(e)
	if !err.IsNull() {
		return
	}

	SendToPath(sdata, p)
	return
}
Beispiel #9
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()
}
Beispiel #10
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
}
Beispiel #11
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 #12
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 #13
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
		}
	}
}
Beispiel #14
0
// MulBigPow10 computes 10 * x ** n.
// It reuses x.
func MulBigPow10(x *big.Int, n int32) *big.Int {
	if x.Sign() == 0 || n <= 0 {
		return x
	}
	b := pow.BigTen(int64(n))
	return x.Mul(x, &b)
}
Beispiel #15
0
//newPrivateKey makes private key from seeds.
func newPrivateKey(pSeed, qSeed big.Int) (*PrivateKey, error) {
	q := &qSeed
	p := &pSeed
	var tmp big.Int
	test := big.NewInt(0x7743)
	var q1, phi, keyD, keyN big.Int
	for count := 0; count < rsaCreateGiveup; count++ {
		q = primize(q)
		q1.Add(q, tmp.SetInt64(-1))
		p = primize(p)
		phi.Add(p, tmp.SetInt64(-1))
		phi.Mul(&phi, &q1)
		keyD.ModInverse(rsaPublicE, &phi)
		if keyD.Cmp(tmp.SetInt64(0)) == 0 {
			continue
		}
		keyN.Mul(p, q)
		tmp.Exp(test, rsaPublicE, &keyN)
		tmp.Exp(&tmp, &keyD, &keyN)
		if tmp.Cmp(test) == 0 {
			return &PrivateKey{&keyN, &keyD}, nil
		}
		p.Add(p, tmp.SetInt64(2))
		q.Add(q, tmp.SetInt64(2))
	}
	err := errors.New("cannot generate private key")
	log.Fatal(err)
	return nil, err
}
Beispiel #16
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
}
Beispiel #17
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
}
Beispiel #18
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
}
Beispiel #19
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
}
Beispiel #20
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 #21
0
//Verify verifies the proof file server send.
func (sw *Swizzle) Verify(p Proof) (bool, error) {
	proof, ok := p.(*SwizzleProof)
	if !ok {
		return false, errors.New("use SwizzleProof instance for proof")
	}
	var rhs big.Int
	var dummy big.Int
	ch := sw.lastChallenge
	for i := 0; i < sw.chunks; i++ {
		f, err := keyedPRFBig(sw.fKey, sw.prime, i)
		if err != nil {
			return false, err
		}
		v, err := keyedPRFBig(ch.Key, ch.Vmax, i)
		if err != nil {
			return false, err
		}
		rhs.Add(&rhs, dummy.Mul(v, f))
	}
	for j := 0; j < ch.Sectors; j++ {
		alpha, err := keyedPRFBig(sw.alphaKey, sw.prime, j)
		if err != nil {
			return false, err
		}
		rhs.Add(&rhs, dummy.Mul(alpha, &proof.Mu[j]))
	}
	dummy.DivMod(&rhs, sw.prime, &rhs)
	if proof.Sigma.Cmp(&rhs) == 0 {
		return true, nil
	}
	return false, nil
}
Beispiel #22
0
func main() {
	s := bufio.NewScanner(bufio.NewReader(os.Stdin))
	s.Split(bufio.ScanWords)

	s.Scan()
	a, _ := strconv.Atoi(s.Text())

	s.Scan()
	b, _ := strconv.Atoi(s.Text())

	s.Scan()
	n, _ := strconv.Atoi(s.Text())

	switch n {
	case 0:
		fmt.Printf("0\n")
	case 1:
		fmt.Printf("%v\n", a)
	case 2:
		fmt.Printf("%v\n", b)
	default:
		fp := big.NewInt(int64(a))
		fc := big.NewInt(int64(b))
		for i := 2; i < n; i++ {
			f := new(big.Int)
			f.Mul(fc, fc)
			f.Add(f, fp)
			fp = fc
			fc = f
		}
		fmt.Printf("%v\n", fc)
	}
}
Beispiel #23
0
Datei: dsa.go Projekt: 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
}
Beispiel #24
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 #25
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)
	}
}
Beispiel #26
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
}
Beispiel #27
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)
	}
}
Beispiel #28
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 #29
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 #30
0
func main() {
	in, _ := os.Open("465.in")
	defer in.Close()
	out, _ := os.Create("465.out")
	defer out.Close()

	var s1, s2 string
	var op byte
	var i1, i2, i3 big.Int
	var maxInt = big.NewInt(math.MaxInt32)
	for {
		if _, err := fmt.Fscanf(in, "%s %c %s", &s1, &op, &s2); err != nil {
			break
		}
		fmt.Fprintf(out, "%s %c %s\n", s1, op, s2)
		i1.SetString(s1, 10)
		if i1.Cmp(maxInt) > 0 {
			fmt.Fprintln(out, "first number too big")
		}
		i2.SetString(s2, 10)
		if i2.Cmp(maxInt) > 0 {
			fmt.Fprintln(out, "second number too big")
		}
		if op == '+' {
			i3.Add(&i1, &i2)
		} else {
			i3.Mul(&i1, &i2)
		}
		if i3.Cmp(maxInt) > 0 {
			fmt.Fprintln(out, "result too big")
		}
	}
}