Discuss this help topic in SecureBlackbox Forum

Create enveloping CMS signature

The easiest way to create an enveloping CMS signature (the signature that includes the signed data in its body) with SecureBlackbox is using its TElSignedCMSMessage component. Follow the below step-by-step guidance to create one over your data:

  1. Create an instance of TElSignedCMSMessage class: TElSignedCMSMessage cms = new TElSignedCMSMessage();
  2. Create a brand new message structure by passing your content (the data that you want to sign) to the cms's CreateNew() method:
    
    byte[] data = Encoding.UTF8Encoding.UTF8.GetBytes("One thing I can tell you is we got to be free");
    cms.CreateNew(data, 0, data.Length);
    
  3. Add a signature object:
    
    int sigIndex = cms.AddSignature(); // for new signatures sigIndex will always be 0, but it is a good practice to do it that way
    TElCMSSignature sig = cms.get_Signatures(sigIndex);
    
  4. Configure the signature object as needed. Set SigningTime, ContentType and other attributes (read more on signature attributes here). sig.SigningTime = DateTime.UtcNow;
  5. Load your signing certificate (private key is a must!):
    
    TElX509Certificate cert = new TElX509Certificate();
    int r = cert.LoadFromFileAuto("cert.pfx", "password");
    if (r != 0) {
      throw new Exception("Failed to load the signing certificate");
    }
    
  6. Finalize the signature by actually signing it: sig.Sign(cert, null); While the above call passes null as the second parameter, you can use it to pass a certificate chain to be included in the signature.
  7. Set cms's Detached property to false: cms.Detached = false;
  8. Save the message to the output stream:
    
    FileStream f = new FileStream("signature.p7s", FileMode.Create);
    try
    {
      cms.Save(f);
    }
    finally
    {
      f.Close();
    }
    
    That's it, the enveloping signature is now saved in the 'signature.p7s' file.

How To articles about Cryptographic Message Syntax (CMS)

Discuss this help topic in SecureBlackbox Forum