Discuss this help topic in SecureBlackbox Forum

XML: Encyrpt arbitrary data

First set TElXMLEncryptor.EncryptedDataType property to xedtExternal.

Next, setup properties, related to encryption algorithm and keys, such as TElXMLEncryptor.EncryptionMethod, TElXMLEncryptor.KeyData and optionally TElXMLEncryptor.KeyName.

Then call TElXMLEncryptor.Encrypt() method and pass it the data that you want to encrypt.

Call Save() method of TElXMLEncryptor class. The method will return the node, which contains the encrypted data.

Finally you can append the node with encrypted data to the document where you need it.

C#:


TElXMLDOMDocument Encrypt(byte[] DataToEncrypt, byte[] AESKey)
{
  TElXMLEncryptor Encryptor = new TElXMLEncryptor(null);
  TElXMLKeyInfoSymmetricData SymKeyData = new TElXMLKeyInfoSymmetricData(true);
  try
  {
    Encryptor.EncryptedDataType = SBXMLSec.Unit.xedtExternal;
    Encryptor.EncryptionMethod = SBXMLSec.Unit.xemAES;

    // setup the key
    SymKeyData.Key.Key = AESKey;
    SymKeyData.Key.GenerateIV(16 * 8); // generate random IV (initialization vector)
    Encryptor.KeyData = SymKeyData;

    // encrypt the data
    Encryptor.Encrypt(DataToEncrypt);

    // we create a temporary XML document to hold the encrypted node
    TElXMLDOMDocument Result = new TElXMLDOMDocument();
    TElXMLDOMElement EncryptedNode = null;
    try
    {
      EncryptedNode = Encryptor.Save(Result);
    }
    catch (Exception e)
    {
      Result.Dispose();
      throw;
    }

    Result.AppendChild(EncryptedNode);
    return Result;
  }
  finally
  {
    Encryptor.Dispose();
    SymKeyData.Dispose();
  }
}
Delphi:

function Encrypt(const DataToEncrypt : ByteArray; const AESKey : ByteArray): TElXMLDOMDocument;
var
  Encryptor : TElXMLEncryptor;
  SymKeyData : TElXMLKeyInfoSymmetricData;
  EncryptedNode : TElXMLDOMElement;
begin
  Encryptor := TElXMLEncryptor.Create(nil);
  SymKeyData := TElXMLKeyInfoSymmetricData.Create(True);
  try
    Encryptor.EncryptedDataType := xedtExternal;
    Encryptor.EncryptionMethod := xemAES;

    // setup the key
    SymKeyData.Key.Key := AESKey;
    SymKeyData.Key.GenerateIV(16 * 8); // generate random IV (initialization vector)
    Encryptor.KeyData :=  SymKeyData;

    Encryptor.Encrypt(DataToEncrypt);

    // we create a temporary XML document to hold the encrypted node
    Result := TElXMLDOMDocument.Create;
    try
      EncryptedNode := Encryptor.Save(Result);
    except
      FreeAndNil(Result);
      raise;
    end;

    Result.AppendChild(EncryptedNode);
  finally
    FreeAndNil(Encryptor);
    FreeAndNil(SymKeyData);
  end;
end;

How To articles about XML encryption (XMLEnc)

Discuss this help topic in SecureBlackbox Forum