本文整理匯總了Golang中crypto/x509.CertPool類的典型用法代碼示例。如果您正苦於以下問題:Golang CertPool類的具體用法?Golang CertPool怎麽用?Golang CertPool使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了CertPool類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: loadCertFile
func loadCertFile(roots *x509.CertPool, fname string) error {
data, err := ioutil.ReadFile(fname)
if err == nil {
roots.AppendCertsFromPEM(data)
}
return err
}
示例2: newHTTPSTransport
func newHTTPSTransport(tlsCertFile, tlsKeyFile, tlsCACertFile string) etcd.CancelableTransport {
var cc *tls.Config = nil
if tlsCertFile != "" && tlsKeyFile != "" {
var rpool *x509.CertPool
if tlsCACertFile != "" {
if pemBytes, err := ioutil.ReadFile(tlsCACertFile); err == nil {
rpool = x509.NewCertPool()
rpool.AppendCertsFromPEM(pemBytes)
}
}
if tlsCert, err := tls.LoadX509KeyPair(tlsCertFile, tlsKeyFile); err == nil {
cc = &tls.Config{
RootCAs: rpool,
Certificates: []tls.Certificate{tlsCert},
InsecureSkipVerify: true,
}
}
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
TLSClientConfig: cc,
}
return tr
}
示例3: Dial
func (a *ldapAuther) Dial() error {
var err error
var certPool *x509.CertPool
if a.server.RootCACert != "" {
certPool := x509.NewCertPool()
for _, caCertFile := range strings.Split(a.server.RootCACert, " ") {
if pem, err := ioutil.ReadFile(caCertFile); err != nil {
return err
} else {
if !certPool.AppendCertsFromPEM(pem) {
return errors.New("Failed to append CA certificate " + caCertFile)
}
}
}
}
for _, host := range strings.Split(a.server.Host, " ") {
address := fmt.Sprintf("%s:%d", host, a.server.Port)
if a.server.UseSSL {
tlsCfg := &tls.Config{
InsecureSkipVerify: a.server.SkipVerifySSL,
ServerName: host,
RootCAs: certPool,
}
a.conn, err = ldap.DialTLS("tcp", address, tlsCfg)
} else {
a.conn, err = ldap.Dial("tcp", address)
}
if err == nil {
return nil
}
}
return err
}
示例4: downloadBuildpack
func (repo CloudControllerBuildpackBitsRepository) downloadBuildpack(url string, cb func(*os.File, error)) {
fileutils.TempFile("buildpack-download", func(tempfile *os.File, err error) {
if err != nil {
cb(nil, err)
return
}
var certPool *x509.CertPool
if len(repo.TrustedCerts) > 0 {
certPool = x509.NewCertPool()
for _, tlsCert := range repo.TrustedCerts {
cert, _ := x509.ParseCertificate(tlsCert.Certificate[0])
certPool.AddCert(cert)
}
}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: certPool},
Proxy: http.ProxyFromEnvironment,
},
}
response, err := client.Get(url)
if err != nil {
cb(nil, err)
return
}
io.Copy(tempfile, response.Body)
tempfile.Seek(0, 0)
cb(tempfile, nil)
})
}
示例5: getTLSConfig
// getTLSConfig constructs a tls.Config that uses keys/certificates in the given files.
func getTLSConfig(certFile, keyFile, caFile string) (*tls.Config, error) {
var certs []tls.Certificate
if certFile != "" || keyFile != "" {
if certFile == "" || keyFile == "" {
return nil, util.Errorf("TLS client requires both cert file and key file")
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, util.Errorf("Could not load keypair: %s", err)
}
certs = append(certs, cert)
}
var cas *x509.CertPool
if caFile != "" {
cas = x509.NewCertPool()
caBytes, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, err
}
ok := cas.AppendCertsFromPEM(caBytes)
if !ok {
return nil, util.Errorf("Could not parse certificate file: %s", caFile)
}
}
tlsConfig := &tls.Config{
Certificates: certs,
ClientCAs: cas,
RootCAs: cas,
}
return tlsConfig, nil
}
示例6: loadTLSClientConfig
// loadTLSClientConfig initializes a *tls.Config using the given WebhookNotifierConfiguration.
//
// If no certificates are given, (nil, nil) is returned.
// The CA certificate is optional and falls back to the system default.
func loadTLSClientConfig(cfg *WebhookNotifierConfiguration) (*tls.Config, error) {
if cfg.CertFile == "" || cfg.KeyFile == "" {
return nil, nil
}
cert, err := tls.LoadX509KeyPair(cfg.CertFile, cfg.KeyFile)
if err != nil {
return nil, err
}
var caCertPool *x509.CertPool
if cfg.CAFile != "" {
caCert, err := ioutil.ReadFile(cfg.CAFile)
if err != nil {
return nil, err
}
caCertPool = x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
}
tlsConfig := &tls.Config{
ServerName: cfg.ServerName,
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
return tlsConfig, nil
}
示例7: loadPEMCertificate
func loadPEMCertificate(certPool *x509.CertPool, pemCerts []byte) (ok bool) {
for len(pemCerts) > 0 {
var block *pem.Block
block, pemCerts = pem.Decode(pemCerts)
if block == nil {
break
}
if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
continue
}
// Assumption: CA is self-signed. Not recommended
// for production environments.
cert.IsCA = true
certPool.AddCert(cert)
ok = true
}
return
}
示例8: NewRemoteServer
// NewRemoteServer generates a RemoteServer with the server address and
// the root CA the server uses to authenticate itself.
func NewRemoteServer(serverAddress, CAFile string) (*RemoteServer, error) {
var rootCAs *x509.CertPool
// populate a root CA pool from input CAfile
// otherwise, use the system's default root CA set
if CAFile != "" {
rootCAs = x509.NewCertPool()
pemBytes, err := ioutil.ReadFile(CAFile)
if err != nil {
return nil, errors.New("fail to read CA file: " + err.Error())
}
ok := rootCAs.AppendCertsFromPEM(pemBytes)
if !ok {
return nil, errors.New("fail to populate CA root pool.")
}
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: rootCAs},
DisableCompression: true,
}
server := &RemoteServer{
client: &http.Client{Transport: tr},
serverAddress: serverAddress,
}
return server, nil
}
示例9: main
/*
main registers this RP's HTTP request handlers; creates the HTTPS client for issuing OP ID Token requests and starts its HTTP server.
*/
func main() {
var (
certPool *x509.CertPool
server http.Server
err error
)
//This aeadCipher is used to encrypt/decrypt the Authn Request Cookie that is used to pass the Authn Request State value
//from the Authn Request to the Authn Response.
aeadCipher, err = aead.NewAEADCipher()
if err != nil {
return
}
//Initialize an HTTPS capable client and replace the default aws HTTP client that doesn't support HTTPS
certPool = x509.NewCertPool()
certPool.AppendCertsFromPEM([]byte(certbndl.PemCerts))
opClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: certPool},
},
}
//Start the service
server = http.Server{Addr: ":443", ReadTimeout: 10 * time.Minute, WriteTimeout: 10 * time.Minute, ErrorLog: logger.Logger()}
http.HandleFunc("/login", handleLogin)
http.HandleFunc("/authn-token", handleAuthnToken)
logger.Println("Starting oidc on " + exthost + ":443")
err = server.ListenAndServeTLS("resilient-networks.crt", "resilient-networks.key")
if err != nil {
logger.Fatal(err)
}
}
示例10: loadStore
func loadStore(roots *x509.CertPool, name string) {
store, errno := syscall.CertOpenSystemStore(syscall.InvalidHandle, syscall.StringToUTF16Ptr(name))
if errno != 0 {
return
}
var cert *syscall.CertContext
for {
cert = syscall.CertEnumCertificatesInStore(store, cert)
if cert == nil {
break
}
var asn1Slice []byte
hdrp := (*reflect.SliceHeader)(unsafe.Pointer(&asn1Slice))
hdrp.Data = cert.EncodedCert
hdrp.Len = int(cert.Length)
hdrp.Cap = int(cert.Length)
buf := make([]byte, len(asn1Slice))
copy(buf, asn1Slice)
if cert, err := x509.ParseCertificate(buf); err == nil {
roots.AddCert(cert)
}
}
syscall.CertCloseStore(store, 0)
}
示例11: GetHttpClient
func GetHttpClient() *http.Client {
if client != nil {
return client
} else {
var certPool *x509.CertPool
if pemfile := setting.KeystoneRootCAPEMFile; pemfile != "" {
certPool = x509.NewCertPool()
pemFileContent, err := ioutil.ReadFile(pemfile)
if err != nil {
panic(err)
}
if !certPool.AppendCertsFromPEM(pemFileContent) {
log.Error(3, "Failed to load any certificates from Root CA PEM file %s", pemfile)
} else {
log.Info("Successfully loaded certificate(s) from %s", pemfile)
}
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: certPool,
InsecureSkipVerify: !setting.KeystoneVerifySSLCert},
}
tr.Proxy = http.ProxyFromEnvironment
client = &http.Client{Transport: tr}
return client
}
}
示例12: GetTLSConfig
//func (ck *CertKit) GetTLSConfig(AuthRequired bool) (*tls.Config, error) {
func (ck *CertKit) GetTLSConfig(Access uint8) (*tls.Config, error) {
var atype tls.ClientAuthType
var tlsConfig *tls.Config
var roots *x509.CertPool
switch Access {
case stonelizard.AccessNone:
atype = tls.NoClientCert
case stonelizard.AccessAuth, stonelizard.AccessAuthInfo:
atype = tls.RequestClientCert
case stonelizard.AccessVerifyAuth, stonelizard.AccessVerifyAuthInfo:
atype = tls.RequireAndVerifyClientCert
// Code adapted from crypto/x509/root_unix.go
roots = x509.NewCertPool()
for _, directory := range CertDirectories {
fis, err := ioutil.ReadDir(directory)
if err != nil {
Goose.Auth.Logf(5, "Error scanning certificate directory %s: %s", directory, err)
continue
}
for _, fi := range fis {
data, err := ioutil.ReadFile(fmt.Sprintf("%s%c%s", directory, os.PathSeparator, fi.Name()))
if err != nil {
Goose.Auth.Logf(5, "Error load CA certificate from %s%c%s: %s", directory, os.PathSeparator, fi.Name(), err)
continue
}
Goose.Auth.Logf(5, "Loaded CA certificate from %s%c%s: %s", directory, os.PathSeparator, fi.Name(), err)
roots.AppendCertsFromPEM(data)
}
}
}
Goose.Auth.Logf(6, "authtype: %#v", atype)
Goose.Auth.Logf(6, "CAs: %#v", roots)
tlsConfig = &tls.Config{
ClientAuth: atype,
ClientCAs: roots,
// InsecureSkipVerify: true,
Certificates: make([]tls.Certificate, 1),
}
/*
srv.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(svc.PemPath + "/server.crt", svc.PemPath + "/server.key")
if err != nil {
Goose.InitServe.Logf(1,"Failed reading server certificates: %s",err)
return err
}
*/
tlsConfig.Certificates[0] = ck.ServerX509KeyPair
Goose.Auth.Logf(5, "X509KeyPair used: %#v", tlsConfig.Certificates[0])
tlsConfig.BuildNameToCertificate()
return tlsConfig, nil
}
示例13: ExtendedValidateRoute
// ExtendedValidateRoute performs an extended validation on the route
// including checking that the TLS config is valid.
func ExtendedValidateRoute(route *routeapi.Route) field.ErrorList {
tlsConfig := route.Spec.TLS
result := field.ErrorList{}
if tlsConfig == nil {
return result
}
tlsFieldPath := field.NewPath("spec").Child("tls")
if errs := validateTLS(route, tlsFieldPath); len(errs) != 0 {
result = append(result, errs...)
}
// TODO: Check if we can be stricter with validating the certificate
// is for the route hostname. Don't want existing routes to
// break, so disable the hostname validation for now.
// hostname := route.Spec.Host
hostname := ""
var certPool *x509.CertPool
if len(tlsConfig.CACertificate) > 0 {
certPool = x509.NewCertPool()
if ok := certPool.AppendCertsFromPEM([]byte(tlsConfig.CACertificate)); !ok {
result = append(result, field.Invalid(tlsFieldPath.Child("caCertificate"), tlsConfig.CACertificate, "failed to parse CA certificate"))
}
}
verifyOptions := &x509.VerifyOptions{
DNSName: hostname,
Roots: certPool,
}
if len(tlsConfig.Certificate) > 0 {
if _, err := validateCertificatePEM(tlsConfig.Certificate, verifyOptions); err != nil {
result = append(result, field.Invalid(tlsFieldPath.Child("certificate"), tlsConfig.Certificate, err.Error()))
}
certKeyBytes := []byte{}
certKeyBytes = append(certKeyBytes, []byte(tlsConfig.Certificate)...)
if len(tlsConfig.Key) > 0 {
certKeyBytes = append(certKeyBytes, byte('\n'))
certKeyBytes = append(certKeyBytes, []byte(tlsConfig.Key)...)
}
if _, err := tls.X509KeyPair(certKeyBytes, certKeyBytes); err != nil {
result = append(result, field.Invalid(tlsFieldPath.Child("key"), tlsConfig.Key, err.Error()))
}
}
if len(tlsConfig.DestinationCACertificate) > 0 {
roots := x509.NewCertPool()
if ok := roots.AppendCertsFromPEM([]byte(tlsConfig.DestinationCACertificate)); !ok {
result = append(result, field.Invalid(tlsFieldPath.Child("destinationCACertificate"), tlsConfig.DestinationCACertificate, "failed to parse destination CA certificate"))
}
}
return result
}
示例14: LoadTLSConfig
// LoadTLSConfig will load a certificate from config with all TLS based keys
// defined. If Certificate and CertificateKey are configured, client authentication
// will be configured. If no CAs are configured, the host CA will be used by go
// built-in TLS support.
func LoadTLSConfig(config MothershipConfig) (*tls.Config, error) {
certificate := config.Certificate
key := config.CertificateKey
rootCAs := config.CAs
hasCertificate := certificate != ""
hasKey := key != ""
var certs []tls.Certificate
switch {
case hasCertificate && !hasKey:
return nil, ErrCertificateNoKey
case !hasCertificate && hasKey:
return nil, ErrKeyNoCertificate
case hasCertificate && hasKey:
cert, err := tls.LoadX509KeyPair(certificate, key)
if err != nil {
logp.Critical("Failed loading client certificate", err)
return nil, err
}
certs = []tls.Certificate{cert}
}
var roots *x509.CertPool
if len(rootCAs) > 0 {
roots = x509.NewCertPool()
for _, caFile := range rootCAs {
pemData, err := ioutil.ReadFile(caFile)
if err != nil {
logp.Critical("Failed reading CA certificate: %s", err)
return nil, err
}
if ok := roots.AppendCertsFromPEM(pemData); !ok {
return nil, ErrNotACertificate
}
}
}
insecureSkipVerify := false
if config.TLSInsecure != nil {
insecureSkipVerify = *config.TLSInsecure
}
// Support minimal TLS 1.0.
// TODO: check supported JRuby versions for logstash supported
// TLS 1.1 and switch
tlsConfig := tls.Config{
MinVersion: tls.VersionTLS10,
Certificates: certs,
RootCAs: roots,
InsecureSkipVerify: insecureSkipVerify,
}
return &tlsConfig, nil
}
示例15: addCertsFromKeychain
func addCertsFromKeychain(pool *x509.CertPool, keychain string) error {
cmd := exec.Command("/usr/bin/security", "find-certificate", "-a", "-p", keychain)
data, err := cmd.Output()
if err != nil {
return err
}
pool.AppendCertsFromPEM(data)
return nil
}