Discuss this help topic in SecureBlackbox Forum

Create detached CMS signature

The easiest way to create a detached CMS signature with SecureBlackbox is using the TElSignedCMSMessage component. The following step-by-step example illustrates the most common scenario:

  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 true: cms.Detached = true;
  8. Save the message to the output stream:
    
    FileStream f = new FileStream("signature.p7s", FileMode.Create);
    try
    {
      cms.Save(f);
    }
    finally
    {
      f.Close();
    }
    
  9. Remember to save the content too, as it isn't going to be included in the signature:
    
    FileStream f = new FileStream("content.dat", FileMode.Create);
    try
    {
      f.Write(data, 0, data.Length);
    }
    finally
    {
      f.Close();
    }
    
    That's it, the detached signature is now saved in the 'signature.p7s' file.

How To articles about Cryptographic Message Syntax (CMS)

Discuss this help topic in SecureBlackbox Forum