Example #1
0
func genModuli(numModuli int, output chan<- *big.Int, wg *sync.WaitGroup) {
	dupChan := make(chan *big.Int, 1)
	var prime1, prime2 *big.Int
	var err error

	for i := 0; i < numModuli; i++ {
		prime1, err = cryptorand.Prime(cryptorand.Reader, (*bits+1)/2)
		if err != nil {
			log.Fatal("Unable to generate random prime")
		}
		if (i % (*dupeprob)) == 1 {
			select {
			case prime2 = <-dupChan:
				output <- new(big.Int).Mul(prime1, prime2)
				continue
			default:
				dupChan <- prime1
			}
		}
		prime2, err = cryptorand.Prime(cryptorand.Reader, (*bits)/2)
		if err != nil {
			log.Fatal("Unable to generate random prime")
		}
		output <- new(big.Int).Mul(prime1, prime2)
	}
	wg.Done()
}
Example #2
0
// NewPaillierPrivateKey generates a new Paillier private key (key pair).
//
// The key used in the Paillier crypto system consists of four integer
// values. The public key has two parameters; the private key has three
// parameters (one parameter is shared between the keys). As in RSA it
// starts with two random primes 'p' and 'q'; the public key parameter
// are computed as:
//
//   n := p * q
//   g := random number from interval [0,n^2[
//
// The private key parameters are computed as:
//
//   n := p * q
//   l := lcm (p-1,q-1)
//   u := (((g^l mod n^2)-1)/n) ^-1 mod n
//
// N.B. The division by n is integer based and rounds toward zero!
func NewPaillierPrivateKey(bits int) (key *PaillierPrivateKey, err error) {

	// generate primes 'p' and 'q' and their factor 'n'
	// repeat until the requested factor bitsize is reached
	var p, q, n *big.Int
	for {
		bitsP := (bits - 5) / 2
		bitsQ := bits - bitsP

		p, err = rand.Prime(rand.Reader, bitsP)
		if err != nil {
			return nil, err
		}
		q, err = rand.Prime(rand.Reader, bitsQ)
		if err != nil {
			return nil, err
		}

		n = new(big.Int).Mul(p, q)
		if n.BitLen() == bits {
			break
		}
	}

	// initialize variables
	one := big.NewInt(1)
	n2 := new(big.Int).Mul(n, n)

	// compute public key parameter 'g' (generator)
	g, err := rand.Int(rand.Reader, n2)
	if err != nil {
		return nil, err
	}

	// compute private key parameters
	p1 := new(big.Int).Sub(p, one)
	q1 := new(big.Int).Sub(q, one)
	l := new(big.Int).Mul(q1, p1)
	l.Div(l, new(big.Int).GCD(nil, nil, p1, q1))

	a := new(big.Int).Exp(g, l, n2)
	a.Sub(a, one)
	a.Div(a, n)
	u := new(big.Int).ModInverse(a, n)

	// return key pair
	pubkey := &PaillierPublicKey{
		N: n,
		G: g,
	}
	prvkey := &PaillierPrivateKey{
		PaillierPublicKey: pubkey,
		L:                 l,
		U:                 u,
		P:                 p,
		Q:                 q,
	}
	return prvkey, nil
}
Example #3
0
// GeneratePrime randomly generates a big.Int prime number with the given size
// in bits
func GeneratePrime(size int) *big.Int {
	prime, err := rand.Prime(rand.Reader, size)
	if err != nil {
		panic(err)
	}
	return prime
}
Example #4
0
func main() {
	end = make(map[int64]int)
	b := big.NewInt(int64(10))
	for i := 0; i < size; i++ {
		r, _ := c_rand.Int(c_rand.Reader, b)
		m := r.Int64()
		end[m]++
	}

	for i, j := range end {
		fmt.Print(i)
		for m := 0; m < j/(size/100); m++ {
			fmt.Print("*")
		}
		fmt.Println("	", j)
	}

	for i := 0; i < 11; i++ {
		fmt.Println(c_rand.Prime(c_rand.Reader, 64))
	}

	for i := 0; i < 11; i++ {
		fmt.Println(m_rand.ExpFloat64())
	}
}
Example #5
0
// genState generates a starting state using Go's 'crypto/rand'
// package. The state will be a 64-bit prime. It'll panic if
// rand.Prime returns an error.
func genState() uint64 {
	prime, err := rand.Prime(rand.Reader, 64)
	if err != nil {
		panic(err)
	}
	return prime.Uint64()
}
Example #6
0
//NewSwizzle makes a Swizzle instance.
func NewSwizzle(key []byte, sectors int, prime *big.Int, primebits int) (Heartbeat, error) {
	if key == nil {
		key = make([]byte, 32)
		rand.Read(key)
	}
	if primebits <= 0 {
		primebits = defaultPrimebits
	}
	if sectors <= 0 {
		sectors = defaultSectors
	}
	if prime == nil {
		var err error
		prime, err = rand.Prime(rand.Reader, primebits)
		if err != nil {
			return nil, err
		}
	}

	m := Swizzle{key: key, prime: prime, sectors: sectors}
	m.fKey = make([]byte, 32)
	rand.Read(m.fKey)
	m.alphaKey = make([]byte, 32)
	rand.Read(m.alphaKey)
	return &m, nil
}
Example #7
0
// Generate a new cyclic group and generator of given bits size.
func New(random io.Reader, bits int) (*Group, error) {
	for {
		// Generate a large prime of size 'bits'-1
		q, err := rand.Prime(random, bits-1)
		if err != nil {
			return nil, err
		}
		// Calculate the safe prime p=2q+1 of order 'bits'
		p := new(big.Int).Mul(q, big.NewInt(2))
		p = new(big.Int).Add(p, big.NewInt(1))

		// Probability of p being non-prime is negligible
		if p.ProbablyPrime(negligibleExp / 2) {
			for {
				// Generate a generator of p
				a, err := rand.Int(random, p)
				if err != nil {
					return nil, err
				}
				// Ensure generator order is not 2 (efficiency)
				if b := new(big.Int).Exp(a, big.NewInt(2), p); b.Cmp(big.NewInt(1)) == 0 {
					continue
				}
				// Return if generator order is q
				if b := new(big.Int).Exp(a, q, p); b.Cmp(big.NewInt(1)) == 0 {
					return &Group{p, a}, nil
				}
			}
		}
	}
}
Example #8
0
File: v1.go Project: mconintet/uuid
func NewV1(node net.HardwareAddr) (uuid *Uuid, err error) {
	var (
		inter *net.Interface
		t     int64
		clk   *big.Int
		clkB  []byte
	)

	v1mutex.Lock()
	defer v1mutex.Unlock()

	uuid = new(Uuid)

	if node == nil {
		if inter, err = GetFirstNetInterface(); err == nil {
			uuid.Node = inter.HardwareAddr[0:6]
		} else if err == errNoInterface {
			if uuid.Node, err = GetRandomNode(); err != nil {
				return nil, err
			}
		} else {
			return nil, err
		}
	} else {
		uuid.Node = node[0:6]
	}

	if clk, err = rand.Prime(rand.Reader, 14); err != nil {
		return nil, err
	}

	t = GetTime()

	uuid.TimeLow = []byte{
		byte(t >> 24),
		byte(t >> 16),
		byte(t >> 8),
		byte(t),
	}

	uuid.TimeMid = []byte{
		byte(t >> 40),
		byte(t >> 32),
	}

	uuid.TimeHiVer = []byte{
		byte(t>>56) | ver1,
		byte(t >> 48),
	}

	clkB = clk.Bytes()
	uuid.ClockSeq = []byte{
		clkB[0] | variant,
		clkB[1],
	}

	return uuid, err
}
// NewMersennePrime returns a seeded, initialized MT19937, seeded
// using a large from from 'crypto/rand'.
// Will panic if rand.Prime returns an error.
func NewMersennePrime() *MT19937 {
	m := New()
	prime, err := rand.Prime(rand.Reader, 64)
	if err != nil {
		panic(err)
	}
	m.Seed(prime.Int64())
	return m
}
Example #10
0
func ShowPrime() {
	for i := 0; i < *iterations; i++ {
		if p, err := rand.Prime(rand.Reader, *bits); err != nil {
			log.Fatalf("failed to read random prime: %s", err)
		} else {
			log.Printf("got random prime: %s", p)
		}
	}
}
Example #11
0
File: v1.go Project: mconintet/uuid
func GetRandomNode() (node []byte, err error) {
	var bi *big.Int

	if bi, err = rand.Prime(rand.Reader, 48); err != nil {
		return nil, err
	}

	return bi.Bytes(), nil
}
Example #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("crypto/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))
		g.GCD(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
}
func newStore() *sessions.CookieStore {
	storeSeed, err := rand.Prime(rand.Reader, 128)
	if err != nil {
		fmt.Errorf("Could not initialise CookieStore: %v\n", err)
	}
	store := sessions.NewCookieStore([]byte(storeSeed.String()))
	store.MaxAge(86400) // 1 day
	return store
}
// Warmup warms up the PRNG by running a 64-bit prime number of iterations.
func (m *MT19937) Warmup() {
	prime, err := rand.Prime(rand.Reader, 64)
	if err != nil {
		panic(err)
	}
	n := prime.Uint64()

	for i := uint64(0); i < n; i++ {
		m.Int64()
	}
}
Example #15
0
// https://golang.org/issue/6849.
func TestPrimeSmall(t *testing.T) {
	for n := 2; n < 10; n++ {
		p, err := rand.Prime(rand.Reader, n)
		if err != nil {
			t.Fatalf("Can't generate %d-bit prime: %v", n, err)
		}
		if p.BitLen() != n {
			t.Fatalf("%v is not %d-bit", p, n)
		}
		if !p.ProbablyPrime(32) {
			t.Fatalf("%v is not prime", p)
		}
	}
}
Example #16
0
func (s secureReadWriteCloser) Write(data []byte) (n int, err error) {
	if s.out != nil {
		// get a nonce
		// crypto rand seems capable of generating a 24byte prime number
		nonceBigint, err := rand.Prime(rand.Reader, 24*8)
		if err != nil {
			return n, err
		}

		copy(nonce[:], nonceBigint.Bytes())

		// send the encrypted data
		return s.out.Write(box.Seal(nil, data, &nonce, s.peerPub, s.priv))
	}
	return
}
Example #17
0
func main() {

	if n, err := rand.Int(rand.Reader, big.NewInt(1024)); err == nil {
		fmt.Println(n)
	}

	if n, err := rand.Prime(rand.Reader, 128); err == nil {
		fmt.Println(n)
	}

	//25885087847758063
	//172947142856842446121302980611922498603

	d := 0x12
	fmt.Printf("%d", d)
}
Example #18
0
// Generates a valid Optimus struct by calculating a random prime number
// This function takes a few seconds and is resource intensive
func GenerateSeed(bits int) *Optimus {
	// use Prime Number Theorem to calculate number of primes in each bit
	// http://mathworld.wolfram.com/PrimeNumberTheorem.html
	numPrimes := make([]float64, bits)
	for i := MIN_PRIME_BITS; i < bits; i++ {
		exp := math.Pow(2, float64(i)) - 1
		numPrimes[i] = exp / (math.Log(exp))
	}
	maxNumPrimesStr := strings.Split(strconv.FormatFloat(numPrimes[bits-1], 'f', -1, 64), ".")[0]
	maxNumPrimeBigInt := &big.Int{}
	maxNumPrimeBigInt.SetString(maxNumPrimesStr, 10)

	//Generated prime must be less than MAX_INT
	maxInt := BitsToBig(bits)
	var randomPrime *big.Int

	for true {
		randNumBigInt, _ := rand.Int(rand.Reader, maxNumPrimeBigInt)
		randNumPrimeFloat, _ := strconv.ParseFloat(randNumBigInt.String(), 64)
		primeNumBits := bits
		for i := MIN_PRIME_BITS; i < bits; i++ {
			if randNumPrimeFloat < numPrimes[i] {
				primeNumBits = i + 1
				break
			}
		}
		randomPrime, _ = rand.Prime(rand.Reader, primeNumBits)
		compare := &big.Int{}
		compare.Sub(randomPrime, maxInt)
		if compare.Sign() == -1 {
			break
		}
	}

	//Calculate Mod Inverse for selectedPrime
	modInverse := ModInverse(randomPrime, maxInt)

	//Generate Random Integer less than MAX_INT
	randomNumber, _ := rand.Int(rand.Reader, maxInt)

	return &Optimus{randomPrime, modInverse, randomNumber, bits, maxInt}
}
Example #19
0
func main() {
	for _, n := range []int{128, 160, 256, 512} {
		p, err := rand.Prime(rand.Reader, n+1)
		if err != nil {
			panic(err)
		}
		fmt.Printf("var p_%v = big.NewInt(0).SetBytes([]byte{", n)
		data := p.Bytes()
		for i, b := range data {
			if i > 0 {
				fmt.Printf(",")
			}
			if i < len(data)-1 && i%8 == 0 {
				fmt.Printf("\n\t")
			}
			fmt.Printf("0x%x", b)
		}
		fmt.Printf("})\n\n")
	}
}
Example #20
0
func TestSqrt(t *testing.T) {
	p, err := rand.Prime(rand.Reader, 256)
	if err != nil {
		t.Fatal("failed to create random prime number")
	}
	count := 0
	for i := 0; i < 1000; i++ {
		g, err := rand.Int(rand.Reader, p)
		if err != nil {
			t.Fatal("failed to create random int")
		}
		if isQuadraticResidue(g, p) {
			count++
			h, err := SqrtModP(g, p)
			if err != nil {
				t.Fatal("sqrtmodp failed")
			}
			gg := new(big.Int).Exp(h, TWO, p)
			if gg.Cmp(g) != 0 {
				t.Fatal("result error")
			}
		}
	}
}
Example #21
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("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2")
	}

	primes := make([]*big.Int, nprimes)

