forked from hyperledger/fabric-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
comm.go
60 lines (46 loc) · 1.61 KB
/
comm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package comm
import (
"crypto/tls"
"crypto/x509"
cutil "github.com/hyperledger/fabric-sdk-go/internal/github.com/hyperledger/fabric/common/util"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core"
"github.com/pkg/errors"
)
// TLSConfig returns the appropriate config for TLS including the root CAs,
// certs for mutual TLS, and server host override. Works with certs loaded either from a path or embedded pem.
func TLSConfig(cert *x509.Certificate, serverName string, config core.Config) (*tls.Config, error) {
certPool, err := config.TLSCACertPool()
if err != nil {
return nil, err
}
if cert == nil && (certPool == nil || len(certPool.Subjects()) == 0) {
//Return empty tls config if there is no cert provided or if certpool unavailable
return &tls.Config{}, nil
}
tlsCaCertPool, err := config.TLSCACertPool(cert)
if err != nil {
return nil, err
}
clientCerts, err := config.TLSClientCerts()
if err != nil {
return nil, errors.Errorf("Error loading cert/key pair for TLS client credentials: %v", err)
}
return &tls.Config{RootCAs: tlsCaCertPool, Certificates: clientCerts, ServerName: serverName}, nil
}
// TLSCertHash is a utility method to calculate the SHA256 hash of the configured certificate (for usage in channel headers)
func TLSCertHash(config core.Config) []byte {
certs, err := config.TLSClientCerts()
if err != nil || len(certs) == 0 {
return nil
}
cert := certs[0]
if len(cert.Certificate) == 0 {
return nil
}
h := cutil.ComputeSHA256(cert.Certificate[0])
return h
}