2017-04-17 18:08:24 -04:00
|
|
|
package cryptoservice
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/x509"
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
2017-10-30 12:21:41 -04:00
|
|
|
"github.com/theupdateframework/notary/tuf/data"
|
|
|
|
"github.com/theupdateframework/notary/tuf/utils"
|
2017-04-17 18:08:24 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// GenerateCertificate generates an X509 Certificate from a template, given a GUN and validity interval
|
2017-08-24 18:40:24 -04:00
|
|
|
func GenerateCertificate(rootKey data.PrivateKey, gun data.GUN, startTime, endTime time.Time) (*x509.Certificate, error) {
|
2017-04-17 18:08:24 -04:00
|
|
|
signer := rootKey.CryptoSigner()
|
|
|
|
if signer == nil {
|
2017-08-24 18:40:24 -04:00
|
|
|
return nil, fmt.Errorf("key type not supported for Certificate generation: %s", rootKey.Algorithm())
|
2017-04-17 18:08:24 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return generateCertificate(signer, gun, startTime, endTime)
|
|
|
|
}
|
|
|
|
|
2017-08-24 18:40:24 -04:00
|
|
|
func generateCertificate(signer crypto.Signer, gun data.GUN, startTime, endTime time.Time) (*x509.Certificate, error) {
|
|
|
|
template, err := utils.NewCertificate(gun.String(), startTime, endTime)
|
2017-04-17 18:08:24 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to create the certificate template for: %s (%v)", gun, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
derBytes, err := x509.CreateCertificate(rand.Reader, template, template, signer.Public(), signer)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to create the certificate for: %s (%v)", gun, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
cert, err := x509.ParseCertificate(derBytes)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse the certificate for key: %s (%v)", gun, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return cert, nil
|
|
|
|
}
|