NextSetOfPrimes:
	for {
		todo := bits
		// crypto/rand should set the top two bits in each prime.
		// Thus each prime has the form
		//   p_i = 2^bitlen(p_i) × 0.11... (in base 2).
		// And the product is:
		//   P = 2^todo × α
		// where α is the product of nprimes numbers of the form 0.11...
		//
		// If α < 1/2 (which can happen for nprimes > 2), we need to
		// shift todo to compensate for lost bits: the mean value of 0.11...
		// is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2
		// will give good results.
		if nprimes >= 7 {
			todo += (nprimes - 2) / 5
		}
		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)
		}
		if n.BitLen() != bits {
			// This should never happen for nprimes == 2 because
			// crypto/rand should set the top two bits in each prime.
			// For nprimes > 2 we hope it does not happen often.
			continue NextSetOfPrimes
		}

		g := new(big.Int)
		priv.D = new(big.Int)
		y := new(big.Int)
		e := big.NewInt(int64(priv.E))
		g.GCD(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
}
Example #22
0
func main() {
	var sss shamir.SecretSharing

	secretStr := "Golang secret"
	sss.Secret = str2big(secretStr)

	sss.T = 3
	sss.N = 7

	nbits := sss.Secret.BitLen() + 1
	sss.PrimeMod, _ = rand.Prime(rand.Reader, nbits)

	sss.GeneratePol()
	sss.GenerateShares()

	fmt.Println("Secret:")
	fmt.Println("-------")
	fmt.Printf("\tstring: %s\n", secretStr)
	fmt.Printf("\thexa:   %x\n\n", sss.Secret)

	fmt.Println("Threshold:")
	fmt.Println("----------")
	fmt.Printf("\t(t, n) = (%d, %d)\n\n", sss.T, sss.N)

	fmt.Println("Prime modulo")
	fmt.Println("------------")
	fmt.Printf("\tmodulo = %x\n\n", sss.PrimeMod)

	fmt.Println("Polynomial coefficients")
	fmt.Println("----------------------------------------")
	for i, e := range sss.Coeffs {
		fmt.Printf("\ta_%d = %x\n", i, e)
	}

	fmt.Println("\nShares of the participants:")
	fmt.Println("---------------------------")
	for i, e := range sss.Shares {
		fmt.Printf("\t(x_%d, y_%d) = (%x, %x)\n", i, i, e.Px, e.Py)
	}

	// We simulate a random collaboration of participants to recover the secret
	// by shuffling the shares and using only the first T
	fmt.Println("\nParticipants used:")
	fmt.Println("-------------------")
	mrand.Seed(time.Now().UnixNano())
	perm := mrand.Perm(sss.N)
	for i := 0; i < sss.T; i++ {
		j := perm[i]
		sss.Shares[i], sss.Shares[j] = sss.Shares[j], sss.Shares[i]
		px := sss.Shares[perm[i]].Px
		py := sss.Shares[perm[i]].Py
		fmt.Printf("\t(x_%d, y_%d) = (%x, %x)\n", perm[i], perm[i], px, py)
	}
	sss.Shares = sss.Shares[0:sss.T]
	sss.Secret.SetInt64(0)

	sss.RecoverSecret()
	fmt.Println("\nRecovered secred:")
	fmt.Println("-----------------")
	fmt.Printf("\tstring: %s\n", big2str(sss.Secret))
	fmt.Printf("\thexa:   %x\n\n", sss.Secret)
}
Example #23
0
func main() {
	p, _ := new(big.Int).SetString("233970423115425145524320034830162017933", 10)
	a := big.NewInt(-95051)
	b := big.NewInt(11279326)
	G := dh.NewEllipticCurve(a, b, p)

	gx := big.NewInt(182)
	gy, _ := new(big.Int).SetString("85518893674295321206118380980485522083", 10)
	g := dh.NewEllipticCurveElement(G, gx, gy)
	q, _ := new(big.Int).SetString("29246302889428143187362802287225875743", 10)
	GG := dh.NewGeneratedGroup(G, g, *q)

	log.Printf("========== PART 1 ==========")
	alice := dh.NewECDSA(GG)
	log.Printf("Alice's group identity: %s", alice.Group().Identity())
	log.Printf("Alice's group generator: %s", alice.Group().Generator())
	log.Printf("Alice's generator^q: %s", alice.Group().Pow(alice.Group().Generator(), q))
	r, s := alice.Sign(secretMessage)
	log.Printf("r=%d s=%d", r, s)
	log.Printf("Verifies: %v",
		dh.ECDSAVerify(secretMessage, r, s, alice))
	log.Printf("Verifies with different message: %v",
		dh.ECDSAVerify([]byte("xxx"), r, s, alice))
	r.Add(r, big.NewInt(1))
	r.Mod(r, p)
	log.Printf("Verifies after r += 1: %v",
		dh.ECDSAVerify(secretMessage, r, s, alice))
	s.Add(s, big.NewInt(1))
	s.Mod(s, p)
	log.Printf("Verifies after r and s += 1: %v",
		dh.ECDSAVerify(secretMessage, r, s, alice))
	r.Sub(r, big.NewInt(1))
	r.Mod(r, p)
	log.Printf("Verifies after s += 1: %v",
		dh.ECDSAVerify(secretMessage, r, s, alice))
	s.Sub(s, big.NewInt(1))
	s.Mod(s, p)
	log.Printf("Verifies original: %v",
		dh.ECDSAVerify(secretMessage, r, s, alice))

	eve := dh.FindVerifyingECDSA(secretMessage, r, s, GG)
	log.Printf("Eve's group identity: %s", eve.Group().Identity())
	log.Printf("Eve's group generator: %s", eve.Group().Generator())
	log.Printf("Eve's generator^q: %s", eve.Group().Pow(eve.Group().Generator(), q))
	log.Printf("Eve verifies: %v",
		dh.ECDSAVerify(secretMessage, r, s, eve))

	log.Printf("========== PART 2 ==========")
	pi, err := crand.Prime(crand.Reader, keySize/2)
	if err != nil {
		panic(err)
	}
	qi, err := crand.Prime(crand.Reader, keySize/2)
	if err != nil {
		panic(err)
	}
	bob := dh.NewRSA(pi, qi)
	log.Printf("Bob's (N, e) = (%d, %d)", new(big.Int).Mul(qi, pi), bob.PublicKey())
	h := sha1.New()
	if n, err := h.Write(secretMessage); n != len(secretMessage) || err != nil {
		log.Fatal("Error calculating hash")
	}
	hashBytes := h.Sum(nil)
	// Don't feel like implementing padding again
	sigBytes := bob.Decrypt(new(big.Int).SetBytes(hashBytes))
	log.Printf("Bob's signature verifies: %v",
		hmac.Equal(hashBytes, bob.Encrypt(sigBytes).Bytes()))

	eveN, eveE, _ := chosenEncrytion(sigBytes, hashBytes, keySize)
	log.Printf("Eve's (N', e') = (%d, %d)", eveN, eveE)
	log.Printf("Eve's signature verifies: %v",
		hmac.Equal(hashBytes, new(big.Int).Exp(new(big.Int).SetBytes(sigBytes), eveE, eveN).Bytes()))

	log.Printf("========== PART 3 ==========")
	original := []byte("Transfer $100 from Chris to the Treasury")
	desired := []byte("Transfer $1,000,000 from the Treasury to Chris")
	pi, err = crand.Prime(crand.Reader, keySize/2)
	if err != nil {
		panic(err)
	}
	qi, err = crand.Prime(crand.Reader, keySize/2)
	if err != nil {
		panic(err)
	}
	bob = dh.NewRSA(pi, qi)
	log.Printf("Bob's (N, e) = (%d, %d)", new(big.Int).Mul(qi, pi), bob.PublicKey())
	enc := bob.Encrypt(original)
	eveN, eveE, eveD := chosenEncrytion(desired, enc.Bytes(), keySize)
	log.Printf("Eve's (N', e', d') = (%d, %d, %d)", eveN, eveE, eveD)
	if eveN.Cmp(new(big.Int).SetBytes(desired)) < 0 {
		log.Panic("Eve's key is too small")
	}
	log.Printf("Decrypted: %s", new(big.Int).Exp(enc, eveD, eveN).Bytes())
}
Example #24
0
func BenchmarkPrime(b *testing.B) {
	r := mathrand.New(mathrand.NewSource(time.Now().UnixNano()))
	for i := 0; i < b.N; i++ {
		rand.Prime(r, 1024)
	}
}
Example #25
0
File: rsa.go Project: achanda/go
// GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit
// size and the given random source, 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) (*PrivateKey, error) {
	priv := new(PrivateKey)
	priv.E = 65537

	if nprimes < 2 {
		return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2")
	}

	if bits < 64 {
		primeLimit := float64(uint64(1) << uint(bits/nprimes))
		// pi approximates the number of primes less than primeLimit
		pi := primeLimit / (math.Log(primeLimit) - 1)
		// Generated primes start with 11 (in binary) so we can only
		// use a quarter of them.
		pi /= 4
		// Use a factor of two to ensure that key generation terminates
		// in a reasonable amount of time.
		pi /= 2
		if pi <= float64(nprimes) {
			return nil, errors.New("crypto/rsa: too few primes of given length to generate an RSA key")
		}
	}

	primes := make([]*big.Int, nprimes)

