Esempio n. 1
0
func RandomString(n int) string {

	randInt, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
	if err != nil {
		panic(err)
	}

	buf := make([]byte, n)

	for n, cache, remaining := n-1, randInt.Int64(), charMax; n >= 0; {
		if remaining == 0 {

			randInt, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
			if err != nil {
				panic(err)
			}

			cache, remaining = randInt.Int64(), charMax
		}
		if idx := int(cache & charMask); idx < len(charBytes) {
			buf[n] = charBytes[idx]
			n--
		}
		cache >>= charBits
		remaining--
	}

	return string(buf)
}
Esempio n. 2
0
func TestTripartiteDiffieHellman(t *testing.T) {
	a, _ := rand.Int(rand.Reader, Order)
	b, _ := rand.Int(rand.Reader, Order)
	c, _ := rand.Int(rand.Reader, Order)

	pa := new(G1).ScalarBaseMult(a)
	qa := new(G2).ScalarBaseMult(a)
	pb := new(G1).ScalarBaseMult(b)
	qb := new(G2).ScalarBaseMult(b)
	pc := new(G1).ScalarBaseMult(c)
	qc := new(G2).ScalarBaseMult(c)

	k1 := Pair(pb, qc)
	k1.ScalarMult(k1, a)
	k1Bytes := k1.Marshal()

	k2 := Pair(pc, qa)
	k2.ScalarMult(k2, b)
	k2Bytes := k2.Marshal()

	k3 := Pair(pa, qb)
	k3.ScalarMult(k3, c)
	k3Bytes := k3.Marshal()

	if !bytes.Equal(k1Bytes, k2Bytes) || !bytes.Equal(k2Bytes, k3Bytes) {
		t.Errorf("keys didn't agree")
	}
}
Esempio n. 3
0
func (self *DHGroup) GeneratePrivateKey(randReader io.Reader) (key *DHKey, err error) {
	if randReader == nil {
		randReader = rand.Reader
	}

	// x should be in (0, p).
	// alternative approach:
	// x, err := big.Add(rand.Int(randReader, big.Sub(p, big.NewInt(1))), big.NewInt(1))
	//
	// However, since x is highly unlikely to be zero if p is big enough,
	// we would rather use an iterative approach below,
	// which is more efficient in terms of exptected running time.
	x, err := rand.Int(randReader, self.p)
	if err != nil {
		return
	}

	zero := big.NewInt(0)
	for x.Cmp(zero) == 0 {
		x, err = rand.Int(randReader, self.p)
		if err != nil {
			return
		}
	}
	key = new(DHKey)
	key.x = x

	// y = g ^ x mod p
	key.y = new(big.Int).Exp(self.g, x, self.p)
	key.group = self
	return
}
Esempio n. 4
0
func ExamplePair() {
	// This implements the tripartite Diffie-Hellman algorithm from "A One
	// Round Protocol for Tripartite Diffie-Hellman", A. Joux.
	// http://www.springerlink.com/content/cddc57yyva0hburb/fulltext.pdf

	// Each of three parties, a, b and c, generate a private value.
	a, _ := rand.Int(rand.Reader, Order)
	b, _ := rand.Int(rand.Reader, Order)
	c, _ := rand.Int(rand.Reader, Order)

	// Then each party calculates g₁ and g₂ times their private value.
	pa := new(G1).ScalarBaseMult(a)
	qa := new(G2).ScalarBaseMult(a)

	pb := new(G1).ScalarBaseMult(b)
	qb := new(G2).ScalarBaseMult(b)

	pc := new(G1).ScalarBaseMult(c)
	qc := new(G2).ScalarBaseMult(c)

	// Now each party exchanges its public values with the other two and
	// all parties can calculate the shared key.
	k1 := Pair(pb, qc)
	k1.ScalarMult(k1, a)

	k2 := Pair(pc, qa)
	k2.ScalarMult(k2, b)

	k3 := Pair(pa, qb)
	k3.ScalarMult(k3, c)

	// k1, k2 and k3 will all be equal.
}
Esempio n. 5
0
// TestConcurrentSameData tests between 100 and 200 concurrent writes of
// identical data to the API.
func (s *TestSuite) TestConcurrentSameData(c *C) {
	b, err := rand.Int(rand.Reader, big.NewInt(int64(100)))
	c.Assert(err, IsNil)
	count := 100 + int(b.Int64())
	wg := sync.WaitGroup{}
	wg.Add(count)
	bi, err := rand.Int(rand.Reader, big.NewInt(int64(int(MiB)-1)))
	c.Assert(err, IsNil)
	size := int(bi.Int64()) + 1
	value := make([]byte, size)
	_, err = rand.Read(value)
	c.Assert(err, IsNil)
	writer := func() {
		resp, err := http.Post(s.url, "", bytes.NewBuffer(value))
		defer resp.Body.Close()
		c.Assert(err, IsNil)
		if resp.StatusCode != 200 && resp.StatusCode != 201 {
			c.Fatal("Expected status 200 or 201, but got", resp.StatusCode)
		}
		// Done
		wg.Done()
	}
	for i := 0; i < count; i++ {
		go writer()
	}
	wg.Wait()
}
Esempio n. 6
0
func VoteOne(c elliptic.Curve, px *big.Int, py *big.Int) *Checkbox {
	var err error
	h := new(Checkbox)
	h.s, err = rand.Int(rand.Reader, c.Params().N)
	if err != nil {
		panic("this shouldn't happen")
	}
	h.ax, h.ay = c.ScalarBaseMult(h.s.Bytes())
	tx, ty := c.ScalarMult(px, py, h.s.Bytes())
	h.bx, h.by = c.Add(tx, ty, c.Params().Gx, c.Params().Gy)
	//TODO: refactor: lots of similar logic here but parts very
	//c2, r2 fake, c1 r1 genuine
	//Form the faked challenge
	h.c2, err = rand.Int(rand.Reader, c.Params().N)
	if err != nil {
		panic("this shouldn't happen")
	}
	h.r2, err = rand.Int(rand.Reader, c.Params().N)
	if err != nil {
		panic("this shouldn't happen")
	}
	//Compute the commitments v3, v4 as the verifier will
	v3x, v3y := doublescalarmult(c, c.Params().Gx, c.Params().Gy, h.r2.Bytes(),
		h.ax, h.ay, h.c2.Bytes())
	v4x, v4y := doublescalarmult(c, px, py, h.r2.Bytes(),
		h.bx, h.by, h.c2.Bytes())
	//Commit to other side
	s1, err := rand.Int(rand.Reader, c.Params().N)
	if err != nil {
		panic("something deeply wrong")
	}
	v1x, v1y := c.ScalarBaseMult(s1.Bytes())
	v2x, v2y := c.ScalarMult(px, py, s1.Bytes())
	//Compute the total challenge
	var entries [6][]byte
	entries[0] = elliptic.Marshal(c, h.ax, h.ay)
	entries[1] = elliptic.Marshal(c, h.bx, h.by)
	entries[2] = elliptic.Marshal(c, v1x, v1y)
	entries[3] = elliptic.Marshal(c, v2x, v2y)
	entries[4] = elliptic.Marshal(c, v3x, v3y)
	entries[5] = elliptic.Marshal(c, v4x, v4y)
	challenge := sha256.Sum256(bytes.Join(entries[:], []byte{}))
	ctot := big.NewInt(0)
	ctot.SetBytes(challenge[:])
	ctot.Mod(ctot, c.Params().N)
	h.c1 = big.NewInt(0)
	h.c1.Sub(ctot, h.c2)
	h.c1.Mod(h.c1, c.Params().N)
	//r=s1-c1*h.s
	t := big.NewInt(0)
	t.Mul(h.c1, h.s)
	t.Mod(t, c.Params().N)
	t.Sub(s1, t)
	t.Mod(t, c.Params().N)
	h.r1 = t
	return h
}
Esempio n. 7
0
/**
 * Tests that the key is correctly updated in each node's storage system.
 */
