Exemple #1
0
func GenerateSigningTestKey(sigAlg SignatureAlgorithm) (sig, ver interface{}) {
	switch sigAlg {
	case RS256, RS384, RS512, PS256, PS384, PS512:
		sig = rsaTestKey
		ver = &rsaTestKey.PublicKey
	case HS256, HS384, HS512:
		sig, _, _ = randomKeyGenerator{size: 16}.genKey()
		ver = sig
	case ES256:
		key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
		sig = key
		ver = &key.PublicKey
	case ES384:
		key, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
		sig = key
		ver = &key.PublicKey
	case ES512:
		key, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
		sig = key
		ver = &key.PublicKey
	default:
		panic("Must update test case")
	}

	return
}
Exemple #2
0
func init() {
	raw256, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	ecdsaKey, _ = NewSignerFromKey(raw256)

	raw384, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
	ecdsa384Key, _ = NewSignerFromKey(raw384)

	raw521, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
	ecdsa521Key, _ = NewSignerFromKey(raw521)

	// Create a cert and sign it for use in tests.
	testCert := &OpenSSHCertV01{
		Nonce:           []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil
		Key:             ecdsaKey.PublicKey(),
		ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage
		ValidAfter:      0,                              // unix epoch
		ValidBefore:     maxUint64,                      // The end of currently representable time.
		Reserved:        []byte{},                       // To pass reflect.DeepEqual after marshal & parse, this must be non-nil
		SignatureKey:    rsaKey.PublicKey(),
	}
	sigBytes, _ := rsaKey.Sign(rand.Reader, testCert.BytesForSigning())
	testCert.Signature = &signature{
		Format: testCert.SignatureKey.PublicKeyAlgo(),
		Blob:   sigBytes,
	}
	testCertKey = &testSigner{
		Signer: ecdsaKey,
		pub:    testCert,
	}
}
Exemple #3
0
func TestBadPubs(t *testing.T) {
	priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}

	bad1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}

	bad2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}
	bad2.Curve = elliptic.P521()

	var bad3 *ecdsa.PublicKey
	if _, err = ECDH(priv, bad3); err == nil {
		t.Fatalf("ECDH should fail with nil key")
	} else if _, err = ECDH(priv, &bad1.PublicKey); err == nil {
		t.Fatalf("ECDH should fail with mismatched curve")
	} else if _, err = ECDH(priv, &bad2.PublicKey); err == nil {
		t.Fatalf("ECDH should fail with wrong curve")
	}
}
func TestProcessRequestUserKey(t *testing.T) {
	server, client := setupHttp(200, "application/json", `{"success":true,"message":"my message"}`)
	defer server.Close()

	// Create Test Keys
	userKey := new(ecdsa.PrivateKey)
	userKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

	partnerKey := new(ecdsa.PrivateKey)
	partnerKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

	// Sign User's Public Key (SHA1 Hash)  with Partner's Key
	userPubkey, _ := x509.MarshalPKIXPublicKey(&userKey.PublicKey)
	hash := sha1.New().Sum(userPubkey)
	r, s, _ := ecdsa.Sign(rand.Reader, partnerKey, hash)
	sigToMarshal := &ecdsaSignature{R: r, S: s}
	keySig, _ := asn1.Marshal(sigToMarshal)

	userKeyPartner := &NetkiPartner{UserKey: userKey, KeySigningKey: &partnerKey.PublicKey, KeySignature: keySig}

	requester := &NetkiRequester{HTTPClient: client}
	result, err := requester.ProcessRequest(userKeyPartner, "http://domain.com/uri", "GET", "")

	assert.Equal(t, nil, err)
	assert.NotEqual(t, nil, result)
}
Exemple #5
0
// Generates a compatible OpenSSH private key. The key is in the
// raw Go key format. To convert this to a PEM encoded key, see
// MarshalPrivate.
func GenerateKey(keytype Type, size int) (key interface{}, err error) {
	switch keytype {
	case KEY_RSA:
		if size < 2048 {
			return nil, ErrInvalidKeySize
		}
		var rsakey *rsa.PrivateKey
		rsakey, err = rsa.GenerateKey(PRNG, size)
		if err != nil {
			return
		}
		key = rsakey
	case KEY_ECDSA:
		var eckey *ecdsa.PrivateKey
		switch size {
		case 256:
			eckey, err = ecdsa.GenerateKey(elliptic.P256(), PRNG)
		case 384:
			eckey, err = ecdsa.GenerateKey(elliptic.P384(), PRNG)
		case 521:
			eckey, err = ecdsa.GenerateKey(elliptic.P521(), PRNG)
		default:
			return nil, ErrInvalidKeySize
		}
		key = eckey
	case KEY_DSA:
		var sizes dsa.ParameterSizes
		switch size {
		case 1024:
			sizes = dsa.L1024N160
		case 2048:
			sizes = dsa.L2048N256
		case 3072:
			sizes = dsa.L3072N256
		default:
			err = ErrInvalidKeySize
			return
		}

		params := dsa.Parameters{}
		err = dsa.GenerateParameters(&params, rand.Reader, sizes)
		if err != nil {
			return
		}

		dsakey := &dsa.PrivateKey{
			PublicKey: dsa.PublicKey{
				Parameters: params,
			},
		}
		err = dsa.GenerateKey(dsakey, rand.Reader)
		if err != nil {
			return
		}
		key = dsakey
	}

	return
}
Exemple #6
0
func TestGenerateKey(t *testing.T) {
	var err error

	alicePriv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}

	bobPriv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}
}
Exemple #7
0
func TestSetupKeys(t *testing.T) {
	var err error

	alice, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}

	bob, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}
}
Exemple #8
0
func TestLogCache(t *testing.T) {
	cache := logCache{
		logs: make(map[string]*Log),
	}

	// Adding a log with an invalid base64 public key should error
	_, err := cache.AddLog("www.test.com", "1234")
	test.AssertError(t, err, "AddLog() with invalid base64 pk didn't error")

	// Adding a log with an invalid URI should error
	_, err = cache.AddLog(":", "")
	test.AssertError(t, err, "AddLog() with an invalid log URI didn't error")

	// Create one keypair & base 64 public key
	k1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	test.AssertNotError(t, err, "ecdsa.GenerateKey() failed for k1")
	der1, err := x509.MarshalPKIXPublicKey(&k1.PublicKey)
	test.AssertNotError(t, err, "x509.MarshalPKIXPublicKey(der1) failed")
	k1b64 := base64.StdEncoding.EncodeToString(der1)

	// Create a second keypair & base64 public key
	k2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	test.AssertNotError(t, err, "ecdsa.GenerateKey() failed for k2")
	der2, err := x509.MarshalPKIXPublicKey(&k2.PublicKey)
	test.AssertNotError(t, err, "x509.MarshalPKIXPublicKey(der2) failed")
	k2b64 := base64.StdEncoding.EncodeToString(der2)

	// Adding the first log should not produce an error
	l1, err := cache.AddLog("http://log.one.example.com", k1b64)
	test.AssertNotError(t, err, "cache.AddLog() failed for log 1")
	test.AssertEquals(t, cache.Len(), 1)
	test.AssertEquals(t, l1.uri, "http://log.one.example.com")
	test.AssertEquals(t, l1.logID, k1b64)

	// Adding it again should not produce any errors, or increase the Len()
	l1, err = cache.AddLog("http://log.one.example.com", k1b64)
	test.AssertNotError(t, err, "cache.AddLog() failed for second add of log 1")
	test.AssertEquals(t, cache.Len(), 1)
	test.AssertEquals(t, l1.uri, "http://log.one.example.com")
	test.AssertEquals(t, l1.logID, k1b64)

	// Adding a second log should not error and should increase the Len()
	l2, err := cache.AddLog("http://log.two.example.com", k2b64)
	test.AssertNotError(t, err, "cache.AddLog() failed for log 2")
	test.AssertEquals(t, cache.Len(), 2)
	test.AssertEquals(t, l2.uri, "http://log.two.example.com")
	test.AssertEquals(t, l2.logID, k2b64)
}
Exemple #9
0
func TestSignWithP384(t *testing.T) {
	message := []byte("Hello, world!")

	key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
	if err != nil {
		t.Error(err)
		return
	}

	signature, err := Sign(message, key)
	if err != nil {
		t.Error(err)
		return
	}

	if !Verify(message, signature, &key.PublicKey) {
		t.Error("signature was not correct")
		return
	}

	message[0] ^= 0xff
	if Verify(message, signature, &key.PublicKey) {
		t.Error("signature was good for altered message")
	}
}
Exemple #10
0
// Generate generates a key as specified in the request. Currently,
// only ECDSA and RSA are supported.
func (kr *BasicKeyRequest) Generate() (crypto.PrivateKey, error) {
	log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo(), kr.Size())
	switch kr.Algo() {
	case "rsa":
		if kr.Size() < 2048 {
			return nil, errors.New("RSA key is too weak")
		}
		if kr.Size() > 8192 {
			return nil, errors.New("RSA key size too large")
		}
		return rsa.GenerateKey(rand.Reader, kr.Size())
	case "ecdsa":
		var curve elliptic.Curve
		switch kr.Size() {
		case curveP256:
			curve = elliptic.P256()
		case curveP384:
			curve = elliptic.P384()
		case curveP521:
			curve = elliptic.P521()
		default:
			return nil, errors.New("invalid curve")
		}
		return ecdsa.GenerateKey(curve, rand.Reader)
	default:
		return nil, errors.New("invalid algorithm")
	}
}
Exemple #11
0
// Generate generates a key as specified in the request. Currently,
// only ECDSA and RSA are supported.
func (kr *KeyRequest) Generate() (interface{}, error) {
	log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo, kr.Size)
	switch kr.Algo {
	case "rsa":
		if kr.Size < 2048 {
			return nil, errors.New("RSA key is too weak")
		}
		return rsa.GenerateKey(rand.Reader, kr.Size)
	case "ecdsa":
		var curve elliptic.Curve
		switch kr.Size {
		case curveP256:
			curve = elliptic.P256()
		case curveP384:
			curve = elliptic.P384()
		case curveP521:
			curve = elliptic.P521()
		default:
			return nil, errors.New("invalid curve")
		}
		return ecdsa.GenerateKey(curve, rand.Reader)
	default:
		return nil, errors.New("invalid algorithm")
	}
}
// Cert generates a new TLS certificate for hostname and signs it using caPrivKey.
func Cert(t *testing.T, caCert *x509.Certificate, caPrivKey *ecdsa.PrivateKey, hostname string, rnd io.Reader) tls.Certificate {
	if rnd == nil {
		rnd = rand.Reader
	}
	privKey, err := ecdsa.GenerateKey(elliptic.P256(), rnd)
	if err != nil {
		t.Fatal(err)
	}
	certTemplate := &x509.Certificate{
		Subject:      pkix.Name{CommonName: hostname},
		SerialNumber: newSerial(t, rnd),
		NotBefore:    time.Now(),
		NotAfter:     time.Now().Add(1 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
	}
	if ip := net.ParseIP(hostname); ip != nil {
		certTemplate.IPAddresses = []net.IP{ip}
	}

	certDER, err := x509.CreateCertificate(rnd, certTemplate, caCert, &privKey.PublicKey, caPrivKey)
	if err != nil {
		t.Fatal(err)
	}
	cert, err := x509.ParseCertificate(certDER)
	if err != nil {
		t.Fatal(err)
	}
	return tls.Certificate{Certificate: [][]byte{certDER}, PrivateKey: privKey, Leaf: cert}
}
Exemple #13
0
func (ca *CA) createCAKeyPair(name string) *ecdsa.PrivateKey {
	caLogger.Debug("Creating CA key pair.")

	curve := primitives.GetDefaultCurve()

	priv, err := ecdsa.GenerateKey(curve, rand.Reader)
	if err == nil {
		raw, _ := x509.MarshalECPrivateKey(priv)
		cooked := pem.EncodeToMemory(
			&pem.Block{
				Type:  "ECDSA PRIVATE KEY",
				Bytes: raw,
			})
		err = ioutil.WriteFile(ca.path+"/"+name+".priv", cooked, 0644)
		if err != nil {
			caLogger.Panic(err)
		}

		raw, _ = x509.MarshalPKIXPublicKey(&priv.PublicKey)
		cooked = pem.EncodeToMemory(
			&pem.Block{
				Type:  "ECDSA PUBLIC KEY",
				Bytes: raw,
			})
		err = ioutil.WriteFile(ca.path+"/"+name+".pub", cooked, 0644)
		if err != nil {
			caLogger.Panic(err)
		}
	}
	if err != nil {
		caLogger.Panic(err)
	}

	return priv
}
Exemple #14
0
// newPrincipalKey generates an ECDSA (public, private) key pair.
func newPrincipalKey() (publicKey, *ecdsa.PrivateKey, error) {
	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}
	return newECDSAPublicKey(&priv.PublicKey), priv, nil
}
Exemple #15
0
// GeneratePrivateKey is a wrapper for ecdsa.GenerateKey that returns a PrivateKey
// instead of the normal ecdsa.PrivateKey.
func GeneratePrivateKey(curve *KoblitzCurve) (*PrivateKey, error) {
	key, err := ecdsa.GenerateKey(curve, rand.Reader)
	if err != nil {
		return nil, err
	}
	return (*PrivateKey)(key), nil
}
Exemple #16
0
// certState returns a new or existing certState.
// If a new certState is returned, state.exist is false and the state is locked.
// The returned error is non-nil only in the case where a new state could not be created.
func (m *Manager) certState(domain string) (*certState, error) {
	m.stateMu.Lock()
	defer m.stateMu.Unlock()
	if m.state == nil {
		m.state = make(map[string]*certState)
	}
	// existing state
	if state, ok := m.state[domain]; ok {
		return state, nil
	}

	// new locked state
	var (
		err error
		key crypto.Signer
	)
	if m.ForceRSA {
		key, err = rsa.GenerateKey(rand.Reader, 2048)
	} else {
		key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	}
	if err != nil {
		return nil, err
	}

	state := &certState{
		key:    key,
		locked: true,
	}
	state.Lock() // will be unlocked by m.certState caller
	m.state[domain] = state
	return state, nil
}
// createPasswordRec creates a new record from a username and password
func createPasswordRec(password string, admin bool) (newRec PasswordRecord, err error) {
	newRec.Type = DefaultRecordType

	if newRec.PasswordSalt, err = symcrypt.MakeRandom(16); err != nil {
		return
	}

	if newRec.HashedPassword, err = hashPassword(password, newRec.PasswordSalt); err != nil {
		return
	}

	if newRec.KeySalt, err = symcrypt.MakeRandom(16); err != nil {
		return
	}

	passKey, err := derivePasswordKey(password, newRec.KeySalt)
	if err != nil {
		return
	}

	// generate a key pair
	switch DefaultRecordType {
	case RSARecord:
		var rsaPriv *rsa.PrivateKey
		rsaPriv, err = rsa.GenerateKey(rand.Reader, 2048)
		if err != nil {
			return
		}
		// encrypt RSA key with password key
		if err = encryptRSARecord(&newRec, rsaPriv, passKey); err != nil {
			return
		}
		newRec.RSAKey.RSAPublic = rsaPriv.PublicKey
	case ECCRecord:
		var ecPriv *ecdsa.PrivateKey
		ecPriv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
		if err != nil {
			return
		}
		// encrypt ECDSA key with password key
		if err = encryptECCRecord(&newRec, ecPriv, passKey); err != nil {
			return
		}
		newRec.ECKey.ECPublic = ecPriv.PublicKey
	}

	// encrypt AES key with password key
	aesKey, err := symcrypt.MakeRandom(16)
	if err != nil {
		return
	}

	if newRec.AESKey, err = encryptECB(aesKey, passKey); err != nil {
		return
	}

	newRec.Admin = admin

	return
}
Exemple #18
0
func generatePriv() (*ecdsa.PrivateKey, error) {
	priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
	if err != nil {
		return nil, err
	}
	return priv, nil
}
Exemple #19
0
// GenerateKeys returns a new key pair, with the private and public key
// encoded in PEM format.
func GenerateKeys() (privKey []byte, pubKey []byte, err error) {
	// Generate a new key pair
	key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	// Marshal the private key
	bs, err := x509.MarshalECPrivateKey(key)
	if err != nil {
		return nil, nil, err
	}

	// Encode it in PEM format
	privKey = pem.EncodeToMemory(&pem.Block{
		Type:  "EC PRIVATE KEY",
		Bytes: bs,
	})

	// Marshal the public key
	bs, err = x509.MarshalPKIXPublicKey(key.Public())
	if err != nil {
		return nil, nil, err
	}

	// Encode it in PEM format
	pubKey = pem.EncodeToMemory(&pem.Block{
		Type:  "EC PUBLIC KEY",
		Bytes: bs,
	})

	return
}
Exemple #20
0
func TestECDSAVerifierOtherCurves(t *testing.T) {
	curves := []elliptic.Curve{elliptic.P256(), elliptic.P384(), elliptic.P521()}

	for _, curve := range curves {
		ecdsaPrivKey, err := ecdsa.GenerateKey(curve, rand.Reader)

		// Get a DER-encoded representation of the PublicKey
		ecdsaPubBytes, err := x509.MarshalPKIXPublicKey(&ecdsaPrivKey.PublicKey)
		assert.NoError(t, err, "failed to marshal public key")

		// Get a DER-encoded representation of the PrivateKey
		ecdsaPrivKeyBytes, err := x509.MarshalECPrivateKey(ecdsaPrivKey)
		assert.NoError(t, err, "failed to marshal private key")

		testECDSAPubKey := data.NewECDSAPublicKey(ecdsaPubBytes)
		testECDSAKey, err := data.NewECDSAPrivateKey(testECDSAPubKey, ecdsaPrivKeyBytes)
		assert.NoError(t, err, "failed to read private key")

		// Sign some data using ECDSA
		message := []byte("test data for signing")
		hashed := sha256.Sum256(message)
		signedData, err := ecdsaSign(testECDSAKey, hashed[:])
		assert.NoError(t, err)

		// Create and call Verify on the verifier
		ecdsaVerifier := ECDSAVerifier{}
		err = ecdsaVerifier.Verify(testECDSAKey, signedData, message)
		assert.NoError(t, err, "expecting success but got error while verifying data using ECDSA")

		// Make sure an invalid signature fails verification
		signedData[0]++
		err = ecdsaVerifier.Verify(testECDSAKey, signedData, message)
		assert.Error(t, err, "expecting error but got success while verifying data using ECDSA")
	}
}
Exemple #21
0
// generates a multiple-certificate file with both RSA and ECDSA certs and
// returns the filename so that cleanup can be deferred.
func generateMultiCert(t *testing.T) string {
	tempFile, err := ioutil.TempFile("/tmp", "cert-test")
	defer tempFile.Close()
	assert.NoError(t, err)

	rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
	assert.NoError(t, err)
	ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	assert.NoError(t, err)
	template, err := trustmanager.NewCertificate("gun")
	assert.NoError(t, err)

	for _, key := range []crypto.Signer{rsaKey, ecKey} {
		derBytes, err := x509.CreateCertificate(
			rand.Reader, template, template, key.Public(), key)
		assert.NoError(t, err)

		cert, err := x509.ParseCertificate(derBytes)
		assert.NoError(t, err)

		pemBytes := trustmanager.CertToPEM(cert)
		nBytes, err := tempFile.Write(pemBytes)
		assert.NoError(t, err)
		assert.Equal(t, nBytes, len(pemBytes))
	}
	return tempFile.Name()
}
Exemple #22
0
func TestKeyLength(t *testing.T) {
	expNil := 0
	recNil := KeyLength(nil)
	if expNil != recNil {
		t.Fatal("KeyLength on nil did not return 0")
	}

	expNonsense := 0
	inNonsense := "string?"
	outNonsense := KeyLength(inNonsense)
	if expNonsense != outNonsense {
		t.Fatal("KeyLength malfunctioning on nonsense input")
	}

	//test the ecdsa branch
	ecdsaPriv, _ := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
	ecdsaIn, _ := ecdsaPriv.Public().(*ecdsa.PublicKey)
	expEcdsa := ecdsaIn.Curve.Params().BitSize
	outEcdsa := KeyLength(ecdsaIn)
	if expEcdsa != outEcdsa {
		t.Fatal("KeyLength malfunctioning on ecdsa input")
	}

	//test the rsa branch
	rsaPriv, _ := rsa.GenerateKey(rand.Reader, 256)
	rsaIn, _ := rsaPriv.Public().(*rsa.PublicKey)
	expRsa := rsaIn.N.BitLen()
	outRsa := KeyLength(rsaIn)

	if expRsa != outRsa {
		t.Fatal("KeyLength malfunctioning on rsa input")
	}
}
Exemple #23
0
func TestECDSASHA2PrivateKey(t *testing.T) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	spki_key := PrivateKey{HashKey{}, *key}
	//t.Log(spki_key.String())
	string_key, _, err := sexprs.Parse([]byte(spki_key.String()))
	if err != nil {
		t.Fatal(err)
	}
	byte_key, _, err := sexprs.Parse(spki_key.Sexp().Pack())
	if err != nil {
		t.Fatal(err)
	}
	if !string_key.Equal(byte_key) {
		t.Fatal("String- and byte-read keys differ")
	}
	eval_key, err := EvalPrivateKey(string_key)
	if err != nil {
		t.Fatal(err)
	}
	if key.X.Cmp(eval_key.X) != 0 {
		t.Fatal("Differing X: %s vs. %x", key.X, eval_key.X)
	}
	if key.Y.Cmp(eval_key.Y) != 0 {
		t.Fatal("Differing X: %s vs. %x", key.Y, eval_key.Y)
	}
	if key.D.Cmp(eval_key.D) != 0 {
		t.Fatal("Differing X: %s vs. %x", key.D, eval_key.D)
	}
}
Exemple #24
0
func GenerateEmptyConfig() (*tls.Config, error) {
	priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
	if err != nil {
		return nil, err
	}
	number, err := rand.Int(rand.Reader, big.NewInt(0).Lsh(big.NewInt(1), 128))
	if err != nil {
		return nil, err
	}
	cert := &x509.Certificate{
		SerialNumber:          number,
		NotBefore:             time.Now(),
		NotAfter:              time.Now().Add(time.Hour * 24),
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
		BasicConstraintsValid: true,
	}
	certbytes, err := x509.CreateCertificate(rand.Reader, cert, cert, &priv.PublicKey, priv)
	if err != nil {
		return nil, err
	}

	ct := tls.Certificate{[][]byte{certbytes}, priv, nil, cert}
	c := &tls.Config{InsecureSkipVerify: true}
	c.Certificates = append(c.Certificates, ct)
	c.NextProtos = []string{Proto}
	return c, nil
}
Exemple #25
0
// Creates a self-signed certificate and matching private key suitable for
// responding to a TLS-SNI challenge. hostname should be a hostname returned by
// TLSSNIHostname.
func CreateTLSSNICertificate(hostname string) (certDER []byte, privateKey crypto.PrivateKey, err error) {
	crt := x509.Certificate{
		Subject: pkix.Name{
			CommonName: hostname,
		},
		Issuer: pkix.Name{
			CommonName: hostname,
		},
		SerialNumber:          big.NewInt(1),
		NotBefore:             time.Now().Add(-24 * time.Hour),
		NotAfter:              time.Now().Add(365 * 24 * time.Hour),
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		DNSNames:              []string{hostname},
	}

	pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return
	}

	certDER, err = x509.CreateCertificate(rand.Reader, &crt, &crt, &pk.PublicKey, pk)
	privateKey = pk
	return
}
// CA returns a new CA certificate, a pool containing that certificate, and the
// corresponding private key.
func CA(t *testing.T, rnd io.Reader) (*x509.Certificate, *x509.CertPool, *ecdsa.PrivateKey) {
	if rnd == nil {
		rnd = rand.Reader
	}
	var err error
	caPrivKey, err := ecdsa.GenerateKey(elliptic.P256(), rnd)
	if err != nil {
		t.Fatal(err)
	}
	caCertTemplate := &x509.Certificate{
		Subject:               pkix.Name{CommonName: "testingCA"},
		SerialNumber:          newSerial(t, rnd),
		NotBefore:             time.Now(),
		NotAfter:              time.Now().Add(time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:       true,
		MaxPathLen: 4,
	}
	caCertDER, err := x509.CreateCertificate(rnd, caCertTemplate, caCertTemplate, &caPrivKey.PublicKey, caPrivKey)
	if err != nil {
		t.Fatal(err)
	}
	caCert, err := x509.ParseCertificate(caCertDER)
	if err != nil {
		t.Fatal(err)
	}

	caPool := x509.NewCertPool()
	caPool.AddCert(caCert)
	return caCert, caPool, caPrivKey
}
Exemple #27
0
func TestECDSASignerPrivateKey(t *testing.T) {
	ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	priv := NewSignerPrivateKey(time.Now(), &ecdsaSigner{ecdsaPriv})

	if priv.PubKeyAlgo != PubKeyAlgoECDSA {
		t.Fatal("NewSignerPrivateKey should have made a ECSDA private key")
	}

	sig := &Signature{
		PubKeyAlgo: PubKeyAlgoECDSA,
		Hash:       crypto.SHA256,
	}
	msg := []byte("Hello World!")

	h, err := populateHash(sig.Hash, msg)
	if err != nil {
		t.Fatal(err)
	}
	if err := sig.Sign(h, priv, nil); err != nil {
		t.Fatal(err)
	}

	if h, err = populateHash(sig.Hash, msg); err != nil {
		t.Fatal(err)
	}
	if err := priv.VerifySignature(h, sig); err != nil {
		t.Fatal(err)
	}
}
Exemple #28
0
func init() {
	var filename string
	var err error
	flag.StringVar(&filename, "file", "key.txt",
		"file containing secret key")
	flag.Parse()
	f, err := ioutil.ReadFile(filename)
	if err != nil {
		panic(err)
	}
	b := sha512.Sum512(f)
	key, err = ecdsa.GenerateKey(elliptic.P256(), bytes.NewReader(b[:]))
	if err != nil {
		panic(err)
	}
	err = rs.Open("./test.db", key)
	if err != nil {
		panic(err)
	}
	m = new(mic.Reader)
	go func() {
		for {
			var bits [32]byte
			m.Read(bits[:])
			_, err := rs.New(bits)
			if err != nil {
				fmt.Printf("error making record %s\n", err)
			}
			time.Sleep(60 * time.Second)
		}
	}()
}
Exemple #29
0
func (ctrl *Controller) AddHostKeyFromCluster(host string) error {
	generate := func() (string, error) {
		// Generate an ECDSA key.
		key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
		if err != nil {
			return "", err
		}
		derBytes, err := x509.MarshalECPrivateKey(key)
		if err != nil {
			return "", err
		}
		w := &bytes.Buffer{}
		if err := pem.Encode(w, &pem.Block{Type: "EC PRIVATE KEY", Bytes: derBytes}); err != nil {
			return "", err
		}
		return w.String(), nil
	}
	pemString, err := ctrl.cluster.GetValueWithDefault(fmt.Sprintf("console/%s", host), generate)
	if err != nil {
		return fmt.Errorf("failed to get/generate host key: %s", err)
	}

	signer, err := ssh.ParsePrivateKey([]byte(pemString))
	if err != nil {
		return fmt.Errorf("failed to parse host key: %s", err)
	}

	ctrl.config.AddHostKey(signer)
	return nil
}
Exemple #30
0
// Encrypt secures and authenticates its input using the public key
// using ECDHE with AES-128-CBC-HMAC-SHA1.
func Encrypt(pub *ecdsa.PublicKey, in []byte) (out []byte, err error) {
	ephemeral, err := ecdsa.GenerateKey(Curve(), rand.Reader)
	if err != nil {
		return
	}
	x, _ := pub.Curve.ScalarMult(pub.X, pub.Y, ephemeral.D.Bytes())
	if x == nil {
		return nil, errors.New("Failed to generate encryption key")
	}
	shared := sha256.Sum256(x.Bytes())
	iv, err := symcrypt.MakeRandom(16)
	if err != nil {
		return
	}

	paddedIn := padding.AddPadding(in)
	ct, err := symcrypt.EncryptCBC(paddedIn, iv, shared[:16])
	if err != nil {
		return
	}

	ephPub := elliptic.Marshal(pub.Curve, ephemeral.PublicKey.X, ephemeral.PublicKey.Y)
	out = make([]byte, 1+len(ephPub)+16)
	out[0] = byte(len(ephPub))
	copy(out[1:], ephPub)
	copy(out[1+len(ephPub):], iv)
	out = append(out, ct...)

	h := hmac.New(sha1.New, shared[16:])
	h.Write(iv)
	h.Write(ct)
	out = h.Sum(out)
	return
}