From c45aec89e935bae6ec9526f957b5e5c02ed788f7 Mon Sep 17 00:00:00 2001 From: theexiile1305 Date: Fri, 11 Oct 2024 17:26:22 +0200 Subject: [PATCH] feat: add parent certificates --- smime.go | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/smime.go b/smime.go index e92d283..ae6e4f2 100644 --- a/smime.go +++ b/smime.go @@ -16,6 +16,9 @@ var ( // ErrInvalidKeyPair should be used if key pair is invalid ErrInvalidKeyPair = errors.New("invalid key pair") + // ErrInvalidParentCertificates should be used if one of the parent certificates is invalid + ErrInvalidParentCertificates = errors.New("invalid parent certificates") + // ErrCouldNotInitialize should be used if the signed data could not initialize ErrCouldNotInitialize = errors.New("could not initialize signed data") @@ -31,8 +34,9 @@ var ( // SMime is used to sign messages with S/MIME type SMime struct { - privateKey *rsa.PrivateKey - certificate *x509.Certificate + privateKey *rsa.PrivateKey + parentCertificates []*x509.Certificate + certificate *x509.Certificate } // NewSMime construct a new instance of SMime with a provided *tls.Certificate @@ -41,9 +45,19 @@ func newSMime(keyPair *tls.Certificate) (*SMime, error) { return nil, ErrInvalidKeyPair } + parentCertificates := make([]*x509.Certificate, 0) + for _, cert := range keyPair.Certificate[1:] { + c, err := x509.ParseCertificate(cert) + if err != nil { + return nil, ErrInvalidParentCertificates + } + parentCertificates = append(parentCertificates, c) + } + return &SMime{ - privateKey: keyPair.PrivateKey.(*rsa.PrivateKey), - certificate: keyPair.Leaf, + privateKey: keyPair.PrivateKey.(*rsa.PrivateKey), + certificate: keyPair.Leaf, + parentCertificates: parentCertificates, }, nil } @@ -58,7 +72,7 @@ func (sm *SMime) signMessage(message string) (*string, error) { return nil, ErrCouldNotInitialize } - if err = signedData.AddSigner(sm.certificate, sm.privateKey, pkcs7.SignerInfoConfig{}); err != nil { + if err = signedData.AddSignerChain(sm.certificate, sm.privateKey, sm.parentCertificates, pkcs7.SignerInfoConfig{}); err != nil { return nil, ErrCouldNotAddSigner }