func testSingleProposerUpdateKey(doneChan chan bool) {
	key := "b"

	// send first proposal
	randint, _ := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	rand.Seed(randint.Int64())
	value := rand.Uint32()
	if _, ok := pt.cliMap[1]; !ok {
		LOGE.Println("FAIL: missing node 1")
		doneChan <- false
		return
	}

	pnum, err := pt.GetNextProposalNumber(key, 1)
	reply, err := pt.Propose(key, value, pnum.N, 1)

	if err != nil {
		printFailErr("Propose", err)
		doneChan <- false
		return
	}

	// send second proposal
	randint, _ = crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	rand.Seed(randint.Int64())
	value = rand.Uint32()

	pnum2, err := pt.GetNextProposalNumber(key, 1)
	// the proposal numbers should be monotonically increasing
	if pnum.N >= pnum2.N {
		LOGE.Println("FAIL: newer proposal number is less than or equal to older proposal number")
		doneChan <- false
		return
	}

	reply, err = pt.Propose(key, value, pnum2.N, 1)
	if err != nil {
		printFailErr("Propose", err)
		doneChan <- false
		return
	}

	if !checkProposeReply(reply, key, value) {
		doneChan <- false
		return
	}

	if !checkGetValueAll(key, value) {
		doneChan <- false
		return
	}

	doneChan <- true
}
Esempio n. 8
0
func getNewIds() (dlId, cookieName string) {
	dlId = ""
	for {
		_, ex := currentBounces[dlId]
		if !ex && (len(dlId) > 0) {
			break
		}

		r, _ := rand.Int(rand.Reader, big.NewInt(maxRand))
		dlId = fmt.Sprintf("%s", hex.EncodeToString(r.Bytes()))
	}
	r, _ := rand.Int(rand.Reader, big.NewInt(maxRand))
	cookieName = fmt.Sprintf("Dl-%s", hex.EncodeToString(r.Bytes()))
	return
}
Esempio n. 9
0
File: util.go Progetto: jlisee/cbd
// Generates and opens a temporary file with a defined prefix and suffix
// This is the same api as ioutil.TempFile accept it accepts a suffix
//  TODO: see if this is too slow
func TempFile(dir, prefix string, suffix string) (f *os.File, err error) {
	if dir == "" {
		dir = os.TempDir()
	}

	// The maximum size of random file count
	// TODO: see if we can do this at package scope somehow
	var maxRand *big.Int = big.NewInt(0)
	maxRand.SetString("FFFFFFFFFFFFFFFF", 16)

	var randNum *big.Int

	for i := 0; i < 10000; i++ {
		// Generate random part of the path name
		randNum, err = rand.Int(rand.Reader, maxRand)

		if err != nil {
			return
		}

		// Transform to an int
		randString := hex.EncodeToString(randNum.Bytes())

		// Attempt to open file and fail if it already exists
		name := filepath.Join(dir, prefix+randString+suffix)
		f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
		if os.IsExist(err) {
			continue
		}
		break
	}
	return
}
Esempio n. 10
0
func (s *Sessions) Begin(userid string, displayName, photoUrl *string) (
	*http.Cookie, error) {
	n, err := rand.Int(rand.Reader, big.NewInt(1<<62))
	if err != nil {
		return nil, err
	}
	sid := n.String()

	var uv userView
	uv.Id = userid
	if displayName != nil {
		uv.Name = *displayName
	} else {
		uv.Name = ""
	}
	if photoUrl != nil {
		uv.PhotoUrl = *photoUrl
	} else {
		uv.PhotoUrl = "/images/unknown_avatar.png"
	}

	s.lock.Lock()
	s.sidToUser[sid] = uv
	s.lock.Unlock()

	cookie := http.Cookie{
		Name:  sidCookie,
		Value: sid,
	}
	return &cookie, nil
}
Esempio n. 11
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
}
func generateRandomName() string {
	n, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
	if err != nil {
		log.Fatalf("Unable to generate random container name: %v\n", err)
	}
	return fmt.Sprintf("image-inspector-%016x", n)
}
Esempio n. 13
0
func (s realSource) generate() *big.Int {
	randInt, err := rand.Int(rand.Reader, maxBigInt)
	if err != nil {
		panic(err)
	}
	return randInt
}
Esempio n. 14
0
func Handler(rw http.ResponseWriter, req *http.Request) {

	requestLogId, err := rand.Int(rand.Reader, big.NewInt(999999))
	if err != nil {
		glog.Errorf("Failed to get a random number. Err:%s", err)
	}

	context.Set(req, RequestLogIdKey, fmt.Sprintf("%06d", requestLogId))
	if glog.V(2) {
		glog.Infof("Session request tagged %06d started with url: %s", requestLogId, req.URL)
	}

	checkCredentials(req)

	router := mux.NewRouter()
	router.HandleFunc("/session/users", doUser).Methods("PUT")
	router.HandleFunc("/session/user/{SysUserId}", doUser).Methods("POST")
	router.HandleFunc("/session/user/{EmailAddr}/token/{Token}", verifyEmail).Methods("GET")
	router.HandleFunc("/session/login", doLogin).Methods("POST")
	router.HandleFunc("/session/login", getLogin).Methods("GET")
	router.HandleFunc("/session/reset/{EmailAddr}", getResetToken).Methods("GET")
	router.HandleFunc("/session/reset/{EmailAddr}/token/{Token}", useResetToken).Methods("GET")
	router.HandleFunc("/session/logout", doLogout).Methods("POST")

	router.ServeHTTP(rw, req)
}
Esempio n. 15
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)
}
Esempio n. 16
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
				}
			}
		}
	}
}
Esempio n. 17
0
func generateCert(privKey *rsa.PrivateKey, domain string) ([]byte, error) {
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, err
	}

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			CommonName: "ACME Challenge TEMP",
		},
		NotBefore: time.Now(),
		NotAfter:  time.Now().Add(365),

		KeyUsage:              x509.KeyUsageKeyEncipherment,
		BasicConstraintsValid: true,
		DNSNames:              []string{domain},
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, privKey)
	if err != nil {
		return nil, err
	}

	return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}), nil
}
Esempio n. 18
0
// randInt returns a random number from 0 to max - 1.
func randInt(max int) int {
	b, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
	if err != nil {
		log.Fatal(err)
	}
	return int(b.Int64())
}
Esempio n. 19
0
func rand(max *big.Int) int64 {
	i, err := urandom.Int(urandom.Reader, max)
	if err != nil {
		return prandom.Int63n(max.Int64())
	}
	return i.Int64()
}
Esempio n. 20
0
func main() {
	spec := options.NewOptions(mySpec).SetParseCallback(MyParseCallback)
	opt := spec.Parse(os.Args[1:])

	fmt.Printf("I will concatenate the files: %q\n", opt.Extra)
	if n {
		fmt.Println("I will number each line")
	}
	if e {
		fmt.Println("I will escape each line")
	}
	if r != 1 {
		fmt.Printf("I will repeat each line %d times\n", r)
	}
	if v > 0 {
		fmt.Printf("I will be verbose (level %d)\n", v)
	}
	fmt.Printf("Input charset: %s\n", in)
	fmt.Printf("Output charset: %s\n", out)

	fmt.Printf("Chance for a cookie: %.2f\n", c)
	var max = big.NewInt(1000)
	rnd, _ := rand.Int(rand.Reader, max)
	if cInt > rnd.Int64() {
		fmt.Println("*** You got a cookie! Yay! ***")
	}
}
Esempio n. 21
0
func (crtkit *CertKit) GenerateServer(subject pkix.Name, host, email string, NotBefore ...time.Time) error {
	var e error
	var derBytes []byte
	var notBefore time.Time

	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return errors.New(fmt.Sprintf("failed to generate private key: %s", err))
	}

	if len(NotBefore) > 0 {
		notBefore = NotBefore[0]
	} else {
		notBefore = time.Now()
	}
	serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
	if err != nil {
		return errors.New(fmt.Sprintf("failed to generate serial number: %s", err))
	}

	if host == "" {
		host, _ = os.Hostname()
	}

	Goose.Generator.Logf(6, "Certificate authority used: %#v", crtkit.CACert)

	template := x509.Certificate{
		SerialNumber:          serialNumber,
		Subject:               subject,
		IsCA:                  false,
		NotBefore:             notBefore,
		NotAfter:              notBefore.Add(365 * 24 * time.Hour),
		DNSNames:              []string{host, strings.Split(host, ".")[0]},
		AuthorityKeyId:        crtkit.CACert.SubjectKeyId,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageContentCommitment,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
		BasicConstraintsValid: true,
	}

	Goose.Generator.Logf(4, "X509 Template: %#v", template)

	if crtkit.CACert.CRLDistributionPoints != nil {
		template.CRLDistributionPoints = crtkit.CACert.CRLDistributionPoints
	} else {
		Goose.Generator.Logf(1, "Certificate authority without CRL distribution points")
	}

	crtkit.ServerKey = priv
	crtkit.ServerCert = &template
	derBytes, e = x509.CreateCertificate(rand.Reader, &template, crtkit.CACert, &priv.PublicKey, crtkit.CAKey)
	if e != nil {
		return errors.New(fmt.Sprintf("Failed to create certificate: %s", e))
	}
	Goose.Generator.Logf(4, "DER Certificate: %s", derBytes)
	crtkit.ServerCertPem = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	crtkit.ServerKeyPem = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	Goose.Generator.Logf(4, "PEM Certificate: %s", crtkit.ServerCertPem)

	return nil
}
Esempio n. 22
0
// GenerateSerialNumber generates a serial number suitable for a certificate
func GenerateSerialNumber() (*big.Int, error) {
	serial, err := rand.Int(rand.Reader, (&big.Int{}).Exp(big.NewInt(2), big.NewInt(159), nil))
	if err != nil {
		return nil, InternalError{Err: fmt.Sprintf("error generating serial number: %v", err)}
	}
	return serial, nil
}
Esempio n. 23
0
// This function handles the create requests.
func create_keys(base int, count int, r [2]int) {
	var key int
	for i := 0; i < count; i++ {
		key = base + i
		m, _ := rand.Int(rand.Reader, big.NewInt(int64(r[1]-r[0])))
		r1 := int(m.Int64()) + r[0]
		value := RandStringBytesRmndr(r1)
		start = time.Now()
		_, err := client.Set(toString(key), value, 1000)
		elapsed := time.Since(start)
		log.Println("key %s took %s", key, elapsed)

		// This part is helpful in generating the commandline report
		var errStr string
		if err != nil {
			errStr = err.Error()
		}
		results <- &result{
			errStr:   errStr,
			duration: elapsed,
		}

	}
	defer wg.Done()
}
Esempio n. 24
0
// TestAESRelatedUtilFunctions tests various functions commonly used in fabric wrt AES
func TestAESRelatedUtilFunctions(t *testing.T) {

	key, err := GetRandomBytes(32)
	if err != nil {
		t.Fatalf("Failed generating AES key [%s]", err)
	}

	for i := 1; i < 100; i++ {
		l, err := rand.Int(rand.Reader, big.NewInt(1024))
		if err != nil {
			t.Fatalf("Failed generating AES key [%s]", err)
		}
		msg, err := GetRandomBytes(int(l.Int64()) + 1)
		if err != nil {
			t.Fatalf("Failed generating AES key [%s]", err)
		}

		ct, err := AESCBCPKCS7Encrypt(key, msg)
		if err != nil {
			t.Fatalf("Failed encrypting [%s]", err)
		}

		msg2, err := AESCBCPKCS7Decrypt(key, ct)
		if err != nil {
			t.Fatalf("Failed decrypting [%s]", err)
		}

		if 0 != bytes.Compare(msg, msg2) {
			t.Fatalf("Wrong decryption output [%x][%x]", msg, msg2)
		}

	}

}
Esempio n. 25
0
func generateDerCert(privKey *rsa.PrivateKey, expiration time.Time, domain string) ([]byte, error) {
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, err
	}

	if expiration.IsZero() {
		expiration = time.Now().Add(365)
	}

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			CommonName: "ACME Challenge TEMP",
		},
		NotBefore: time.Now(),
		NotAfter:  expiration,

		KeyUsage:              x509.KeyUsageKeyEncipherment,
		BasicConstraintsValid: true,
		DNSNames:              []string{domain},
	}

	return x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, privKey)
}
Esempio n. 26
0
/**
 * Tests that a single proposal should be able to
 * successfully be committed to every node.
 */