NextSetOfPrimes:
	for {
		todo := bits
		// crypto/rand should set the top two bits in each prime.
		// Thus each prime has the form
		//   p_i = 2^bitlen(p_i) × 0.11... (in base 2).
		// And the product is:
		//   P = 2^todo × α
		// where α is the product of nprimes numbers of the form 0.11...
		//
		// If α < 1/2 (which can happen for nprimes > 2), we need to
		// shift todo to compensate for lost bits: the mean value of 0.11...
		// is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2
		// will give good results.
		if nprimes >= 7 {
			todo += (nprimes - 2) / 5
		}
		for i := 0; i < nprimes; i++ {
			var err error
			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)
		}
		if n.BitLen() != bits {
			// This should never happen for nprimes == 2 because
			// crypto/rand should set the top two bits in each prime.
			// For nprimes > 2 we hope it does not happen often.
			continue NextSetOfPrimes
		}

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

		if g.Cmp(bigOne) == 0 {
			if priv.D.Sign() < 0 {
				priv.D.Add(priv.D, totient)
			}
			priv.Primes = primes
			priv.N = n

			break
		}
	}

	priv.Precompute()
	return priv, nil
}
Example #26
0
func BenchmarkCryptoRandPrime(b *testing.B) {
	for i := 0; i < b.N; i++ {
		rand.Prime(rand.Reader, 1024)
	}
}
Example #27
0
func randomID() uint32 {
	i, _ := crypto.Prime(crypto.Reader, 64)
	seed := i.Int64()
	r := rand.New(rand.NewSource(seed))
	return r.Uint32() & 0xFFFFFFF0
}
Example #28
0
// Test that passing bits < 2 causes Prime to return nil, error
func TestPrimeBitsLt2(t *testing.T) {
	if p, err := rand.Prime(rand.Reader, 1); p != nil || err == nil {
		t.Errorf("Prime should return nil, error when called with bits < 2")
	}
}
Example #29
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 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

	if nprimes < 2 {
		return nil, os.ErrorString("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
}