Discuss this help topic in SecureBlackbox Forum

Encrypt document with standard encryption handler

To encrypt OpenXML (Office Open XML, OOXML) document using standard encryption handler

  1. load the document into an instance of TElOfficeOpenXMLDocument class
  2. if the document is encryptable, create an instance of TElOfficeOpenXMLStandardEncryptionHandler class
  3. set Password and EncryptionAlgorithm (supported algorithms are 128-, 192- and 256-bit AES) properties of the created encryption handler instance
  4. assign this encryption handler to TElOfficeDocument.EncryptionHandler property
  5. call TElOfficeBinaryDocument.EncryptTo() method to encrypt and save the document to a stream.

C#:


void EncryptOpenXMLStandard(string sourceFilename, string destFilename, string password)
{
    TElOfficeDocument Document = new TElOfficeDocument();
    TElOfficeOpenXMLStandardEncryptionHandler StandardEncryptionHandler = new TElOfficeOpenXMLStandardEncryptionHandler();
    try
    {
        Document.Open(sourceFilename);
        if ((Document.DocumentFormat != TSBOfficeDocumentFormat.OpenXML) && !Document.Encryptable)
            throw new Exception("Cannot encrypt OpenXML document using Standard encryption handler");

        StandardEncryptionHandler.Password = password;
        StandardEncryptionHandler.EncryptionAlgorithm = SBConstants.Unit.SB_ALGORITHM_CNT_AES256;
        Document.EncryptionHandler = StandardEncryptionHandler;

        using (FileStream f = new FileStream(destFilename, FileMode.CreateNew))
        {
            Document.EncryptTo(f);
        }
    }
    finally
    {
        Document.Dispose();
        StandardEncryptionHandler.Dispose();
    }
}
Delphi:

procedure EncryptOpenXMLStandard(const SourceFilename, DestFilename, Password : string);
var
  Document : TElOfficeDocument;
  StandardEncryptionHandler : TElOfficeOpenXMLStandardEncryptionHandler;
  F : TFileStream;
begin
  Document := TElOfficeDocument.Create(nil);
  StandardEncryptionHandler := TElOfficeOpenXMLStandardEncryptionHandler.Create(nil);
  try
    Document.Open(SourceFilename);
    if (Document.DocumentFormat <> dfOpenXML) and not Document.Encryptable then
      raise Exception.Create('Cannot encrypt OpenXML document using Standard encryption handler');

    StandardEncryptionHandler.Password := Password;
    StandardEncryptionHandler.EncryptionAlgorithm := SB_ALGORITHM_CNT_AES256;
    Document.EncryptionHandler := StandardEncryptionHandler;

    F := TFileStream.Create(DestFilename, fmCreate or fmShareDenyWrite);
    try
      Document.EncryptTo(F);
    finally
      FreeAndNil(F);
    end;
  finally
    FreeAndNil(Document);
    FreeAndNil(StandardEncryptionHandler);
  end;
end;

How To articles about MS Office OpenXML documents

Discuss this help topic in SecureBlackbox Forum