Files
kubesphere/pkg/models/kubeconfig/internal/pki_helpers.go
2020-01-15 15:58:35 +08:00

65 lines
1.8 KiB
Go

/*
*
* Copyright 2020 The KubeSphere Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* /
*/
package pkiutil
import (
"crypto"
cryptorand "crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"github.com/pkg/errors"
certutil "k8s.io/client-go/util/cert"
)
// NewCSRAndKey generates a new key and CSR and that could be signed to create the given certificate
func NewCSRAndKey(config *certutil.Config) (*x509.CertificateRequest, *rsa.PrivateKey, error) {
key, err := certutil.NewPrivateKey()
if err != nil {
return nil, nil, errors.Wrap(err, "unable to create private key")
}
csr, err := NewCSR(*config, key)
if err != nil {
return nil, nil, errors.Wrap(err, "unable to generate CSR")
}
return csr, key, nil
}
// NewCSR creates a new CSR
func NewCSR(cfg certutil.Config, key crypto.Signer) (*x509.CertificateRequest, error) {
template := &x509.CertificateRequest{
Subject: pkix.Name{
CommonName: cfg.CommonName,
Organization: cfg.Organization,
},
DNSNames: cfg.AltNames.DNSNames,
IPAddresses: cfg.AltNames.IPs,
}
csrBytes, err := x509.CreateCertificateRequest(cryptorand.Reader, template, key)
if err != nil {
return nil, errors.Wrap(err, "failed to create a CSR")
}
return x509.ParseCertificateRequest(csrBytes)
}