pki_helpers.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package utils
  14. import (
  15. "crypto"
  16. cryptorand "crypto/rand"
  17. "crypto/rsa"
  18. "crypto/x509"
  19. "crypto/x509/pkix"
  20. "encoding/pem"
  21. "math"
  22. "math/big"
  23. "time"
  24. "github.com/pkg/errors"
  25. certutil "k8s.io/client-go/util/cert"
  26. )
  27. const (
  28. certificateBlockType = "CERTIFICATE"
  29. rsaKeySize = 2048
  30. duration365d = time.Hour * 24 * 365
  31. )
  32. // NewPrivateKey creates an RSA private key
  33. func NewPrivateKey() (*rsa.PrivateKey, error) {
  34. return rsa.GenerateKey(cryptorand.Reader, rsaKeySize)
  35. }
  36. // EncodeCertPEM returns PEM-endcoded certificate data
  37. func EncodeCertPEM(cert *x509.Certificate) []byte {
  38. block := pem.Block{
  39. Type: certificateBlockType,
  40. Bytes: cert.Raw,
  41. }
  42. return pem.EncodeToMemory(&block)
  43. }
  44. // NewSignedCert creates a signed certificate using the given CA certificate and key
  45. func NewSignedCert(cfg *certutil.Config, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer) (*x509.Certificate, error) {
  46. serial, err := cryptorand.Int(cryptorand.Reader, new(big.Int).SetInt64(math.MaxInt64))
  47. if err != nil {
  48. return nil, err
  49. }
  50. if len(cfg.CommonName) == 0 {
  51. return nil, errors.New("must specify a CommonName")
  52. }
  53. if len(cfg.Usages) == 0 {
  54. return nil, errors.New("must specify at least one ExtKeyUsage")
  55. }
  56. certTmpl := x509.Certificate{
  57. Subject: pkix.Name{
  58. CommonName: cfg.CommonName,
  59. Organization: cfg.Organization,
  60. },
  61. DNSNames: cfg.AltNames.DNSNames,
  62. IPAddresses: cfg.AltNames.IPs,
  63. SerialNumber: serial,
  64. NotBefore: caCert.NotBefore,
  65. NotAfter: time.Now().Add(duration365d).UTC(),
  66. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  67. ExtKeyUsage: cfg.Usages,
  68. }
  69. certDERBytes, err := x509.CreateCertificate(cryptorand.Reader, &certTmpl, caCert, key.Public(), caKey)
  70. if err != nil {
  71. return nil, err
  72. }
  73. return x509.ParseCertificate(certDERBytes)
  74. }