blob: 3a5aef089a78436030b8068b4e1d4ec377f898eb [file] [log] [blame]
khenaidooab1f7bd2019-11-14 14:00:27 -05001// 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
15package tlsutil
16
17import (
18 "crypto/tls"
19 "crypto/x509"
20 "encoding/pem"
21 "io/ioutil"
22)
23
24// NewCertPool creates x509 certPool with provided CA files.
25func 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
45 certPool.AddCert(cert)
46 }
47 }
48
49 return certPool, nil
50}
51
52// NewCert generates TLS cert by using the given cert,key and parse function.
53func NewCert(certfile, keyfile string, parseFunc func([]byte, []byte) (tls.Certificate, error)) (*tls.Certificate, error) {
54 cert, err := ioutil.ReadFile(certfile)
55 if err != nil {
56 return nil, err
57 }
58
59 key, err := ioutil.ReadFile(keyfile)
60 if err != nil {
61 return nil, err
62 }
63
64 if parseFunc == nil {
65 parseFunc = tls.X509KeyPair
66 }
67
68 tlsCert, err := parseFunc(cert, key)
69 if err != nil {
70 return nil, err
71 }
72 return &tlsCert, nil
73}