...
1# pkcs7
2
3[](https://godoc.org/go.mozilla.org/pkcs7)
4[](https://github.com/mozilla-services/pkcs7/actions/workflows/ci.yml?query=branch%3Amaster+event%3Apush)
5
6pkcs7 implements parsing and creating signed and enveloped messages.
7
8```go
9package main
10
11import (
12 "bytes"
13 "crypto/rsa"
14 "crypto/x509"
15 "encoding/pem"
16 "fmt"
17 "os"
18
19 "go.mozilla.org/pkcs7"
20)
21
22func SignAndDetach(content []byte, cert *x509.Certificate, privkey *rsa.PrivateKey) (signed []byte, err error) {
23 toBeSigned, err := NewSignedData(content)
24 if err != nil {
25 err = fmt.Errorf("Cannot initialize signed data: %s", err)
26 return
27 }
28 if err = toBeSigned.AddSigner(cert, privkey, SignerInfoConfig{}); err != nil {
29 err = fmt.Errorf("Cannot add signer: %s", err)
30 return
31 }
32
33 // Detach signature, omit if you want an embedded signature
34 toBeSigned.Detach()
35
36 signed, err = toBeSigned.Finish()
37 if err != nil {
38 err = fmt.Errorf("Cannot finish signing data: %s", err)
39 return
40 }
41
42 // Verify the signature
43 pem.Encode(os.Stdout, &pem.Block{Type: "PKCS7", Bytes: signed})
44 p7, err := pkcs7.Parse(signed)
45 if err != nil {
46 err = fmt.Errorf("Cannot parse our signed data: %s", err)
47 return
48 }
49
50 // since the signature was detached, reattach the content here
51 p7.Content = content
52
53 if bytes.Compare(content, p7.Content) != 0 {
54 err = fmt.Errorf("Our content was not in the parsed data:\n\tExpected: %s\n\tActual: %s", content, p7.Content)
55 return
56 }
57 if err = p7.Verify(); err != nil {
58 err = fmt.Errorf("Cannot verify our signed data: %s", err)
59 return
60 }
61
62 return signed, nil
63}
64```
65
66
67
68## Credits
69This is a fork of [fullsailor/pkcs7](https://github.com/fullsailor/pkcs7)
View as plain text