2 Copyright 2014 The Kubernetes Authors.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
31 // CanReadCertAndKey returns true if the certificate and key files already exists,
32 // otherwise returns false. If lost one of cert and key, returns error.
33 func CanReadCertAndKey(certPath, keyPath string) (bool, error) {
34 certReadable := canReadFile(certPath)
35 keyReadable := canReadFile(keyPath)
37 if certReadable == false && keyReadable == false {
41 if certReadable == false {
42 return false, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", certPath)
45 if keyReadable == false {
46 return false, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", keyPath)
52 // If the file represented by path exists and
53 // readable, returns true otherwise returns false.
54 func canReadFile(path string) bool {
55 f, err := os.Open(path)
65 // WriteCert writes the pem-encoded certificate data to certPath.
66 // The certificate file will be created with file mode 0644.
67 // If the certificate file already exists, it will be overwritten.
68 // The parent directory of the certPath will be created as needed with file mode 0755.
69 func WriteCert(certPath string, data []byte) error {
70 if err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil {
73 return ioutil.WriteFile(certPath, data, os.FileMode(0644))
76 // WriteKey writes the pem-encoded key data to keyPath.
77 // The key file will be created with file mode 0600.
78 // If the key file already exists, it will be overwritten.
79 // The parent directory of the keyPath will be created as needed with file mode 0755.
80 func WriteKey(keyPath string, data []byte) error {
81 if err := os.MkdirAll(filepath.Dir(keyPath), os.FileMode(0755)); err != nil {
84 return ioutil.WriteFile(keyPath, data, os.FileMode(0600))
87 // LoadOrGenerateKeyFile looks for a key in the file at the given path. If it
88 // can't find one, it will generate a new key and store it there.
89 func LoadOrGenerateKeyFile(keyPath string) (data []byte, wasGenerated bool, err error) {
90 loadedData, err := ioutil.ReadFile(keyPath)
91 // Call verifyKeyData to ensure the file wasn't empty/corrupt.
92 if err == nil && verifyKeyData(loadedData) {
93 return loadedData, false, err
95 if !os.IsNotExist(err) {
96 return nil, false, fmt.Errorf("error loading key from %s: %v", keyPath, err)
99 generatedData, err := MakeEllipticPrivateKeyPEM()
101 return nil, false, fmt.Errorf("error generating key: %v", err)
103 if err := WriteKey(keyPath, generatedData); err != nil {
104 return nil, false, fmt.Errorf("error writing key to %s: %v", keyPath, err)
106 return generatedData, true, nil
109 // MarshalPrivateKeyToPEM converts a known private key type of RSA or ECDSA to
110 // a PEM encoded block or returns an error.
111 func MarshalPrivateKeyToPEM(privateKey crypto.PrivateKey) ([]byte, error) {
112 switch t := privateKey.(type) {
113 case *ecdsa.PrivateKey:
114 derBytes, err := x509.MarshalECPrivateKey(t)
118 privateKeyPemBlock := &pem.Block{
119 Type: ECPrivateKeyBlockType,
122 return pem.EncodeToMemory(privateKeyPemBlock), nil
123 case *rsa.PrivateKey:
124 return EncodePrivateKeyPEM(t), nil
126 return nil, fmt.Errorf("private key is not a recognized type: %T", privateKey)
130 // NewPool returns an x509.CertPool containing the certificates in the given PEM-encoded file.
131 // Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates
132 func NewPool(filename string) (*x509.CertPool, error) {
133 certs, err := CertsFromFile(filename)
137 pool := x509.NewCertPool()
138 for _, cert := range certs {
144 // CertsFromFile returns the x509.Certificates contained in the given PEM-encoded file.
145 // Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates
146 func CertsFromFile(file string) ([]*x509.Certificate, error) {
147 pemBlock, err := ioutil.ReadFile(file)
151 certs, err := ParseCertsPEM(pemBlock)
153 return nil, fmt.Errorf("error reading %s: %s", file, err)
158 // PrivateKeyFromFile returns the private key in rsa.PrivateKey or ecdsa.PrivateKey format from a given PEM-encoded file.
159 // Returns an error if the file could not be read or if the private key could not be parsed.
160 func PrivateKeyFromFile(file string) (interface{}, error) {
161 data, err := ioutil.ReadFile(file)
165 key, err := ParsePrivateKeyPEM(data)
167 return nil, fmt.Errorf("error reading private key file %s: %v", file, err)
172 // PublicKeysFromFile returns the public keys in rsa.PublicKey or ecdsa.PublicKey format from a given PEM-encoded file.
173 // Reads public keys from both public and private key files.
174 func PublicKeysFromFile(file string) ([]interface{}, error) {
175 data, err := ioutil.ReadFile(file)
179 keys, err := ParsePublicKeysPEM(data)
181 return nil, fmt.Errorf("error reading public key file %s: %v", file, err)
186 // verifyKeyData returns true if the provided data appears to be a valid private key.
187 func verifyKeyData(data []byte) bool {
191 _, err := ParsePrivateKeyPEM(data)