Discuss this help topic in SecureBlackbox Forum

Encrypt document with ARCFOUR encryption handler

To encrypt a binary document using 40-bit RC4 encryption handler you need to

  1. load the document into an instance of TElOfficeBinaryDocument class
  2. if the document is encryptable, create an instance of TElOfficeBinaryRC4EncryptionHandler class
  3. set Password property 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 EncryptBinaryRC4(string sourceFilename, string destFilename, string password)
{
    TElOfficeDocument Document = new TElOfficeDocument();
    TElOfficeBinaryRC4EncryptionHandler RC4EncryptionHandler = new TElOfficeBinaryRC4EncryptionHandler();
    try
    {
        Document.Open(sourceFilename);
        if ((Document.DocumentFormat != TSBOfficeDocumentFormat.Binary) || !Document.Encryptable)
            throw new Exception("Cannot encrypt document using binary RC4 encryption handler");

        RC4EncryptionHandler.Password = password;
        Document.EncryptionHandler = RC4EncryptionHandler;

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

procedure EncryptBinaryRC4(const SourceFilename, DestFilename, Password : string);
var
  Document : TElOfficeDocument;
  RC4EncryptionHandler : TElOfficeBinaryRC4EncryptionHandler;
  F : TFileStream;
begin
  Document := TElOfficeDocument.Create(nil);
  RC4EncryptionHandler := TElOfficeBinaryRC4EncryptionHandler.Create(nil);
  try
    Document.Open(SourceFilename);
    if (Document.DocumentFormat <> dfBinary) or not Document.Encryptable then
      raise Exception.Create('Cannot encrypt document using binary RC4 encryption handler');

    RC4EncryptionHandler.Password := Password;
    Document.EncryptionHandler := RC4EncryptionHandler;

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

How To articles about MS Office binary documents

Discuss this help topic in SecureBlackbox Forum