示例#1
1
func init() {
	var err error
	var pemBytes []byte
	var pub crypto.PublicKey
	var p *pem.Block

	if client, err = NewClient(certFile, keyFile, caFile, ioutil.Discard); err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(rsaPubKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if pub, err = x509.ParsePKIXPublicKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	if rsaKey, err = client.RegisterPublicKey(server, pub); err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(ecdsaPubKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if pub, err = x509.ParsePKIXPublicKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	if ecdsaKey, err = client.RegisterPublicKey(server, pub); err != nil {
		log.Fatal(err)
	}
}
示例#2
0
文件: pki.go 项目: hujun-open/manpass
func LoadCertKeyFromEncPkg(encpkg []byte, passwd string) (*CertKey, error) {
	blk, _ := pem.Decode(encpkg)
	if blk == nil {
		return nil, errors.New("Invalid PEM data")
	}
	if blk.Type != pkgTypeStr {
		return nil, errors.New("PEM type is not " + pkgTypeStr)
	}
	decrypted_pem, err := x509.DecryptPEMBlock(blk, []byte(passwd))
	if err != nil {
		return nil, err
	}
	key_pem, rest := pem.Decode(decrypted_pem)
	if blk == nil {
		return nil, errors.New("decrypted content is not PEM")
	}
	cert_pem, _ := pem.Decode(rest)
	if blk == nil {
		return nil, errors.New("Can't find the cert PEM")
	}
	if _, ok := supportedKeyTypes[key_pem.Type]; !ok {
		return nil, errors.New("Unsupported Key types")
	}
	if cert_pem.Type != "CERTIFICATE" {
		return nil, errors.New("Can't find certificate in decrypted PEM data")
	}
	var ck CertKey
	switch key_pem.Type {
	case "RSA PRIVATE KEY":
		rsack := new(RSACertKey)
		priv_key, err := x509.ParsePKCS1PrivateKey(key_pem.Bytes)
		if err != nil {
			return nil, err
		}
		rsack.key = priv_key
		cert, err := x509.ParseCertificates(cert_pem.Bytes)
		if err != nil {
			return nil, err
		}
		rsack.cert = *cert[0]
		ck = rsack
		return &ck, nil
	case "EC PRIVATE KEY":
		ecck := new(ECCertKey)
		priv_key, err := x509.ParseECPrivateKey(key_pem.Bytes)
		if err != nil {
			return nil, err
		}
		ecck.key = priv_key
		cert, err := x509.ParseCertificates(cert_pem.Bytes)
		if err != nil {
			return nil, err
		}
		ecck.cert = *cert[0]
		ck = ecck
		return &ck, nil
	}
	return nil, errors.New("Unussal error, you shouldn't see this")

}
示例#3
0
func LoadCertsKeys(uname string, upass []byte) (ca []byte, ee []byte, pkey []byte, err error) {
	user_dir := common.GetConfDir(uname)
	cafs, err := ioutil.ReadFile(filepath.Join(user_dir, "ca.cert"))
	if err != nil {
		return nil, nil, nil, err
	}
	ca, err = passcrypto.DecryptMeBase32(string(cafs), upass)
	if err != nil {
		return nil, nil, nil, err
	}
	ee_pem, err := ioutil.ReadFile(filepath.Join(user_dir, "ee.cert"))
	if err != nil {
		return nil, nil, nil, err
	}
	ee_blk, _ := pem.Decode(ee_pem)
	ee = ee_blk.Bytes
	pkeyfs, err := ioutil.ReadFile(filepath.Join(user_dir, "ee.key"))
	if err != nil {
		return nil, nil, nil, err
	}
	pkey_pem, _ := pem.Decode(pkeyfs)
	pkey, err = x509.DecryptPEMBlock(pkey_pem, upass)
	if err != nil {
		return nil, nil, nil, err
	}
	return
}
示例#4
0
func init() {
	var err error
	var pemBytes []byte
	var key crypto.Signer
	var p *pem.Block

	s, err = NewServerFromFile(certFile, keyFile, caFile, addr, os.Stdout)
	if err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(rsaPrivKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if key, err = x509.ParsePKCS1PrivateKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	s.RegisterKey(key)

	if pemBytes, err = ioutil.ReadFile(ecdsaPrivKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if key, err = x509.ParseECPrivateKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	s.RegisterKey(key)
}
示例#5
0
func TestBlockHeaderPrecedenceGunFromPath(t *testing.T) {
	// this is a proof of concept that if we have legacy fixtures with nested paths, we infer the gun from them correctly
	s := NewTestImportStore()

	from, _ := os.OpenFile("../fixtures/secure.example.com.key", os.O_RDONLY, notary.PrivExecPerms)
	defer from.Close()
	fromBytes, _ := ioutil.ReadAll(from)
	b, _ := pem.Decode(fromBytes)
	b.Headers["role"] = data.CanonicalSnapshotRole
	b.Headers["path"] = filepath.Join(notary.NonRootKeysSubdir, "anothergun", "12ba0e0a8e05e177bc2c3489bdb6d28836879469f078e68a4812fc8a2d521497")
	bBytes := pem.EncodeToMemory(b)

	in := bytes.NewBuffer(bBytes)

	err := ImportKeys(in, []Importer{s}, "somerole", "somegun", passphraseRetriever)
	require.NoError(t, err)

	require.Len(t, s.data, 1)
	for key := range s.data {
		// block header role= root should take precedence over command line flag
		require.Equal(t, "12ba0e0a8e05e177bc2c3489bdb6d28836879469f078e68a4812fc8a2d521497", key)
		final, rest := pem.Decode(s.data[key])
		require.Len(t, rest, 0)
		require.Equal(t, final.Headers["role"], "snapshot")
		require.Equal(t, final.Headers["gun"], "anothergun")
	}
}
示例#6
0
func TestBlockHeaderPrecedenceRoleAndGun(t *testing.T) {
	s := NewTestImportStore()

	from, _ := os.OpenFile("../fixtures/secure.example.com.key", os.O_RDONLY, notary.PrivExecPerms)
	defer from.Close()
	fromBytes, _ := ioutil.ReadAll(from)
	b, _ := pem.Decode(fromBytes)
	b.Headers["role"] = data.CanonicalSnapshotRole
	b.Headers["gun"] = "anothergun"
	bBytes := pem.EncodeToMemory(b)

	in := bytes.NewBuffer(bBytes)

	err := ImportKeys(in, []Importer{s}, "somerole", "somegun", passphraseRetriever)
	require.NoError(t, err)

	require.Len(t, s.data, 1)
	for key := range s.data {
		// block header role= root should take precedence over command line flag
		require.Equal(t, "12ba0e0a8e05e177bc2c3489bdb6d28836879469f078e68a4812fc8a2d521497", key)
		final, rest := pem.Decode(s.data[key])
		require.Len(t, rest, 0)
		require.Equal(t, final.Headers["role"], "snapshot")
		require.Equal(t, final.Headers["gun"], "anothergun")
	}
}
示例#7
0
func TestSign(t *testing.T) {
	Convey("Given an XML, certificate, and RSA key", t, func() {
		pemString, _ := ioutil.ReadFile("./testdata/rsa.crt")
		pemBlock, _ := pem.Decode([]byte(pemString))
		cert, _ := x509.ParseCertificate(pemBlock.Bytes)

		pemString, _ = ioutil.ReadFile("./testdata/rsa.key")
		pemBlock, _ = pem.Decode([]byte(pemString))
		key, _ := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)

		xml, _ := ioutil.ReadFile("./testdata/nosignature.xml")

		Convey("When generating the signature", func() {
			signer, _ := NewSigner(string(xml))
			xmlStr, err := signer.Sign(key)
			Convey("Then no error occurs", func() {
				So(err, ShouldBeNil)
			})
			Convey("And the signature should be valid", func() {
				validator, _ := NewValidator(xmlStr)
				validator.Certificates = append(validator.Certificates, *cert)
				err := validator.Validate()
				So(err, ShouldBeNil)
			})
		})
	})
}
示例#8
0
// import (decode + decrypt) PEM block which must match one of the given types
func importPem(pemData []byte, prompt PasswordPrompt, types ...string) (*pem.Block, error) {
	block, pemData := pem.Decode(pemData)
	block2, _ := pem.Decode(pemData)
	if nil == block || nil != block2 {
		return nil, NotASinglePemBlock
	}

	{
		// check pem type
		validType := false
		for _, t := range types {
			if t == block.Type {
				validType = true
				break
			}
		}
		if !validType {
			return nil, UnexpectedPemBlock
		}
	}

	if err := utils.DecryptPemBlock(block, prompt); nil != err {
		return nil, err
	}
	return block, nil
}
示例#9
0
func init() {
	// Setup the updateURL if the environment variable is set
	envApi := os.Getenv("CORE_UPDATE_URL")
	if envApi != "" {
		envUrl, err := url.Parse(envApi)
		if err != nil {
			fmt.Printf("Error: couldn't parse CORE_UPDATE_URL: %s", err.Error())
			os.Exit(-1)
		}
		updateURL = *envUrl
	}
	pool := x509.NewCertPool()

	coreosInetPemBlock, _ := pem.Decode([]byte(certs.CoreOS_Internet_Authority_pem))
	if coreosInetPemBlock == nil {
		panic("Error: No PEM data found in CoreOS_Internet_Auth")
	}

	coreosNetPemBlock, _ := pem.Decode([]byte(certs.CoreOS_Internet_Authority_pem))
	if coreosNetPemBlock == nil {
		panic("Error: No PEM data found in CoreOS_Network_Auth")
	}

	coreosInetAuthCert, err := x509.ParseCertificate(coreosInetPemBlock.Bytes)
	if err != nil {
		panic(err.Error())
	}
	coreosNetAuthCert, err := x509.ParseCertificate(coreosNetPemBlock.Bytes)
	if err != nil {
		panic(err.Error())
	}
	pool.AddCert(coreosNetAuthCert)
	pool.AddCert(coreosInetAuthCert)
	tlsTransport.TLSClientConfig = &tls.Config{RootCAs: pool}
}
示例#10
0
func TestWriteCerts(t *testing.T) {
	dir, err := ioutil.TempDir("", "stenocerts")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)
	certFile, keyFile := filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem")
	if err := WriteNewCerts(certFile, keyFile, true); err != nil {
		t.Errorf("unable to generate certs files: %v", err)
	}
	// Test cert file
	if certBytes, err := ioutil.ReadFile(certFile); err != nil {
		t.Errorf("could not read cert file: %v", err)
	} else if block, _ := pem.Decode(certBytes); block == nil {
		t.Errorf("could not get cert pem block: %v", err)
	} else if _, err := x509.ParseCertificate(block.Bytes); err != nil {
		t.Errorf("could not parse cert: %v", err)
	}
	// Test key file
	if keyBytes, err := ioutil.ReadFile(keyFile); err != nil {
		t.Errorf("could not read key file: %v", err)
	} else if block, _ := pem.Decode(keyBytes); block == nil {
		t.Errorf("could not get key pem block: %v", err)
	} else if _, err := x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
		t.Errorf("could not parse key: %v", err)
	}
}
示例#11
0
func main() {
	random, _ := os.Open("/dev/urandom", os.O_RDONLY, 0)
	pembytes := readEntireFile("/home/kris/SSL/gr0g.crt")
	cert, _ := pem.Decode(pembytes)
	keybytes := readEntireFile("/home/kris/SSL/gr0g.key")
	pk, _ := pem.Decode(keybytes)

	privatekey, _ := x509.ParsePKCS1PrivateKey(pk.Bytes)

	config := new(tls.Config)
	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0].Certificate = [][]byte{cert.Bytes}
	config.Certificates[0].PrivateKey = privatekey
	config.Rand = random
	//config.RootCAs = caset
	config.Time = time.Seconds
	listener, err := tls.Listen("tcp", "0.0.0.0:8443", config)

	fmt.Printf("%s\n", err)
	for {
		conn, _ := listener.Accept()
		go func() {
			for {
				buf := make([]byte, 1024)
				_, err := conn.Read(buf)
				if err != nil {
					return
				}
				fmt.Printf("%s", buf)
			}
		}()
	}
}
示例#12
0
func enc(text string) {
	fmt.Println(text)
	data := []byte(text)
	block, _ := pem.Decode([]byte(key["pri"]))
	privkey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
	encData, _ := PrivateEncrypt(privkey, data)
	fmt.Println(encData)

	fmt.Println(base64.StdEncoding.EncodeToString(encData))

	block2, _ := pem.Decode([]byte(key["pub"]))
	pubinterface, rest := x509.ParsePKIXPublicKey(block2.Bytes)
	if rest != nil {
		println("parse public key fail")
		return
	}
	plaindata, err := PublicDecrypt(pubinterface.(*rsa.PublicKey), encData)
	fmt.Println("N:" + base64.StdEncoding.EncodeToString(pubinterface.(*rsa.PublicKey).N.Bytes()))
	if err != nil {
		println(err)
		return
	}
	fmt.Println(string(plaindata))

}
示例#13
0
// path and encrypted key should succeed, tests gun inference from path as well
func TestEncryptedKeyImportSuccess(t *testing.T) {
	s := NewTestImportStore()

	privKey, err := utils.GenerateECDSAKey(rand.Reader)
	originalKey := privKey.Private()
	require.NoError(t, err)

	pemBytes, err := utils.EncryptPrivateKey(privKey, data.CanonicalSnapshotRole, "somegun", cannedPassphrase)
	require.NoError(t, err)

	b, _ := pem.Decode(pemBytes)
	b.Headers["path"] = privKey.ID()
	pemBytes = pem.EncodeToMemory(b)

	in := bytes.NewBuffer(pemBytes)

	_ = ImportKeys(in, []Importer{s}, "", "", passphraseRetriever)
	require.Len(t, s.data, 1)

	keyBytes := s.data[privKey.ID()]

	bFinal, bRest := pem.Decode(keyBytes)
	require.Equal(t, "somegun", bFinal.Headers["gun"])
	require.Len(t, bRest, 0)

	// we should fail to parse it without the passphrase
	privKey, err = utils.ParsePEMPrivateKey(keyBytes, "")
	require.Equal(t, err, errors.New("could not decrypt private key"))
	require.Nil(t, privKey)

	// we should succeed to parse it with the passphrase
	privKey, err = utils.ParsePEMPrivateKey(keyBytes, cannedPassphrase)
	require.NoError(t, err)
	require.Equal(t, originalKey, privKey.Private())
}
示例#14
0
文件: pkcs12.go 项目: haneric21/cfssl
// ParseAndEncode takes key, certificate, and optional password
// as []byte and parses them to get a suitable format to encode them
func ParseAndEncode(key, cert, password []byte) string {
	var file string
	certBlock, _ := pem.Decode(cert)
	certBytes := certBlock.Bytes
	certificate, err := x509.ParseCertificate(certBytes)
	if err != nil {
		return file
	}

	block, _ := pem.Decode(key)
	privKey := block.Bytes
	if block.Type == "RSA PRIVATE KEY" {
		pkcsKey, err := x509.ParsePKCS1PrivateKey(privKey)
		if err != nil {
			return file
		}
		file = Encode(pkcsKey, certificate, password)
	} else if block.Type == "EC PRIVATE KEY" {
		ecKey, err := x509.ParseECPrivateKey(privKey)
		if err != nil {
			return file
		}
		file = Encode(ecKey, certificate, password)
	}

	return file
}
示例#15
0
文件: x509_test.go 项目: Ericean/go
func TestCRLCreation(t *testing.T) {
	block, _ := pem.Decode([]byte(pemPrivateKey))
	priv, _ := ParsePKCS1PrivateKey(block.Bytes)
	block, _ = pem.Decode([]byte(pemCertificate))
	cert, _ := ParseCertificate(block.Bytes)

	now := time.Unix(1000, 0)
	expiry := time.Unix(10000, 0)

	revokedCerts := []pkix.RevokedCertificate{
		{
			SerialNumber:   big.NewInt(1),
			RevocationTime: now,
		},
		{
			SerialNumber:   big.NewInt(42),
			RevocationTime: now,
		},
	}

	crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry)
	if err != nil {
		t.Errorf("error creating CRL: %s", err)
	}

	_, err = ParseDERCRL(crlBytes)
	if err != nil {
		t.Errorf("error reparsing CRL: %s", err)
	}
}
示例#16
0
文件: easyca.go 项目: postfix/easypki
func GetCA(pkiroot string) (*x509.Certificate, *rsa.PrivateKey, error) {
	caKeyBytes, err := ioutil.ReadFile(filepath.Join(pkiroot, "private", "ca.key"))
	if err != nil {
		return nil, nil, fmt.Errorf("read ca private key: %v", err)
	}
	p, _ := pem.Decode(caKeyBytes)
	if p == nil {
		return nil, nil, fmt.Errorf("pem decode did not found pem encoded ca private key")
	}
	caKey, err := x509.ParsePKCS1PrivateKey(p.Bytes)
	if err != nil {
		return nil, nil, fmt.Errorf("parse ca private key: %v", err)
	}

	caCrtBytes, err := ioutil.ReadFile(filepath.Join(pkiroot, "ca.crt"))
	if err != nil {
		return nil, nil, fmt.Errorf("read ca crt: %v", err)
	}
	p, _ = pem.Decode(caCrtBytes)
	if p == nil {
		return nil, nil, fmt.Errorf("pem decode did not found pem encoded ca cert")
	}
	caCrt, err := x509.ParseCertificate(p.Bytes)
	if err != nil {
		return nil, nil, fmt.Errorf("parse ca crt: %v", err)
	}

	return caCrt, caKey, nil
}
示例#17
0
func TestExportKeysByID(t *testing.T) {
	setUp(t)
	tempBaseDir, err := ioutil.TempDir("", "notary-test-")
	require.NoError(t, err)
	defer os.RemoveAll(tempBaseDir)
	output, err := ioutil.TempFile("", "notary-test-import-")
	require.NoError(t, err)
	defer os.RemoveAll(output.Name())
	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			return v, nil
		},
	}
	k.outFile = output.Name()
	err = output.Close() // close so export can open
	require.NoError(t, err)
	k.exportKeyIDs = []string{"one", "three"}

	b := &pem.Block{}
	b.Bytes = make([]byte, 1000)
	rand.Read(b.Bytes)

	b2 := &pem.Block{}
	b2.Bytes = make([]byte, 1000)
	rand.Read(b2.Bytes)

	c := &pem.Block{}
	c.Bytes = make([]byte, 1000)
	rand.Read(c.Bytes)

	bBytes := pem.EncodeToMemory(b)
	b2Bytes := pem.EncodeToMemory(b2)
	cBytes := pem.EncodeToMemory(c)

	fileStore, err := store.NewPrivateKeyFileStorage(tempBaseDir, notary.KeyExtension)
	require.NoError(t, err)
	err = fileStore.Set("one", bBytes)
	require.NoError(t, err)
	err = fileStore.Set("two", b2Bytes)
	require.NoError(t, err)
	err = fileStore.Set("three", cBytes)
	require.NoError(t, err)

	err = k.exportKeys(&cobra.Command{}, nil)
	require.NoError(t, err)

	outRes, err := ioutil.ReadFile(k.outFile)
	require.NoError(t, err)

	block, rest := pem.Decode(outRes)
	require.Equal(t, b.Bytes, block.Bytes)
	require.Equal(t, "one", block.Headers["path"])

	block, rest = pem.Decode(rest)
	require.Equal(t, c.Bytes, block.Bytes)
	require.Equal(t, "three", block.Headers["path"])
	require.Len(t, rest, 0)
}
示例#18
0
文件: cert_test.go 项目: vahe/lxd
func TestGenerateMemCert(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping cert generation in short mode")
	}
	cert, key, err := GenerateMemCert(false)
	if err != nil {
		t.Error(err)
		return
	}
	if cert == nil {
		t.Error("GenerateMemCert returned a nil cert")
		return
	}
	if key == nil {
		t.Error("GenerateMemCert returned a nil key")
		return
	}
	block, rest := pem.Decode(cert)
	if len(rest) != 0 {
		t.Errorf("GenerateMemCert returned a cert with trailing content: %q", string(rest))
	}
	if block.Type != "CERTIFICATE" {
		t.Errorf("GenerateMemCert returned a cert with Type %q not \"CERTIFICATE\"", block.Type)
	}
	block, rest = pem.Decode(key)
	if len(rest) != 0 {
		t.Errorf("GenerateMemCert returned a key with trailing content: %q", string(rest))
	}
	if block.Type != "RSA PRIVATE KEY" {
		t.Errorf("GenerateMemCert returned a cert with Type %q not \"RSA PRIVATE KEY\"", block.Type)
	}
}
示例#19
0
文件: load.go 项目: hilerchyn/fabio
// newCertPool creates a new x509.CertPool by loading the
// PEM blocks from loadFn(path) and adding them to a CertPool.
func newCertPool(path string, caUpgradeCN string, loadFn func(path string) (pemBlocks map[string][]byte, err error)) (*x509.CertPool, error) {
	pemBlocks, err := loadFn(path)
	if err != nil {
		return nil, err
	}

	if len(pemBlocks) == 0 {
		return nil, nil
	}

	pool := x509.NewCertPool()
	for _, pemBlock := range pemBlocks {
		for p, rest := pem.Decode(pemBlock); p != nil; p, rest = pem.Decode(rest) {
			cert, err := x509.ParseCertificate(p.Bytes)
			if err != nil {
				return nil, err
			}
			upgradeCACertificate(cert, caUpgradeCN)
			pool.AddCert(cert)
		}
	}

	log.Printf("[INFO] cert: Load client CA certs from %s", path)
	return pool, nil
}
示例#20
0
文件: key.go 项目: 89hmdys/toast
func LoadKeyFromPEMFile(publicKeyFilePath, privateKeyFilePath string, ParseKey func([]byte, []byte) (Key, error)) (Key, error) {

	//TODO 断言如果入参为"" ,则直接报错

	publicKeyFilePath = strings.TrimSpace(publicKeyFilePath)

	pukBytes, err := ioutil.ReadFile(publicKeyFilePath)
	if err != nil {
		return nil, err
	}

	puk, _ := pem.Decode(pukBytes)
	if puk == nil {
		return nil, errors.New("publicKey is not pem formate")
	}

	privateKeyFilePath = strings.TrimSpace(privateKeyFilePath)

	prkBytes, err := ioutil.ReadFile(privateKeyFilePath)
	if err != nil {
		return nil, err
	}

	prk, _ := pem.Decode(prkBytes)
	if prk == nil {
		return nil, errors.New("privateKey is not pem formate")
	}

	return ParseKey(puk.Bytes, prk.Bytes)
}
示例#21
0
文件: main.go 项目: stonetingxin/apns
// CreateConfig создает описание конфигурации, загружая сертификаты из указанных файлов.
func CreateConfig(bundleId, certFile, keyFile string, sandbox bool) (*apns.ConfigJSON, error) {
	certPEMBlock, err := ioutil.ReadFile(certFile)
	if err != nil {
		return nil, err
	}
	if bundleId == "" {
		bundlerIds := regexp.MustCompile(`subject=\/UID=([\w\.\-]{3,})\/`).
			FindStringSubmatch(string(certPEMBlock))
		if len(bundlerIds) > 1 {
			bundleId = bundlerIds[1]
		}
	}

	keyPEMBlock, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return nil, err
	}
	if _, err = tls.X509KeyPair(certPEMBlock, keyPEMBlock); err != nil {
		return nil, err
	}

	var (
		cert         = make([][]byte, 0, 2)
		certDERBlock *pem.Block
	)
	for {
		certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
		if certDERBlock == nil {
			break
		}
		if certDERBlock.Type == "CERTIFICATE" {
			cert = append(cert, pem.EncodeToMemory(certDERBlock))
		}
	}
	if len(cert) == 0 {
		return nil, errors.New("No certificates find")
	}

	var keyDERBlock *pem.Block
	for {
		keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
		if keyDERBlock == nil {
			return nil, errors.New("failed to parse key PEM data")
		}
		if keyDERBlock.Type == "PRIVATE KEY" ||
			strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
			break
		}
	}

	var config = &apns.ConfigJSON{
		Type:        "apns",
		BundleId:    bundleId,
		Sandbox:     sandbox,
		Certificate: cert,
		PrivateKey:  pem.EncodeToMemory(keyDERBlock),
	}
	return config, nil
}
示例#22
0
文件: tls.go 项目: khia/httpcache
// X509KeyPair parses a public/private key pair from a pair of
// PEM encoded data.
func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err error) {
	var certDERBlock *pem.Block
	for {
		certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
		if certDERBlock == nil {
			break
		}
		if certDERBlock.Type == "CERTIFICATE" {
			cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
		}
	}

	if len(cert.Certificate) == 0 {
		err = errors.New("crypto/tls: failed to parse certificate PEM data")
		return
	}

	keyDERBlock, _ := pem.Decode(keyPEMBlock)
	if keyDERBlock == nil {
		err = errors.New("crypto/tls: failed to parse key PEM data")
		return
	}

	// OpenSSL 0.9.8 generates PKCS#1 private keys by default, while
	// OpenSSL 1.0.0 generates PKCS#8 keys. We try both.
	var key *rsa.PrivateKey
	if key, err = x509.ParsePKCS1PrivateKey(keyDERBlock.Bytes); err != nil {
		var privKey interface{}
		if privKey, err = x509.ParsePKCS8PrivateKey(keyDERBlock.Bytes); err != nil {
			err = errors.New("crypto/tls: failed to parse key: " + err.Error())
			return
		}

		var ok bool
		if key, ok = privKey.(*rsa.PrivateKey); !ok {
			err = errors.New("crypto/tls: found non-RSA private key in PKCS#8 wrapping")
			return
		}
	}

	cert.PrivateKey = key

	// We don't need to parse the public key for TLS, but we so do anyway
	// to check that it looks sane and matches the private key.
	x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
	if err != nil {
		return
	}

	if x509Cert.PublicKeyAlgorithm != x509.RSA || x509Cert.PublicKey.(*rsa.PublicKey).N.Cmp(key.PublicKey.N) != 0 {
		err = errors.New("crypto/tls: private key does not match public key")
		return
	}

	return
}
示例#23
0
文件: pki.go 项目: hujun-open/manpass
func LoadManpassEE(uname string, passwd []byte) (*CertKey, error) {
	//generate a new EE cert/key with specified uname's CA
	//return encrypted CA cert, EE cert and encrypted EE key in a string
	confdir := common.GetConfDir(uname)
	fi, err := os.Stat(confdir)
	if err != nil {
		return nil, err
	}
	if !fi.IsDir() {
		return nil, fmt.Errorf("%s is not a directory", confdir)
	}
	certs, err := ioutil.ReadFile(filepath.Join(confdir, "ee.cert"))
	if err != nil {
		return nil, err
	}

	enks, err := ioutil.ReadFile(filepath.Join(confdir, "ee.key"))
	if err != nil {
		return nil, err
	}
	blk, _ := pem.Decode(enks)
	blk_cert, _ := pem.Decode(certs)
	key_der, err := x509.DecryptPEMBlock(blk, passwd)
	var ck CertKey
	switch blk.Type {
	case "RSA PRIVATE KEY":
		ee := new(RSACertKey)
		eekey, err := x509.ParsePKCS1PrivateKey(key_der)
		if err != nil {
			return nil, err
		}
		ee.key = eekey
		cert, err := x509.ParseCertificates(blk_cert.Bytes)
		if err != nil {
			return nil, err
		}
		ee.cert = *cert[0]
		ck = ee
		return &ck, nil
	case "EC PRIVATE KEY":
		ecck := new(ECCertKey)
		priv_key, err := x509.ParseECPrivateKey(key_der)
		if err != nil {
			return nil, err
		}
		ecck.key = priv_key
		cert, err := x509.ParseCertificates(blk_cert.Bytes)
		if err != nil {
			return nil, err
		}
		ecck.cert = *cert[0]
		ck = ecck
		return &ck, nil
	}
	return nil, errors.New("Unussal error, you shouldn't see this")
}
示例#24
0
// newAccessController creates an accessController using the given options.
func newAccessController(options map[string]interface{}) (auth.AccessController, error) {
	config, err := checkOptions(options)
	if err != nil {
		return nil, err
	}

	fp, err := os.Open(config.rootCertBundle)
	if err != nil {
		return nil, fmt.Errorf("unable to open token auth root certificate bundle file %q: %s", config.rootCertBundle, err)
	}
	defer fp.Close()

	rawCertBundle, err := ioutil.ReadAll(fp)
	if err != nil {
		return nil, fmt.Errorf("unable to read token auth root certificate bundle file %q: %s", config.rootCertBundle, err)
	}

	var rootCerts []*x509.Certificate
	pemBlock, rawCertBundle := pem.Decode(rawCertBundle)
	for pemBlock != nil {
		if pemBlock.Type == "CERTIFICATE" {
			cert, err := x509.ParseCertificate(pemBlock.Bytes)
			if err != nil {
				return nil, fmt.Errorf("unable to parse token auth root certificate: %s", err)
			}

			rootCerts = append(rootCerts, cert)
		}

		pemBlock, rawCertBundle = pem.Decode(rawCertBundle)
	}

	if len(rootCerts) == 0 {
		return nil, errors.New("token auth requires at least one token signing root certificate")
	}

	rootPool := x509.NewCertPool()
	trustedKeys := make(map[string]libtrust.PublicKey, len(rootCerts))
	for _, rootCert := range rootCerts {
		rootPool.AddCert(rootCert)
		pubKey, err := libtrust.FromCryptoPublicKey(crypto.PublicKey(rootCert.PublicKey))
		if err != nil {
			return nil, fmt.Errorf("unable to get public key from token auth root certificate: %s", err)
		}
		trustedKeys[pubKey.KeyID()] = pubKey
	}

	return &accessController{
		realm:       config.realm,
		issuer:      config.issuer,
		service:     config.service,
		rootCerts:   rootPool,
		trustedKeys: trustedKeys,
	}, nil
}
示例#25
0
func TestImportKeys2InOneFile(t *testing.T) {
	s := NewTestImportStore()

	b := &pem.Block{
		Headers: make(map[string]string),
	}
	b.Bytes = make([]byte, 1000)
	rand.Read(b.Bytes)
	b.Headers["path"] = "ankh"

	b2 := &pem.Block{
		Headers: make(map[string]string),
	}
	b2.Bytes = make([]byte, 1000)
	rand.Read(b2.Bytes)
	b2.Headers["path"] = "ankh"

	c := &pem.Block{
		Headers: make(map[string]string),
	}
	c.Bytes = make([]byte, 1000)
	rand.Read(c.Bytes)
	c.Headers["path"] = "morpork"

	bBytes := pem.EncodeToMemory(b)
	b2Bytes := pem.EncodeToMemory(b2)
	bBytes = append(bBytes, b2Bytes...)
	cBytes := pem.EncodeToMemory(c)

	byt := append(bBytes, cBytes...)

	in := bytes.NewBuffer(byt)

	err := ImportKeys(in, []Importer{s}, "", "", passphraseRetriever)
	require.NoError(t, err)

	bFinal, bRest := pem.Decode(s.data["ankh"])
	require.Equal(t, b.Bytes, bFinal.Bytes)
	_, ok := bFinal.Headers["path"]
	require.False(t, ok, "expected no path header, should have been removed at import")
	role, _ := bFinal.Headers["role"]
	require.Equal(t, notary.DefaultImportRole, role)

	b2Final, b2Rest := pem.Decode(bRest)
	require.Equal(t, b2.Bytes, b2Final.Bytes)
	_, ok = b2Final.Headers["path"]
	require.False(t, ok, "expected no path header, should have been removed at import")
	require.Len(t, b2Rest, 0)

	cFinal, cRest := pem.Decode(s.data["morpork"])
	require.Equal(t, c.Bytes, cFinal.Bytes)
	_, ok = cFinal.Headers["path"]
	require.False(t, ok, "expected no path header, should have been removed at import")
	require.Len(t, cRest, 0)
}
示例#26
0
文件: saml_test.go 项目: yahoo/coname
func TestVerifySAMLResponseValid(t *testing.T) {
	issuer := "https://idp.yahoo.com"
	authnResponse := saml.NewSignedResponse()
	authnResponse.Issuer.Url = issuer
	authnResponse.Destination = "https://e2esp.yahoo.com"
	authnResponse.Assertion.Issuer.Url = issuer
	authnResponse.AddAttribute("EmailAddress", "*****@*****.**")
	authnResponse.Assertion.Subject.SubjectConfirmation.SubjectConfirmationData.Recipient = "https://e2esp.yahoo.com"

	k, err := ioutil.ReadFile("test.key")
	if err != nil {
		t.Fatal(err)
	}
	kd, _ := pem.Decode(k)
	privateKey, err := x509.ParsePKCS1PrivateKey(kd.Bytes)
	if err != nil {
		t.Fatal(err)
	}

	certPem, err := ioutil.ReadFile("./test.crt")
	if err != nil {
		t.Fatal(err)
	}

	certBlock, _ := pem.Decode(certPem)
	if certBlock == nil {
		t.Errorf("failed to PEM decode cert")
	}

	authnResponse.Signature.KeyInfo.X509Data.X509Certificate.Cert = base64.StdEncoding.EncodeToString(certBlock.Bytes)

	_, err = exec.LookPath("xmlsec1")
	if err != nil {
		t.Skip("skipping subsequent test since xmlsec1 is missing")
	}

	payload, err := authnResponse.EncodedSignedString(privateKey)
	if err != nil {
		t.Fatal(err)
	}

	cert, err := x509.ParseCertificate(certBlock.Bytes)
	if err != nil {
		t.Fatal(err)
	}
	email, err := VerifySAMLResponse(payload, cert, "https://e2esp.yahoo.com", "EmailAddress", 10*time.Second)
	if err != nil {
		t.Fatal(err)
	}
	if want, got := "*****@*****.**", email; got != want {
		t.Errorf("got %q (wanted %q)", got, want)
	}
}
示例#27
0
文件: main.go 项目: yahoo/coname
func main() {
	// input config file contains initial_keyserver_auth and keyserver_addr
	// this file will be provided by keyserver admin
	if len(os.Args) != 5 {
		fmt.Printf("usage: %s cacert cert id inputcfg\n", os.Args[0])
		return
	}
	caCertFile := os.Args[1]
	certFile := os.Args[2]
	cfgF := os.Args[4]
	id, err := strconv.ParseUint(os.Args[3], 10, 64)
	if err != nil {
		log.Fatalf("Failed to convert %v to uint: %v", os.Args[3], err)
	}
	caCertPem, err := ioutil.ReadFile(caCertFile)
	if err != nil {
		log.Fatalf("Failed to read from %v: %v", caCertFile, err)
	}
	caCertBlock, _ := pem.Decode(caCertPem)
	if caCertBlock == nil {
		log.Fatalf("Failed to parse PEM: %v", string(caCertPem))
	}
	caCert, err := x509.ParseCertificate(caCertBlock.Bytes)
	if err != nil {
		log.Fatalf("Failed to parse X.509 cert: %v", err)
	}

	certPEM, err := ioutil.ReadFile(certFile)
	if err != nil {
		log.Fatalf("Failed to read from %v: %v", certFile, err)
	}

	certBlock, _ := pem.Decode(certPEM)
	if certBlock == nil {
		log.Fatalf("Failed to parse PEM: %v", string(certPEM))
	}
	cert, err := x509.ParseCertificate(certBlock.Bytes)
	if err != nil {
		log.Fatalf("Failed to parse X.509 cert: %v", err)
	}

	configReader, err := os.Open(cfgF)
	if err != nil {
		log.Fatalf("Failed to open input configuration file %v: %v", cfgF, err)
	}
	cfg := &proto.VerifierConfig{}
	err = jsonpb.Unmarshal(configReader, cfg)
	if err != nil {
		log.Fatalf("Failed to parse input configuration file %v: %v", cfgF, err)
	}

	make_config(caCert, cert, uint64(id), cfg)
}
示例#28
0
func TestExportKeysByGUN(t *testing.T) {
	s := NewTestExportStore()

	keyHeaders := make(map[string]string)
	keyHeaders["gun"] = "ankh"
	keyHeaders["role"] = "snapshot"
	b := &pem.Block{
		Headers: keyHeaders,
	}
	b.Bytes = make([]byte, 1000)
	rand.Read(b.Bytes)

	b2 := &pem.Block{
		Headers: keyHeaders,
	}
	b2.Bytes = make([]byte, 1000)
	rand.Read(b2.Bytes)

	otherHeaders := make(map[string]string)
	otherHeaders["gun"] = "morpork"
	otherHeaders["role"] = "snapshot"
	c := &pem.Block{
		Headers: otherHeaders,
	}
	c.Bytes = make([]byte, 1000)
	rand.Read(c.Bytes)

	bBytes := pem.EncodeToMemory(b)
	b2Bytes := pem.EncodeToMemory(b2)
	cBytes := pem.EncodeToMemory(c)

	s.data["one"] = bBytes
	s.data["two"] = b2Bytes
	s.data["three"] = cBytes

	buf := bytes.NewBuffer(nil)

	err := ExportKeysByGUN(buf, s, "ankh")
	require.NoError(t, err)

	out, err := ioutil.ReadAll(buf)
	require.NoError(t, err)

	bFinal, rest := pem.Decode(out)
	require.Equal(t, b.Bytes, bFinal.Bytes)
	require.Equal(t, "one", bFinal.Headers["path"])

	b2Final, rest := pem.Decode(rest)
	require.Equal(t, b2.Bytes, b2Final.Bytes)
	require.Equal(t, "two", b2Final.Headers["path"])
	require.Len(t, rest, 0)
}
示例#29
0
文件: https2.go 项目: RunCross/gobook
func YourLoadX509KeyPair(certFile string, keyFile string) (cert tls.Certificate, err error) {
	certPEMBlock, err := ioutil.ReadFile(certFile)
	if err != nil {
		return
	}

	certDERBlock, restPEMBlock := pem.Decode(certPEMBlock)
	if certDERBlock == nil {
		err = errors.New("crypto/tls: failed to parse certificate PEM data")
		return
	}

	certDERBlockChain, _ := pem.Decode(restPEMBlock)
	if certDERBlockChain == nil {
		cert.Certificate = [][]byte{certDERBlock.Bytes}
	} else {
		cert.Certificate = [][]byte{certDERBlock.Bytes, certDERBlockChain.Bytes}
	}

	keyPEMBlock, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return
	}

	keyDERBlock, _ := pem.Decode(keyPEMBlock)
	if keyDERBlock == nil {
		err = errors.New("crypto/tls: failed to parse key PEM data")
		return
	}

	key, err := x509.ParsePKCS1PrivateKey(keyDERBlock.Bytes)
	if err != nil {
		err = errors.New("crypto/tls: failed to parse key")
		return
	}

	cert.PrivateKey = key

	x509Cert, err := x509.ParseCertificate(certDERBlock.Bytes)
	if err != nil {
		return
	}

	if x509Cert.PublicKeyAlgorithm != x509.RSA ||
		x509Cert.PublicKey.(*rsa.PublicKey).N.Cmp(key.PublicKey.N) != 0 {
		err = errors.New("crypto/tls: private key does not match public key")
		return
	}

	return
}
示例#30
0
func checkValidCert(c *gc.C, cert *lxdclient.Cert) {
	c.Assert(cert, gc.NotNil)

	_, err := tls.X509KeyPair(cert.CertPEM, cert.KeyPEM)
	c.Check(err, jc.ErrorIsNil)

	block, remainder := pem.Decode(cert.CertPEM)
	c.Check(block.Type, gc.Equals, "CERTIFICATE")
	c.Check(remainder, gc.HasLen, 0)

	block, remainder = pem.Decode(cert.KeyPEM)
	c.Check(block.Type, gc.Equals, "RSA PRIVATE KEY")
	c.Check(remainder, gc.HasLen, 0)
}