| 1 |
package x509util |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto" |
| 5 |
"crypto/x509" |
| 6 |
"crypto/x509/pkix" |
| 7 |
"time" |
| 8 |
|
| 9 |
"github.com/pkg/errors" |
| 10 |
) |
| 11 |
|
| 12 |
|
| 13 |
type Leaf struct { |
| 14 |
base |
| 15 |
} |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
func NewLeafProfileWithTemplate(sub *x509.Certificate, iss *x509.Certificate, issPriv crypto.PrivateKey, withOps ...WithOption) (Profile, error) { |
| 22 |
withOps = append(withOps, WithPublicKey(sub.PublicKey)) |
| 23 |
return newProfile(&Leaf{}, sub, iss, issPriv, withOps...) |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
func NewLeafProfile(cn string, iss *x509.Certificate, issPriv crypto.PrivateKey, withOps ...WithOption) (Profile, error) { |
| 30 |
sub := defaultLeafTemplate(pkix.Name{CommonName: cn}, iss.Subject) |
| 31 |
return newProfile(&Leaf{}, sub, iss, issPriv, withOps...) |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
func NewSelfSignedLeafProfile(cn string, withOps ...WithOption) (Profile, error) { |
| 38 |
sub := defaultLeafTemplate(pkix.Name{CommonName: cn}, pkix.Name{CommonName: cn}) |
| 39 |
p, err := newProfile(&Leaf{}, sub, sub, nil, withOps...) |
| 40 |
if err != nil { |
| 41 |
return nil, err |
| 42 |
} |
| 43 |
|
| 44 |
p.SetIssuerPrivateKey(p.SubjectPrivateKey()) |
| 45 |
return p, nil |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
func NewLeafProfileWithCSR(csr *x509.CertificateRequest, iss *x509.Certificate, issPriv crypto.PrivateKey, withOps ...WithOption) (Profile, error) { |
| 53 |
if csr.PublicKey == nil { |
| 54 |
return nil, errors.Errorf("CSR must have PublicKey") |
| 55 |
} |
| 56 |
|
| 57 |
sub := defaultLeafTemplate(csr.Subject, iss.Subject) |
| 58 |
sub.ExtraExtensions = csr.Extensions |
| 59 |
sub.DNSNames = csr.DNSNames |
| 60 |
sub.EmailAddresses = csr.EmailAddresses |
| 61 |
sub.IPAddresses = csr.IPAddresses |
| 62 |
sub.URIs = csr.URIs |
| 63 |
|
| 64 |
withOps = append(withOps, WithPublicKey(csr.PublicKey)) |
| 65 |
return newProfile(&Leaf{}, sub, iss, issPriv, withOps...) |
| 66 |
} |
| 67 |
|
| 68 |
func defaultLeafTemplate(sub pkix.Name, iss pkix.Name) *x509.Certificate { |
| 69 |
notBefore := time.Now() |
| 70 |
return &x509.Certificate{ |
| 71 |
IsCA: false, |
| 72 |
NotBefore: notBefore, |
| 73 |
NotAfter: notBefore.Add(DefaultCertValidity), |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, |
| 78 |
ExtKeyUsage: []x509.ExtKeyUsage{ |
| 79 |
x509.ExtKeyUsageServerAuth, |
| 80 |
x509.ExtKeyUsageClientAuth, |
| 81 |
}, |
| 82 |
BasicConstraintsValid: false, |
| 83 |
MaxPathLen: 0, |
| 84 |
MaxPathLenZero: false, |
| 85 |
Issuer: iss, |
| 86 |
Subject: sub, |
| 87 |
} |
| 88 |
} |