Ejemplo n.º 1
0
func TestSecret(t *testing.T) {
	iniKey, _ := rsa.GenerateKey(rand.Reader, 1024)
	accKey, _ := rsa.GenerateKey(rand.Reader, 1024)

	for i, tt := range stsTests {
		iniSes, _ := New(bytes.NewReader(tt.iniExponent.Bytes()), tt.group, tt.generator, tt.cipher, tt.bits, tt.hash)
		accSes, _ := New(bytes.NewReader(tt.accExponent.Bytes()), tt.group, tt.generator, tt.cipher, tt.bits, tt.hash)
		iniExp, _ := iniSes.Initiate()
		accExp, accToken, _ := accSes.Accept(rand.Reader, accKey, iniExp)
		iniToken, _ := iniSes.Verify(rand.Reader, iniKey, &accKey.PublicKey, accExp, accToken)
		accSes.Finalize(&iniKey.PublicKey, iniToken)

		iniSecret, err := iniSes.Secret()
		if err != nil {
			t.Errorf("test %d: failed to retrieve initiator's secret: %v", i, err)
		} else {
			accSecret, err := accSes.Secret()
			if err != nil {
				t.Errorf("test %d: failed to retrieve acceptor's secret: %v", i, err)
			} else {
				if !bytes.Equal(iniSecret, accSecret) {
					t.Errorf("test %d: secret mismatch: initiator %v, acceptor %v", i, iniSecret, accSecret)
				}
			}
		}
	}
}
Ejemplo n.º 2
0
func (gkms *gpgKeypairMgrSuite) TestGetNotUnique(c *C) {
	mockGPG := func(prev asserts.GPGRunner, input []byte, args ...string) ([]byte, error) {
		if args[1] == "--list-secret-keys" {
			return prev(input, args...)
		}
		c.Assert(args[1], Equals, "--export")

		pk1, err := rsa.GenerateKey(rand.Reader, 512)
		c.Assert(err, IsNil)
		pk2, err := rsa.GenerateKey(rand.Reader, 512)
		c.Assert(err, IsNil)

		buf := new(bytes.Buffer)
		err = packet.NewRSAPublicKey(time.Now(), &pk1.PublicKey).Serialize(buf)
		c.Assert(err, IsNil)
		err = packet.NewRSAPublicKey(time.Now(), &pk2.PublicKey).Serialize(buf)
		c.Assert(err, IsNil)

		return buf.Bytes(), nil
	}
	restore := asserts.MockRunGPG(mockGPG)
	defer restore()

	_, err := gkms.keypairMgr.Get(assertstest.DevKeyID)
	c.Check(err, ErrorMatches, `cannot load GPG public key with fingerprint "[A-F0-9]+": cannot select exported public key, found many`)
}
Ejemplo n.º 3
0
// Full STS communication example illustrated with two concurrent Go routines agreeing on a master key.
func Example_usage() {
	// STS cyclic group parameters, global for the app (small examples, not secure!)
	group := big.NewInt(3910779947)
	generator := big.NewInt(1213725007)

	// STS encryption parameters
	cipher := aes.NewCipher
	bits := 128
	hash := crypto.SHA1

	// RSA key-pairs for the communicating parties, obtained from somewhere else (no error checks)
	iniKey, _ := rsa.GenerateKey(rand.Reader, 1024)
	accKey, _ := rsa.GenerateKey(rand.Reader, 1024)

	// Start two Go routines: one initiator and one acceptor communicating on a channel
	transport := make(chan []byte)
	iniOut := make(chan []byte)
	accOut := make(chan []byte)

	go initiator(group, generator, cipher, bits, hash, iniKey, &accKey.PublicKey, transport, iniOut)
	go acceptor(group, generator, cipher, bits, hash, accKey, &iniKey.PublicKey, transport, accOut)

	// Check that the parties agreed upon the same master key
	iniMaster, iniOk := <-iniOut
	accMaster, accOk := <-accOut

	fmt.Printf("Initiator key valid: %v\n", iniOk && iniMaster != nil)
	fmt.Printf("Acceptor key valid: %v\n", accOk && accMaster != nil)
	fmt.Printf("Keys match: %v\n", bytes.Equal(iniMaster, accMaster))

	// Output:
	// Initiator key valid: true
	// Acceptor key valid: true
	// Keys match: true
}
Ejemplo n.º 4
0
func main() {
	// Instantiate the PKCS11 key
	var pkcs11 struct {
		Module string
		Token  string
		PIN    string
		Label  string
	}
	pkcs11Bytes, err := ioutil.ReadFile(pkcs11FileName)
	panicOnError(err)
	err = json.Unmarshal(pkcs11Bytes, &pkcs11)
	panicOnError(err)
	p11key, err := pkcs11key.New(pkcs11.Module, pkcs11.Token, pkcs11.PIN, pkcs11.Label)
	panicOnError(err)

	// All of the certificates start and end at the same time
	notBefore := time.Now().Truncate(time.Hour).Add(-1 * time.Hour)
	notAfter := notBefore.AddDate(1, 0, 0)

	// Make some keys for the CA and EE
	caKey, err := rsa.GenerateKey(rand.Reader, 2048)
	panicOnError(err)
	eeKey, err := rsa.GenerateKey(rand.Reader, 2048)
	panicOnError(err)

	// Make CA cert with ephemeral key
	template := &x509.Certificate{
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		Subject:               pkix.Name{CommonName: "Happy Hacker Fake CA"},
		BasicConstraintsValid: true,
		IsCA: true,
	}
	caCert := makeCert(template, template, caKey.Public(), caKey)

	// Make EE cert with ephemeral key and print
	template = &x509.Certificate{
		NotBefore: notBefore,
		NotAfter:  notAfter,
		Subject:   pkix.Name{CommonName: "example.com"},
	}
	eeCert := makeCert(template, caCert, eeKey.Public(), caKey)

	// Make OCSP responder cert with PKCS#11 key
	template = &x509.Certificate{
		NotBefore:   notBefore,
		NotAfter:    notAfter,
		Subject:     pkix.Name{CommonName: "Happy Hacker OCSP Signer"},
		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageOCSPSigning},
	}
	ocspCert := makeCert(template, caCert, p11key.Public(), caKey)

	// Write out all the certs in DER and PEM
	ioutil.WriteFile(caCertFileName, caCert.Raw, 0666)
	ioutil.WriteFile(eeCertFileName, eeCert.Raw, 0666)
	ioutil.WriteFile(ocspCertFileName, ocspCert.Raw, 0666)
	ioutil.WriteFile(caCertFileNamePEM, toPEM(caCert), 0666)
	ioutil.WriteFile(eeCertFileNamePEM, toPEM(eeCert), 0666)
	ioutil.WriteFile(ocspCertFileNamePEM, toPEM(ocspCert), 0666)
}
Ejemplo n.º 5
0
func TestToken(t *testing.T) {
	iniKey, _ := rsa.GenerateKey(rand.Reader, 1024)
	accKey, _ := rsa.GenerateKey(rand.Reader, 1024)

	for i, tt := range stsTests {
		iniSes, _ := New(bytes.NewReader(tt.iniExponent.Bytes()), tt.group, tt.generator, tt.cipher, tt.bits, tt.hash)
		accSes, _ := New(bytes.NewReader(tt.accExponent.Bytes()), tt.group, tt.generator, tt.cipher, tt.bits, tt.hash)
		iniExp, _ := iniSes.Initiate()

		accExp, accToken, err := accSes.Accept(rand.Reader, accKey, iniExp)
		if err != nil {
			t.Errorf("test %d: failed to accept incoming exchange: %v", i, err)
		} else if tt.accExponential.Cmp(accExp) != 0 {
			t.Errorf("test %d: exponential mismatch: have %v, want %v", i, accExp, tt.accExponential)
		} else {
			iniToken, err := iniSes.Verify(rand.Reader, iniKey, &accKey.PublicKey, accExp, accToken)
			if err != nil {
				t.Errorf("test %d: failed to verify auth token: %v", i, err)
			} else {
				err := accSes.Finalize(&iniKey.PublicKey, iniToken)
				if err != nil {
					t.Errorf("test %d: failed to finalize key exchange: %v", i, err)
				}
			}
		}
	}
}
Ejemplo n.º 6
0
func (c *Cert) GenerateCerts(domain string) ([]byte, []byte, []byte, []byte, error) {
	caPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	encodedCAPrivateKey := new(bytes.Buffer)
	if err := pem.Encode(encodedCAPrivateKey, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(caPrivateKey)}); err != nil {
		return nil, nil, nil, nil, err
	}

	caTemplate := c.generateTemplate(domain, true)
	encodedCACertificate, err := c.generateCert(caTemplate, caTemplate, &caPrivateKey.PublicKey, caPrivateKey)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	encodedPrivateKey := new(bytes.Buffer)
	if err := pem.Encode(encodedPrivateKey, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}); err != nil {
		return nil, nil, nil, nil, err
	}

	template := c.generateTemplate(domain, false)
	encodedCertificate, err := c.generateCert(template, caTemplate, &privateKey.PublicKey, caPrivateKey)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	return encodedCertificate, encodedPrivateKey.Bytes(), encodedCACertificate, encodedCAPrivateKey.Bytes(), nil
}
Ejemplo n.º 7
0
// Test GenerateCert from Keys
func TestGenerateCertFromKeys(t *testing.T) {
	var notBefore time.Time
	notBefore = time.Now()
	validFor := 365 * 24 * time.Hour
	notAfter := notBefore.Add(validFor)

	signingKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal("Can't generate signing key\n")
	}
	derSignerCert, err := GenerateSelfSignedCertFromKey(signingKey, "Cloudproxy Authority",
		"Application Policy Key", GetSerialNumber(), notBefore, notAfter)
	if err != nil {
		t.Fatal("Can't generate signer key\n")
	}
	fmt.Printf("SigningKey: %x\n", signingKey)

	signedKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal("Can't generate privatekey\n")
	}
	newPublic := PublicKeyFromPrivate(signedKey)
	if newPublic == nil {
		t.Fatal("Can't generate privatekey\n")
	}
	cert, err := GenerateCertFromKeys(signingKey, derSignerCert, newPublic,
		"TestKey", "CommonTestKey", GetSerialNumber(),
		notBefore, notAfter)
	if err != nil {
		t.Fatal("Can't generate cert\n")
	}
	fmt.Printf("cert: %x\n", cert)
}
Ejemplo n.º 8
0
func TestSignCertificate(t *testing.T) {
	var notBefore time.Time
	notBefore = time.Now()
	validFor := 365 * 24 * time.Hour
	notAfter := notBefore.Add(validFor)

	// Generate Policy Key.
	privatePolicyKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal("Can't generate privatekey\n")
	}

	derPolicyCert, err := GenerateSelfSignedCertFromKey(privatePolicyKey, "PolicyKey",
		"PolicyKey", GetSerialNumber(), notBefore, notAfter)
	if err != nil {
		t.Fatal("Can't parse program certificate ", err, "\n")
	}

	// Generate Program Key.
	privateProgramKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal("Can't generate program privatekey\n")
	}
	derProgramCert, err := GenerateCertFromKeys(privatePolicyKey,
		derPolicyCert, &privateProgramKey.PublicKey,
		"JLM", "Test-program", GetSerialNumber(), notBefore, notAfter)
	if err != nil {
		t.Fatal("Can't generate cert\n")
	}
	ok, err := VerifyDerCert(derProgramCert, derPolicyCert)
	if !ok || err != nil {
		t.Fatal("Can't verify certificate ", err, "\n")
	}
}
Ejemplo n.º 9
0
func main() {
	in, err := discover.Discover(net.FlagMulticast)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Interface:", in)

	MasterKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatal(err)
	}
	SlaveKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatal(err)
	}

	Keys := discover.NewPubKeys()
	Keys.Put("slave", &SlaveKey.PublicKey)

	server := &discover.Server{}
	server.Name = "master"
	server.PrivateKey = MasterKey
	server.PubKeys = Keys
	server.Interface = in
	server.AddrVer = discover.Ipv4
	server.Port = "3333"
	server.Protocol = func(addr *net.UDPAddr, req *discover.Request) (resp *discover.Response, err error) {
		if string(req.Data) != "request" {
			return nil, e.New("protocol error")
		}
		return &discover.Response{
			Data: []byte("msg"),
		}, nil
	}
	err = server.Do()
	if err != nil {
		log.Fatal(err)
	}
	defer server.Close()

	client := &discover.Client{}
	client.ServerName = "master"
	client.ServerKey = &MasterKey.PublicKey
	client.Name = "slave"
	client.PrivateKey = SlaveKey
	client.Interface = in
	client.AddrVer = discover.Ipv4
	client.Port = "3333"
	client.Request = func(dst *net.UDPAddr) (*discover.Request, error) {
		return &discover.Request{
			Data: []byte("request"),
		}, nil
	}
	resp, err := client.Discover()
	if err != nil {
		log.Fatal(err)
	}
	log.Println(resp)
}
Ejemplo n.º 10
0
// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
// single identity composed of the given full name, comment and email, any of
// which may be empty but must not contain any of "()<>\x00".
// If config is nil, sensible defaults will be used.
func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) {
	currentTime := config.Now()

	uid := packet.NewUserId(name, comment, email)
	if uid == nil {
		return nil, errors.InvalidArgumentError("user id field contained invalid characters")
	}
	signingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
	if err != nil {
		return nil, err
	}
	encryptingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
	if err != nil {
		return nil, err
	}

	e := &Entity{
		PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey),
		PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv),
		Identities: make(map[string]*Identity),
	}
	isPrimaryId := true
	e.Identities[uid.Id] = &Identity{
		Name:   uid.Name,
		UserId: uid,
		SelfSignature: &packet.Signature{
			CreationTime: currentTime,
			SigType:      packet.SigTypePositiveCert,
			PubKeyAlgo:   packet.PubKeyAlgoRSA,
			Hash:         config.Hash(),
			IsPrimaryId:  &isPrimaryId,
			FlagsValid:   true,
			FlagSign:     true,
			FlagCertify:  true,
			IssuerKeyId:  &e.PrimaryKey.KeyId,
		},
	}

	e.Subkeys = make([]Subkey, 1)
	e.Subkeys[0] = Subkey{
		PublicKey:  packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey),
		PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv),
		Sig: &packet.Signature{
			CreationTime:              currentTime,
			SigType:                   packet.SigTypeSubkeyBinding,
			PubKeyAlgo:                packet.PubKeyAlgoRSA,
			Hash:                      config.Hash(),
			FlagsValid:                true,
			FlagEncryptStorage:        true,
			FlagEncryptCommunications: true,
			IssuerKeyId:               &e.PrimaryKey.KeyId,
		},
	}
	e.Subkeys[0].PublicKey.IsSubkey = true
	e.Subkeys[0].PrivateKey.IsSubkey = true

	return e, nil
}
Ejemplo n.º 11
0
// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
// single identity composed of the given full name, comment and email, any of
// which may be empty but must not contain any of "()<>\x00".
func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email string) (*Entity, os.Error) {
	uid := packet.NewUserId(name, comment, email)
	if uid == nil {
		return nil, error.InvalidArgumentError("user id field contained invalid characters")
	}
	signingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits)
	if err != nil {
		return nil, err
	}
	encryptingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits)
	if err != nil {
		return nil, err
	}

	t := uint32(currentTimeSecs)

	e := &Entity{
		PrimaryKey: packet.NewRSAPublicKey(t, &signingPriv.PublicKey, false /* not a subkey */),
		PrivateKey: packet.NewRSAPrivateKey(t, signingPriv, false /* not a subkey */),
		Identities: make(map[string]*Identity),
	}
	isPrimaryId := true
	e.Identities[uid.Id] = &Identity{
		Name:   uid.Name,
		UserId: uid,
		SelfSignature: &packet.Signature{
			CreationTime: t,
			SigType:      packet.SigTypePositiveCert,
			PubKeyAlgo:   packet.PubKeyAlgoRSA,
			Hash:         crypto.SHA256,
			IsPrimaryId:  &isPrimaryId,
			FlagsValid:   true,
			FlagSign:     true,
			FlagCertify:  true,
			IssuerKeyId:  &e.PrimaryKey.KeyId,
		},
	}

	e.Subkeys = make([]Subkey, 1)
	e.Subkeys[0] = Subkey{
		PublicKey:  packet.NewRSAPublicKey(t, &encryptingPriv.PublicKey, true /* is a subkey */),
		PrivateKey: packet.NewRSAPrivateKey(t, encryptingPriv, true /* is a subkey */),
		Sig: &packet.Signature{
			CreationTime:              t,
			SigType:                   packet.SigTypeSubkeyBinding,
			PubKeyAlgo:                packet.PubKeyAlgoRSA,
			Hash:                      crypto.SHA256,
			FlagsValid:                true,
			FlagEncryptStorage:        true,
			FlagEncryptCommunications: true,
			IssuerKeyId:               &e.PrimaryKey.KeyId,
		},
	}

	return e, nil
}
Ejemplo n.º 12
0
func TestKeys(t *testing.T) {
	var err error
	MasterKey, err = rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}
	SlaveKey, err = rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}
	Keys = NewPubKeys()
	Keys.Put("master", &MasterKey.PublicKey)
	Keys.Put("slave", &SlaveKey.PublicKey)
}
Ejemplo n.º 13
0
// Example demonstrate discovery in work.
func Example() {
	masterKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println(err)
	}
	slaveKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println(err)
	}
	keys := NewPubKeys()
	keys.Put("slave", &slaveKey.PublicKey)

	server := &Server{}
	server.Name = "master"
	server.PrivateKey = masterKey
	server.PubKeys = keys
	server.Protocol = func(addr *net.UDPAddr, req *Request) (resp *Response, err error) {
		if string(req.Data) != "request" {
			return nil, e.New("protocol error")
		}
		return &Response{
			Data: []byte("msg"),
		}, nil
	}
	err = server.Do()
	if err != nil {
		fmt.Println(err)
	}
	defer server.Close()

	client := &Client{}
	client.ServerName = "master"
	client.ServerKey = &masterKey.PublicKey
	client.Name = "slave"
	client.PrivateKey = slaveKey
	client.Port = server.Port
	client.Request = func(dst *net.UDPAddr) (*Request, error) {
		return &Request{
			Data: []byte("request"),
		}, nil
	}
	resp, err := client.Discover()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(resp.Data))
	//Output:
	//msg
}
Ejemplo n.º 14
0
func NewMockUpaxClient(name, lfs string, members []*xcl.MemberInfo,
	primary uint) (mc *MockUpaxClient, err error) {
	var (
		ckPriv, skPriv *rsa.PrivateKey
		ep             []xt.EndPointI
		node           *xn.Node
		uc             *UpaxClient
	)

	// lfs should be a well-formed POSIX path; if the directory does
	// not exist we should create it.
	err = xf.CheckLFS(lfs, 0750)

	// The ckPriv is an RSA key used to encrypt short messages.
	if err == nil {
		if ckPriv == nil {
			ckPriv, err = rsa.GenerateKey(rand.Reader, 2048)
		}
		if err == nil {
			// The skPriv is an RSA key used to create digital signatures.
			if skPriv == nil {
				skPriv, err = rsa.GenerateKey(rand.Reader, 2048)
			}
		}
	}
	// The mock client uses a system-assigned endpoint
	if err == nil {
		var endPoint *xt.TcpEndPoint
		endPoint, err = xt.NewTcpEndPoint("127.0.0.1:0")
		if err == nil {
			ep = []xt.EndPointI{endPoint}
		}
	}
	// spin up an XLattice node
	if err == nil {
		node, err = xn.New(name, nil, // get a default NodeID
			lfs, ckPriv, skPriv, nil, ep, nil) // nil overlays, peers
	}
	if err == nil {
		uc, err = NewUpaxClient(ckPriv, skPriv, node, members, primary)
		if err == nil {
			mc = &MockUpaxClient{
				UpaxClient: *uc,
			}
		}
	}
	return
}
Ejemplo n.º 15
0
// GenerateKey generates a private/public key pair of the given bits. It panics on error.
func GenerateKey(bits int) (asserts.PrivateKey, *rsa.PrivateKey) {
	priv, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		panic(fmt.Errorf("failed to create private key: %v", err))
	}
	return asserts.RSAPrivateKey(priv), priv
}
Ejemplo n.º 16
0
func BenchmarkCheckCert(b *testing.B) {
	dbMap, err := sa.NewDbMap(dbConnStr)
	if err != nil {
		fmt.Println("Couldn't connect to database")
		return
	}

	checker := newChecker(dbMap)
	testKey, _ := rsa.GenerateKey(rand.Reader, 1024)
	expiry := time.Now().AddDate(0, 0, 1)
	serial := big.NewInt(1337)
	rawCert := x509.Certificate{
		Subject: pkix.Name{
			CommonName: "example.com",
		},
		NotAfter:     expiry,
		DNSNames:     []string{"example-a.com"},
		SerialNumber: serial,
	}
	certDer, _ := x509.CreateCertificate(rand.Reader, &rawCert, &rawCert, &testKey.PublicKey, testKey)
	cert := core.Certificate{
		Status:  core.StatusValid,
		Serial:  core.SerialToString(serial),
		Digest:  core.Fingerprint256(certDer),
		DER:     certDer,
		Issued:  time.Now(),
		Expires: expiry,
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		checker.checkCert(cert)
	}
}
Ejemplo n.º 17
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")
	}
}
Ejemplo n.º 18
0
Archivo: csr.go Proyecto: bbandix/cfssl
// 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")
	}
}
Ejemplo n.º 19
0
func TestSignAndVerify(t *testing.T) {
	header := &Header{
		Algorithm: "RS256",
		Typ:       "JWT",
	}
	payload := &ClaimSet{
		Iss: "http://google.com/",
		Aud: "",
		Exp: 3610,
		Iat: 10,
	}

	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}

	token, err := Encode(header, payload, privateKey)
	if err != nil {
		t.Fatal(err)
	}

	err = Verify(token, &privateKey.PublicKey)
	if err != nil {
		t.Fatal(err)
	}
}
Ejemplo n.º 20
0
func generatePrivateKey() (*packet.PrivateKey, error) {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}
	return packet.NewRSAPrivateKey(time.Now(), priv), nil
}
Ejemplo n.º 21
0
// Creation a new Identity
func NewSecretIdentity(password string) *SecretIdentity {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		panic(err)
	}
	return &SecretIdentity{key: key, password: password}
}
Ejemplo n.º 22
0
func TestRSA(t *testing.T) {
	privkey, err := rsa.GenerateKey(rand.Reader, 2048)
	if !assert.NoError(t, err, "GenerateKey succeeds") {
		return
	}

	key := NewRSA(&privkey.PublicKey)
	xmlstr, err := key.Serialize()
	if !assert.NoError(t, err, "Serialize succeeds") {
		return
	}

	t.Logf("%s", xmlstr)

	key2, err := Parse([]byte(xmlstr))
	if !assert.NoError(t, err, "Parse succeeds") {
		return
	}

	switch key2.(type) {
	case *RSA:
	default:
		if !assert.Fail(t, "expected *RSA type, but got something else") {
			return
		}
	}
}
Ejemplo n.º 23
0
func (ka *rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
	// Only send a server key agreement when the cipher is an RSA export
	// TODO: Make this a configuration parameter
	ka.clientVersion = clientHello.vers
	if !ka.ephemeral {
		return nil, nil
	}

	// Generate an ephemeral RSA key or use the one in the config
	if config.ExportRSAKey != nil {
		ka.privateKey = config.ExportRSAKey
	} else {
		key, err := rsa.GenerateKey(config.rand(), 512)
		if err != nil {
			return nil, err
		}
		ka.privateKey = key
	}

	// Serialize the key parameters to a nice byte array. The byte array can be
	// positioned later.
	modulus := ka.privateKey.N.Bytes()
	exponent := big.NewInt(int64(ka.privateKey.E)).Bytes()
	serverRSAParams := make([]byte, 0, 2+len(modulus)+2+len(exponent))
	serverRSAParams = append(serverRSAParams, byte(len(modulus)>>8), byte(len(modulus)))
	serverRSAParams = append(serverRSAParams, modulus...)
	serverRSAParams = append(serverRSAParams, byte(len(exponent)>>8), byte(len(exponent)))
	serverRSAParams = append(serverRSAParams, exponent...)

	return ka.auth.signParameters(config, cert, clientHello, hello, serverRSAParams)
}
Ejemplo n.º 24
0
func newSigner(privKeyFile string) (*signer, error) {
	signer := new(signer)

	if len(privKeyFile) > 0 {
		privateBytes, err := ioutil.ReadFile(privKeyFile)
		if err != nil {
			return nil, errors.New("Failed to load private host key")
		}

		signer.Signer, err = ssh.ParsePrivateKey(privateBytes)
		if err != nil {
			return nil, errors.New("Failed to parse private host key")
		}

		return signer, nil
	}

	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, errors.New("Failed to generate server key pair")
	}

	signer.Signer, err = ssh.NewSignerFromKey(key)
	if err != nil {
		return nil, errors.New("Failed to extract private key from generated key pair")
	}
	signer.generated = true

	return signer, nil
}
Ejemplo n.º 25
0
func GenerateRSAKeyPair() *RSAKeyPair {
	priv, _ := rsa.GenerateKey(rand.Reader, 1024)
	return &RSAKeyPair{
		priv: priv,
		pub:  &priv.PublicKey,
	}
}
Ejemplo n.º 26
0
func TestRsaSign_SignVerify(t *testing.T) {
	rsakey, err := rsa.GenerateKey(rand.Reader, 2048)
	if !assert.NoError(t, err, "RSA key generated") {
		return
	}

	s, err := NewRsaSign(jwa.RS256, rsakey)
	if !assert.NoError(t, err, "RsaSign created") {
		return
	}

	payload := []byte("Hello, world")
	signed, err := s.PayloadSign(payload)
	if !assert.NoError(t, err, "Payload signed") {
		return
	}

	v, err := NewRsaVerify(jwa.RS256, &rsakey.PublicKey)
	if !assert.NoError(t, err, "RsaVerify created") {
		return
	}

	if !assert.NoError(t, v.payloadVerify(payload, signed), "Payload verified") {
		return
	}
}
Ejemplo n.º 27
0
/*
Generates an RSA key pair of the specified key length in bits.
Uses Go's crypto/rand rand.Reader as the source of entropy.

If password is a non-empty string, encrypts the private key so that password is required
to decrypt and use it. If password == "", the private key returned is unencrypted.
*/
func GenerateKeyPair(keyLenBits int, password string) (privateKeyPEM string, publicKeyPEM string, err error) {

	priv, err := rsa.GenerateKey(rand.Reader, keyLenBits)
	if err != nil {
		return
	}
	err = priv.Validate()
	if err != nil {
		return
	}

	privateKeyBytes := x509.MarshalPKCS1PrivateKey(priv)

	privateKeyPEM, err = EncodePrivateKeyPEM(privateKeyBytes, password)
	if err != nil {
		return
	}

	pub := &(priv.PublicKey)
	publicKeyBytes, err := x509.MarshalPKIXPublicKey(pub)
	if err != nil {
		return
	}

	publicKeyPEM, err = EncodePublicKeyPEM(publicKeyBytes)
	if err != nil {
		return
	}

	return
}
Ejemplo n.º 28
0
func TestRSASignerPrivateKey(t *testing.T) {
	rsaPriv, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		t.Fatal(err)
	}

	priv := NewSignerPrivateKey(time.Now(), &rsaSigner{rsaPriv})

	if priv.PubKeyAlgo != PubKeyAlgoRSASignOnly {
		t.Fatal("NewSignerPrivateKey should have made a sign-only RSA private key")
	}

	sig := &Signature{
		PubKeyAlgo: PubKeyAlgoRSASignOnly,
		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)
	}
}
Ejemplo n.º 29
0
func NewKeyPair() (crypto.PublicKey, crypto.PrivateKey, error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, keyBits)
	if err != nil {
		return nil, nil, err
	}
	return &privateKey.PublicKey, privateKey, nil
}
Ejemplo n.º 30
0
Archivo: rsa.go Proyecto: 41px/dmz
func GenerateKey() (pkPem []byte, pubkPem []byte, pubSSHAK []byte, err error) {
	pk, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return
	}
	pkDer := x509.MarshalPKCS1PrivateKey(pk)
	pkBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   pkDer,
	}
	pkPem = pem.EncodeToMemory(&pkBlock)

	pubk := pk.PublicKey
	pubkDer, err := x509.MarshalPKIXPublicKey(&pubk)
	if err != nil {
		return
	}

	pubkBlock := pem.Block{
		Type:    "PUBLIC KEY",
		Headers: nil,
		Bytes:   pubkDer,
	}
	pubkPem = pem.EncodeToMemory(&pubkBlock)

	pubSSH, err := ssh.NewPublicKey(&pubk)
	if err != nil {
		return
	}
	pubSSHAK = ssh.MarshalAuthorizedKey(pubSSH)

	return
}