Zack Williams | e940c7a | 2019-08-21 14:25:39 -0700 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2016 The Kubernetes Authors. |
| 3 | |
| 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 |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 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. |
| 15 | */ |
| 16 | |
| 17 | package cert |
| 18 | |
| 19 | import ( |
| 20 | cryptorand "crypto/rand" |
| 21 | "crypto/rsa" |
| 22 | "crypto/x509" |
| 23 | "crypto/x509/pkix" |
| 24 | "encoding/pem" |
| 25 | "net" |
| 26 | ) |
| 27 | |
| 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{ |
| 32 | Subject: *subject, |
| 33 | DNSNames: dnsSANs, |
| 34 | IPAddresses: ipSANs, |
| 35 | } |
| 36 | |
| 37 | return MakeCSRFromTemplate(privateKey, template) |
| 38 | } |
| 39 | |
| 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) { |
| 45 | t := *template |
| 46 | t.SignatureAlgorithm = sigType(privateKey) |
| 47 | |
| 48 | csrDER, err := x509.CreateCertificateRequest(cryptorand.Reader, &t, privateKey) |
| 49 | if err != nil { |
| 50 | return nil, err |
| 51 | } |
| 52 | |
| 53 | csrPemBlock := &pem.Block{ |
| 54 | Type: CertificateRequestBlockType, |
| 55 | Bytes: csrDER, |
| 56 | } |
| 57 | |
| 58 | return pem.EncodeToMemory(csrPemBlock), nil |
| 59 | } |
| 60 | |
| 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() |
| 65 | switch { |
| 66 | case keySize >= 4096: |
| 67 | return x509.SHA512WithRSA |
| 68 | case keySize >= 3072: |
| 69 | return x509.SHA384WithRSA |
| 70 | default: |
| 71 | return x509.SHA256WithRSA |
| 72 | } |
| 73 | } |
| 74 | return x509.UnknownSignatureAlgorithm |
| 75 | } |