Discuss this help topic in SecureBlackbox Forum

Sign document with CryptoAPI signature handler

To sign a binary document using CryptoAPI signature handler you need to

  1. load the document into an instance of TElOfficeBinaryDocument class
  2. create an instance of TElOfficeBinaryCryptoAPISignatureHandler class and add it to the document using TElOfficeDocument.AddSignature() method
  3. specify the options of the signature using SignTime and ExpireTime properties of the handler
  4. call Sign() method of the handler to sign the document
  5. use Close() or Flush() methods of the document to flush the changes

C#:


void SignBinaryCryptoAPI(string sourceFilename, TElX509Certificate certificate)
{
    using (TElOfficeDocument Document = new TElOfficeDocument())
    {
        Document.Open(sourceFilename);
        if ((Document.DocumentFormat != TSBOfficeDocumentFormat.Binary) || !Document.Signable)
            throw new Exception("Cannot sign document using Binary CryptoAPI signature handler");

        TElOfficeBinaryCryptoAPISignatureHandler BinCryptoAPISigHandler = new TElOfficeBinaryCryptoAPISignatureHandler();
        Document.AddSignature(BinCryptoAPISigHandler, true);

        BinCryptoAPISigHandler.SignTime = DateTime.UtcNow;
        BinCryptoAPISigHandler.ExpireTime = DateTime.UtcNow.AddYears(1);
        BinCryptoAPISigHandler.Sign(certificate);
        Document.Close();
    }
}
Delphi:

procedure SignBinaryCryptoAPI(const SourceFilename : string; Certificate : TElX509Certificate);
var
  Document : TElOfficeDocument;
  BinCryptoAPISigHandler : TElOfficeBinaryCryptoAPISignatureHandler;
begin
  Document := TElOfficeDocument.Create(nil);
  try
    Document.Open(SourceFilename);
    if (Document.DocumentFormat <> dfBinary) or (not Document.Signable) then
      raise Exception.Create('Cannot sign document using Binary CryptoAPI signature handler');

    BinCryptoAPISigHandler := TElOfficeBinaryCryptoAPISignatureHandler.Create(nil);
    Document.AddSignature(BinCryptoAPISigHandler, True);

    BinCryptoAPISigHandler.SignTime := UTCNow;
    BinCryptoAPISigHandler.ExpireTime := IncYear(UTCNow, 1);
    BinCryptoAPISigHandler.Sign(Certificate);
    Document.Close();
  finally
    FreeAndNil(Document);
  end;
end;

How To articles about MS Office binary documents

Discuss this help topic in SecureBlackbox Forum