github.com/emmansun/gmsm@v0.29.1/pkcs7/README.md (about)

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