feat: add parent certificates

This commit is contained in:
theexiile1305 2024-10-11 17:26:22 +02:00
parent 7f7bf80e39
commit c45aec89e9
No known key found for this signature in database
GPG key ID: A1BDDE98F2BF6E40

View file

@ -16,6 +16,9 @@ var (
// ErrInvalidKeyPair should be used if key pair is invalid // ErrInvalidKeyPair should be used if key pair is invalid
ErrInvalidKeyPair = errors.New("invalid key pair") 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 should be used if the signed data could not initialize
ErrCouldNotInitialize = errors.New("could not initialize signed data") ErrCouldNotInitialize = errors.New("could not initialize signed data")
@ -31,8 +34,9 @@ var (
// SMime is used to sign messages with S/MIME // SMime is used to sign messages with S/MIME
type SMime struct { type SMime struct {
privateKey *rsa.PrivateKey privateKey *rsa.PrivateKey
certificate *x509.Certificate parentCertificates []*x509.Certificate
certificate *x509.Certificate
} }
// NewSMime construct a new instance of SMime with a provided *tls.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 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{ return &SMime{
privateKey: keyPair.PrivateKey.(*rsa.PrivateKey), privateKey: keyPair.PrivateKey.(*rsa.PrivateKey),
certificate: keyPair.Leaf, certificate: keyPair.Leaf,
parentCertificates: parentCertificates,
}, nil }, nil
} }
@ -58,7 +72,7 @@ func (sm *SMime) signMessage(message string) (*string, error) {
return nil, ErrCouldNotInitialize 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 return nil, ErrCouldNotAddSigner
} }