pkcs7 implements parsing and creating signed and enveloped messages.
package main
import (
"bytes""crypto/rsa""crypto/x509""encoding/pem""fmt""os""go.mozilla.org/pkcs7"
)
funcSignAndDetach(content []byte, cert*x509.Certificate, privkey*rsa.PrivateKey) (signed []byte, errerror) {
toBeSigned, err:=NewSignedData(content)
iferr!=nil {
err=fmt.Errorf("Cannot initialize signed data: %s", err)
return
}
iferr=toBeSigned.AddSigner(cert, privkey, SignerInfoConfig{}); err!=nil {
err=fmt.Errorf("Cannot add signer: %s", err)
return
}
// Detach signature, omit if you want an embedded signaturetoBeSigned.Detach()
signed, err=toBeSigned.Finish()
iferr!=nil {
err=fmt.Errorf("Cannot finish signing data: %s", err)
return
}
// Verify the signaturepem.Encode(os.Stdout, &pem.Block{Type: "PKCS7", Bytes: signed})
p7, err:=pkcs7.Parse(signed)
iferr!=nil {
err=fmt.Errorf("Cannot parse our signed data: %s", err)
return
}
// since the signature was detached, reattach the content herep7.Content=contentifbytes.Compare(content, p7.Content) !=0 {
err=fmt.Errorf("Our content was not in the parsed data:\n\tExpected: %s\n\tActual: %s", content, p7.Content)
return
}
iferr=p7.Verify(); err!=nil {
err=fmt.Errorf("Cannot verify our signed data: %s", err)
return
}
returnsigned, nil
}This is a fork of fullsailor/pkcs7