Discuss this help topic in SecureBlackbox Forum
XML: Encrypt element contents
First set TElXMLEncryptor.EncryptedDataType property to xedtContent.
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 the node, whose contents you need to be encrypted.
Call Save() method of TElXMLEncryptor class. The method will return the node, which contains the encrypted data.
Finally you need to clear the content of the XML element and add the encrypted node.
C#:
void Encrypt(TElXMLDOMElement ParentElement, byte[] AESKey)
{
TElXMLEncryptor Encryptor = new TElXMLEncryptor(null);
TElXMLKeyInfoSymmetricData SymKeyData = new TElXMLKeyInfoSymmetricData(true);
try
{
Encryptor.EncryptedDataType = SBXMLSec.Unit.xedtContent;
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(ParentElement);
TElXMLDOMElement EncryptedNode = Encryptor.Save(ParentElement.OwnerDocument);
// then clear the content of the xml element and add the encrypted node
while (ParentElement.LastChild != null)
ParentElement.RemoveChild(ParentElement.LastChild);
ParentElement.AppendChild(EncryptedNode);
}
finally
{
Encryptor.Dispose();
SymKeyData.Dispose();
}
}
Delphi:
procedure Encrypt(ParentElement : TElXMLDOMElement; const AESKey : ByteArray);
var
Encryptor : TElXMLEncryptor;
SymKeyData : TElXMLKeyInfoSymmetricData;
EncryptedNode : TElXMLDOMElement;
begin
Encryptor := TElXMLEncryptor.Create(nil);
SymKeyData := TElXMLKeyInfoSymmetricData.Create(True);
try
Encryptor.EncryptedDataType := xedtContent;
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(ParentElement);
EncryptedNode := Encryptor.Save(ParentElement.OwnerDocument);
// then clear the content of the xml element and add the encrypted node
while Assigned(ParentElement.LastChild) do
ParentElement.RemoveChild(ParentElement.LastChild);
ParentElement.AppendChild(EncryptedNode);
finally
FreeAndNil(Encryptor);
FreeAndNil(SymKeyData);
end;
end;