Discuss this help topic in SecureBlackbox Forum
XML: Encrypt XML element
First set TElXMLEncryptor.EncryptedDataType property to xedtElement.
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 to be encrypted.
Call Save() method of TElXMLEncryptor class. The method will return the node, which contains the encrypted data.
Finally you need to replace the node, which you encrypted, with the resulting node. This is done by calling ReplaceChild() method as follows: ANode.ParentNode.ReplaceChild(AnEncryptedNode, AnOriginalNode).
C#:
void Encrypt(TElXMLDOMElement ElementToEncrypt, byte[] AESKey)
{
TElXMLEncryptor Encryptor = new TElXMLEncryptor(null);
TElXMLKeyInfoSymmetricData SymKeyData = new TElXMLKeyInfoSymmetricData(true);
try
{
Encryptor.EncryptedDataType = SBXMLSec.Unit.xedtElement;
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(ElementToEncrypt);
TElXMLDOMElement EncryptedNode = Encryptor.Save(ElementToEncrypt.OwnerDocument);
// then replace an xml element that was encrypted
ElementToEncrypt.ParentNode.ReplaceChild(EncryptedNode, ElementToEncrypt);
}
finally
{
Encryptor.Dispose();
SymKeyData.Dispose();
}
}
Delphi:
procedure Encrypt(ElementToEncrypt : TElXMLDOMElement; const AESKey : ByteArray);
var
Encryptor : TElXMLEncryptor;
SymKeyData : TElXMLKeyInfoSymmetricData;
EncryptedNode : TElXMLDOMElement;
begin
Encryptor := TElXMLEncryptor.Create(nil);
SymKeyData := TElXMLKeyInfoSymmetricData.Create(True);
try
Encryptor.EncryptedDataType := xedtElement;
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(ElementToEncrypt);
EncryptedNode := Encryptor.Save(ElementToEncrypt.OwnerDocument);
// then replace an xml element that was encrypted
ElementToEncrypt.ParentNode.ReplaceChild(EncryptedNode, ElementToEncrypt);
finally
FreeAndNil(Encryptor);
FreeAndNil(SymKeyData);
end;
end;