2 Copyright 2016 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.
20 cryptorand "crypto/rand"
28 // MakeCSR generates a PEM-encoded CSR using the supplied private key, subject, and SANs.
29 // All key types that are implemented via crypto.Signer are supported (This includes *rsa.PrivateKey and *ecdsa.PrivateKey.)
30 func MakeCSR(privateKey interface{}, subject *pkix.Name, dnsSANs []string, ipSANs []net.IP) (csr []byte, err error) {
31 template := &x509.CertificateRequest{
37 return MakeCSRFromTemplate(privateKey, template)
40 // MakeCSRFromTemplate generates a PEM-encoded CSR using the supplied private
41 // key and certificate request as a template. All key types that are
42 // implemented via crypto.Signer are supported (This includes *rsa.PrivateKey
43 // and *ecdsa.PrivateKey.)
44 func MakeCSRFromTemplate(privateKey interface{}, template *x509.CertificateRequest) ([]byte, error) {
46 t.SignatureAlgorithm = sigType(privateKey)
48 csrDER, err := x509.CreateCertificateRequest(cryptorand.Reader, &t, privateKey)
53 csrPemBlock := &pem.Block{
54 Type: CertificateRequestBlockType,
58 return pem.EncodeToMemory(csrPemBlock), nil
61 func sigType(privateKey interface{}) x509.SignatureAlgorithm {
62 // Customize the signature for RSA keys, depending on the key size
63 if privateKey, ok := privateKey.(*rsa.PrivateKey); ok {
64 keySize := privateKey.N.BitLen()
67 return x509.SHA512WithRSA
69 return x509.SHA384WithRSA
71 return x509.SHA256WithRSA
74 return x509.UnknownSignatureAlgorithm