| 1 |
// Copyright 2016 The etcd Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package tlsutil |
| 16 |
|
| 17 |
import ( |
| 18 |
"crypto/tls" |
| 19 |
"crypto/x509" |
| 20 |
"encoding/pem" |
| 21 |
"io/ioutil" |
| 22 |
) |
| 23 |
|
| 24 |
// NewCertPool creates x509 certPool with provided CA files. |
| 25 |
func NewCertPool(CAFiles []string) (*x509.CertPool, error) { |
| 26 |
certPool := x509.NewCertPool() |
| 27 |
|
| 28 |
for _, CAFile := range CAFiles { |
| 29 |
pemByte, err := ioutil.ReadFile(CAFile) |
| 30 |
if err != nil { |
| 31 |
return nil, err |
| 32 |
} |
| 33 |
|
| 34 |
for { |
| 35 |
var block *pem.Block |
| 36 |
block, pemByte = pem.Decode(pemByte) |
| 37 |
if block == nil { |
| 38 |
break |
| 39 |
} |
| 40 |
cert, err := x509.ParseCertificate(block.Bytes) |
| 41 |
if err != nil { |
| 42 |
return nil, err |
| 43 |
} |
| 44 |
certPool.AddCert(cert) |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
return certPool, nil |
| 49 |
} |
| 50 |
|
| 51 |
// NewCert generates TLS cert by using the given cert,key and parse function. |
| 52 |
func NewCert(certfile, keyfile string, parseFunc func([]byte, []byte) (tls.Certificate, error)) (*tls.Certificate, error) { |
| 53 |
cert, err := ioutil.ReadFile(certfile) |
| 54 |
if err != nil { |
| 55 |
return nil, err |
| 56 |
} |
| 57 |
|
| 58 |
key, err := ioutil.ReadFile(keyfile) |
| 59 |
if err != nil { |
| 60 |
return nil, err |
| 61 |
} |
| 62 |
|
| 63 |
if parseFunc == nil { |
| 64 |
parseFunc = tls.X509KeyPair |
| 65 |
} |
| 66 |
|
| 67 |
tlsCert, err := parseFunc(cert, key) |
| 68 |
if err != nil { |
| 69 |
return nil, err |
| 70 |
} |
| 71 |
return &tlsCert, nil |
| 72 |
} |