func testSingleProposerSingleProposal(doneChan chan bool) {
	key := "a"
	randint, _ := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	rand.Seed(randint.Int64())
	value := rand.Uint32()
	if _, ok := pt.cliMap[1]; !ok {
		LOGE.Println("FAIL: missing node 1")
		doneChan <- false
		return
	}

	pnum, err := pt.GetNextProposalNumber(key, 1)
	reply, err := pt.Propose(key, value, pnum.N, 1)
	if err != nil {
		printFailErr("Propose", err)
		doneChan <- false
		return
	}

	if !checkProposeReply(reply, key, value) {
		doneChan <- false
		return
	}

	if !checkGetValueAll(key, value) {
		doneChan <- false
		return
	}

	doneChan <- true
}
Esempio n. 27
0
// newTemplate returns a partially-filled template.
// It should be further populated based on whether the cert is for a CA or node.
func newTemplate(commonName string) (*x509.Certificate, error) {
	// Generate a random serial number.
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, err
	}

	notBefore := timeutil.Now().Add(validFrom)
	notAfter := notBefore.Add(validFor)

	cert := &x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"Cockroach"},
			CommonName:   commonName,
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

		KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
	}

	return cert, nil
}
Esempio n. 28
0
func (s source) Int63() int64 {
	i, err := crand.Int(s, maxInt63)
	if err != nil {
		panic(fmt.Errorf("crypto/rand.Int returned error: %v", err))
	}
	return i.Int64()
}
Esempio n. 29
0
func NewSignedCertificate(cfg CertConfig, key *rsa.PrivateKey, caCert *x509.Certificate, caKey *rsa.PrivateKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64))
	if err != nil {
		return nil, err
	}

	certTmpl := x509.Certificate{
		Subject: pkix.Name{
			CommonName:   cfg.CommonName,
			Organization: caCert.Subject.Organization,
		},
		DNSNames:     cfg.AltNames.DNSNames,
		IPAddresses:  cfg.AltNames.IPs,
		SerialNumber: serial,
		NotBefore:    caCert.NotBefore,
		NotAfter:     time.Now().Add(Duration365d).UTC(),
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
	}
	certDERBytes, err := x509.CreateCertificate(rand.Reader, &certTmpl, caCert, key.Public(), caKey)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(certDERBytes)
}
Esempio n. 30
0
func SessionMiddleware(cs *sessions.CookieStore) routing.Handler {
	return func(c *routing.Context) error {
		session, err := cs.Get(c.Request, SESSION_NAME)
		if err != nil {
			return routing.NewHTTPError(http.StatusInternalServerError, err.Error())
		}
		if session.IsNew {
			randId, _ := rand.Int(rand.Reader, big.NewInt(100000))
			randInt, _ := rand.Int(rand.Reader, big.NewInt(3))
			session.Values["id"] = randId.String()
			session.Values["uid"] = randInt.String()
		}
		session.Save(c.Request, c.Response)
		return nil
	}
}