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