XMLEncryptor Component
Properties Methods Events Config Settings Errors
The XMLEncryptor component encrypts XML documents.
Syntax
TsbxXMLEncryptor
Remarks
XMLEncryptor encrypts XML documents with certificates or generic keys.
Property List
The following is the full list of the properties of the component with short descriptions. Click on the links for further details.
Encoding | Specifies XML encoding. |
EncryptedDataType | Specifies the type of the data being encrypted. |
EncryptionKey | The symmetric (session) key used to encrypt the data. |
EncryptionMethod | The encryption method used to encrypt the document. |
EncryptKey | Specifies if the encryption key is encrypted. |
ExternalData | The data that should be encrypted. |
FIPSMode | Reserved. |
InputBytes | Use this property to pass the input to component in byte array form. |
InputFile | The XML document to be encrypted. |
KeyEncryptionCertBytes | Returns the raw certificate data in DER format. |
KeyEncryptionCertHandle | Allows to get or set a 'handle', a unique identifier of the underlying property object. |
KeyEncryptionKey | The symmetric key used to encrypt a session key. |
KeyEncryptionType | Specifies how the session key is encrypted. |
KeyTransportMethod | Specifies how the session key is encrypted. |
KeyWrapMethod | The key wrap method used to encrypt the session key. |
OutputBytes | Use this property to read the output the component object has produced. |
OutputFile | Defines where to save the encrypted XML document. |
UseGCM | Specifies if GCM mode is enabled. |
XMLNode | Defines the XML element to encrypt. |
Method List
The following is the full list of the methods of the component with short descriptions. Click on the links for further details.
AddKnownNamespace | Adds known prefix and correspondent namespace URI. |
Config | Sets or retrieves a configuration setting. |
DoAction | Performs an additional action. |
Encrypt | Encrypts an XML document. |
Reset | Resets the component settings. |
Event List
The following is the full list of the events fired by the component with short descriptions. Click on the links for further details.
Error | Information about errors during signing. |
FormatElement | Reports the XML element that is currently being processed. |
FormatText | Reports XML text that is currently being processed. |
Notification | This event notifies the application about an underlying control flow event. |
Config Settings
The following is a list of config settings for the component with short descriptions. Click on the links for further details.
EncryptedDataID | Specifies the ID for EncryptedData element. |
EncryptedKeyID | Specifies the ID for EncryptedKey element. |
EncryptedKeyInfoCustomXML | The custom XML content for EncryptedKey\\KeyInfo element. |
EncryptedKeyInfoID | Specifies the ID for EncryptedKey\\KeyInfo element. |
EncryptedKeyOnly | Specifies whether to create only EncryptedKey element. |
EncryptedKeyXMLElement | Specifies the XML element where to save the encrypted key element. |
EncryptionPrefix | Specifies the encryption prefix. |
KeyInfoCustomXML | The custom XML content for KeyInfo element. |
KeyInfoID | Specifies the ID for KeyInfo element. |
KeyName | Contains information about the key used for encryption. |
MimeType | Specifies the mime type of the encrypted data. |
SignaturePrefix | Specifies the signature prefix. |
TempPath | Path for storing temporary files. |
WriteBOM | Specifies whether byte-order mark should be written when saving the document. |
XMLFormatting | Specifies the signature XML formatting. |
ASN1UseGlobalTagCache | Controls whether ASN.1 module should use a global object cache. |
AssignSystemSmartCardPins | Specifies whether CSP-level PINs should be assigned to CNG keys. |
CheckKeyIntegrityBeforeUse | Enables or disable private key integrity check before use. |
CookieCaching | Specifies whether a cookie cache should be used for HTTP(S) transports. |
Cookies | Gets or sets local cookies for the component. |
DefDeriveKeyIterations | Specifies the default key derivation algorithm iteration count. |
DNSLocalSuffix | The suffix to assign for TLD names. |
EnableClientSideSSLFFDHE | Enables or disables finite field DHE key exchange support in TLS clients. |
GlobalCookies | Gets or sets global cookies for all the HTTP transports. |
HardwareCryptoUsePolicy | The hardware crypto usage policy. |
HttpUserAgent | Specifies the user agent name to be used by all HTTP clients. |
HttpVersion | The HTTP version to use in any inner HTTP client components created. |
IgnoreExpiredMSCTLSigningCert | Whether to tolerate the expired Windows Update signing certificate. |
ListDelimiter | The delimiter character for multi-element lists. |
LogDestination | Specifies the debug log destination. |
LogDetails | Specifies the debug log details to dump. |
LogFile | Specifies the debug log filename. |
LogFilters | Specifies the debug log filters. |
LogFlushMode | Specifies the log flush mode. |
LogLevel | Specifies the debug log level. |
LogMaxEventCount | Specifies the maximum number of events to cache before further action is taken. |
LogRotationMode | Specifies the log rotation mode. |
MaxASN1BufferLength | Specifies the maximal allowed length for ASN.1 primitive tag data. |
MaxASN1TreeDepth | Specifies the maximal depth for processed ASN.1 trees. |
OCSPHashAlgorithm | Specifies the hash algorithm to be used to identify certificates in OCSP requests. |
OldClientSideRSAFallback | Specifies whether the SSH client should use a SHA1 fallback. |
ProductVersion | Returns the version of the SecureBlackbox library. |
ServerSSLDHKeyLength | Sets the size of the TLS DHE key exchange group. |
StaticDNS | Specifies whether static DNS rules should be used. |
StaticIPAddress[domain] | Gets or sets an IP address for the specified domain name. |
StaticIPAddresses | Gets or sets all the static DNS rules. |
Tag | Allows to store any custom data. |
TLSSessionGroup | Specifies the group name of TLS sessions to be used for session resumption. |
TLSSessionLifetime | Specifies lifetime in seconds of the cached TLS session. |
TLSSessionPurgeInterval | Specifies how often the session cache should remove the expired TLS sessions. |
UseInternalRandom | Switches between SecureBlackbox-own and platform PRNGs. |
UseLegacyAdESValidation | Enables legacy AdES validation mode. |
UseOwnDNSResolver | Specifies whether the client components should use own DNS resolver. |
UseSharedSystemStorages | Specifies whether the validation engine should use a global per-process copy of the system certificate stores. |
UseSystemNativeSizeCalculation | An internal CryptoAPI access tweak. |
UseSystemOAEPAndPSS | Enforces or disables the use of system-driven RSA OAEP and PSS computations. |
UseSystemRandom | Enables or disables the use of the OS PRNG. |
Encoding Property (XMLEncryptor Component)
Specifies XML encoding.
Syntax
__property String Encoding = { read=FEncoding, write=FSetEncoding };
Default Value
""
Remarks
Use this property to specify the encoding to apply to the XML documents.
Data Type
String
EncryptedDataType Property (XMLEncryptor Component)
Specifies the type of the data being encrypted.
Syntax
__property TsbxXMLEncryptorEncryptedDataTypes EncryptedDataType = { read=FEncryptedDataType, write=FSetEncryptedDataType };
enum TsbxXMLEncryptorEncryptedDataTypes { cxedtElement=0, cxedtContent=1, cxedtExternal=2 };
Default Value
cxedtElement
Remarks
This property specifies the data type to be encrypted.
Supported values:
cxedtElement | 0 | The XML element is encrypted.
XMLNode property specifies the XML element that should be encrypted. |
cxedtContent | 1 | Element content is encrypted.
XMLNode property specifies the XML element which content should be encrypted. |
cxedtExternal | 2 | External data is encrypted. Use ExternalData property to set the data that should be encrypted.
XMLNode property specifies the location where xenc:EncryptedData element should be placed. |
Data Type
Integer
EncryptionKey Property (XMLEncryptor Component)
The symmetric (session) key used to encrypt the data.
Syntax
__property DynamicArrayEncryptionKey = { read=FEncryptionKey, write=FSetEncryptionKey };
Remarks
Use this property to provide the encryption symmetric (session) key that will be used to encrypt a data.
It is required when the EncryptKey property is disabled. If the EncryptKey property is enabled, and no value is set, the component will generate a random session key (recommended).
This property is not available at design time.
Data Type
Byte Array
EncryptionMethod Property (XMLEncryptor Component)
The encryption method used to encrypt the document.
Syntax
__property String EncryptionMethod = { read=FEncryptionMethod, write=FSetEncryptionMethod };
Default Value
"AES256"
Remarks
This property contains the encryption algorithm used to encrypt the XML document.
Supported values:
SB_XML_ENCRYPTION_ALGORITHM_RC4 | RC4 | |
SB_XML_ENCRYPTION_ALGORITHM_DES | DES | |
SB_XML_ENCRYPTION_ALGORITHM_3DES | 3DEST | |
SB_XML_ENCRYPTION_ALGORITHM_AES128 | AES128 | |
SB_XML_ENCRYPTION_ALGORITHM_AES192 | AES192 | |
SB_XML_ENCRYPTION_ALGORITHM_AES256 | AES256 | |
SB_XML_ENCRYPTION_ALGORITHM_CAMELLIA128 | Camellia128 | |
SB_XML_ENCRYPTION_ALGORITHM_CAMELLIA192 | Camellia192 | |
SB_XML_ENCRYPTION_ALGORITHM_CAMELLIA256 | Camellia256 | |
SB_XML_ENCRYPTION_ALGORITHM_SEED | SEED |
If UseGCM property is enabled, then supported values are:
SB_XML_ENCRYPTION_ALGORITHM_AES128 | AES128 | |
SB_XML_ENCRYPTION_ALGORITHM_AES192 | AES192 | |
SB_XML_ENCRYPTION_ALGORITHM_AES256 | AES256 |
Data Type
String
EncryptKey Property (XMLEncryptor Component)
Specifies if the encryption key is encrypted.
Syntax
__property bool EncryptKey = { read=FEncryptKey, write=FSetEncryptKey };
Default Value
false
Remarks
Use this property to specify if encryption (session) key should be encrypted and also added to the encrypted data.
Data Type
Boolean
ExternalData Property (XMLEncryptor Component)
The data that should be encrypted.
Syntax
__property DynamicArrayExternalData = { read=FExternalData, write=FSetExternalData };
Remarks
Use this property to provide the data that should be encrypted if EncryptedDataType property is set to cxedtExternal value.
This property is not available at design time.
Data Type
Byte Array
FIPSMode Property (XMLEncryptor Component)
Reserved.
Syntax
__property bool FIPSMode = { read=FFIPSMode, write=FSetFIPSMode };
Default Value
false
Remarks
This property is reserved for future use.
Data Type
Boolean
InputBytes Property (XMLEncryptor Component)
Use this property to pass the input to component in byte array form.
Syntax
__property DynamicArrayInputBytes = { read=FInputBytes, write=FSetInputBytes };
Remarks
Assign a byte array containing the data to be processed to this property.
This property is not available at design time.
Data Type
Byte Array
InputFile Property (XMLEncryptor Component)
The XML document to be encrypted.
Syntax
__property String InputFile = { read=FInputFile, write=FSetInputFile };
Default Value
""
Remarks
Provide the path to the XML document to be encrypted.
Data Type
String
KeyEncryptionCertBytes Property (XMLEncryptor Component)
Returns the raw certificate data in DER format.
Syntax
__property DynamicArrayKeyEncryptionCertBytes = { read=FKeyEncryptionCertBytes };
Remarks
Returns the raw certificate data in DER format.
This property is read-only and not available at design time.
Data Type
Byte Array
KeyEncryptionCertHandle Property (XMLEncryptor Component)
Allows to get or set a 'handle', a unique identifier of the underlying property object.
Syntax
__property __int64 KeyEncryptionCertHandle = { read=FKeyEncryptionCertHandle, write=FSetKeyEncryptionCertHandle };
Default Value
0
Remarks
Allows to get or set a 'handle', a unique identifier of the underlying property object. Use this property to assign objects of the same type in a quicker manner, without copying them fieldwise.
When you pass a handle of one object to another, the source object is copied to the destination rather than assigned. It is safe to get rid of the original object
after such operation.
pdfSigner.setSigningCertHandle(certMgr.getCertHandle());
This property is not available at design time.
Data Type
Long64
KeyEncryptionKey Property (XMLEncryptor Component)
The symmetric key used to encrypt a session key.
Syntax
__property DynamicArrayKeyEncryptionKey = { read=FKeyEncryptionKey, write=FSetKeyEncryptionKey };
Remarks
Use this property to provide the encryption symmetric key that will be used to encrypt a session key. It is required when the EncryptKey property is enabled and KeyEncryptionType is set to cxetKeyWrap value.
This property is not available at design time.
Data Type
Byte Array
KeyEncryptionType Property (XMLEncryptor Component)
Specifies how the session key is encrypted.
Syntax
__property TsbxXMLEncryptorKeyEncryptionTypes KeyEncryptionType = { read=FKeyEncryptionType, write=FSetKeyEncryptionType };
enum TsbxXMLEncryptorKeyEncryptionTypes { cxetKeyTransport=0, cxetKeyWrap=1 };
Default Value
cxetKeyTransport
Remarks
This property specifies how the session key is encrypted.
Supported values:
cxetKeyTransport | 0 | The key is encrypted using public-key based algorithm |
cxetKeyWrap | 1 | The key is encrypted using symmetric algorithm with pre-shared secret key |
Data Type
Integer
KeyTransportMethod Property (XMLEncryptor Component)
Specifies how the session key is encrypted.
Syntax
__property TsbxXMLEncryptorKeyTransportMethods KeyTransportMethod = { read=FKeyTransportMethod, write=FSetKeyTransportMethod };
enum TsbxXMLEncryptorKeyTransportMethods { cxktRSA15=0, cxktRSAOAEP=1 };
Default Value
cxktRSA15
Remarks
This property specifies how the session key is encrypted.
Supported values:
cxktRSA15 | 0 | RSA 1.5 (RSAES-PKCS1-v1_5) encryption is used |
cxktRSAOAEP | 1 | RSA-OAEP (RSAES-OAEP-ENCRYPT) encryption is used |
Data Type
Integer
KeyWrapMethod Property (XMLEncryptor Component)
The key wrap method used to encrypt the session key.
Syntax
__property String KeyWrapMethod = { read=FKeyWrapMethod, write=FSetKeyWrapMethod };
Default Value
"Camellia256"
Remarks
This property specifies the key wrap algorithm used to encrypt the session key.
Supported values:
SB_XML_ENCRYPTION_ALGORITHM_3DES | 3DEST | |
SB_XML_ENCRYPTION_ALGORITHM_AES128 | AES128 | |
SB_XML_ENCRYPTION_ALGORITHM_AES192 | AES192 | |
SB_XML_ENCRYPTION_ALGORITHM_AES256 | AES256 | |
SB_XML_ENCRYPTION_ALGORITHM_CAMELLIA128 | Camellia128 | |
SB_XML_ENCRYPTION_ALGORITHM_CAMELLIA192 | Camellia192 | |
SB_XML_ENCRYPTION_ALGORITHM_CAMELLIA256 | Camellia256 | |
SB_XML_ENCRYPTION_ALGORITHM_SEED | SEED |
Data Type
String
OutputBytes Property (XMLEncryptor Component)
Use this property to read the output the component object has produced.
Syntax
__property DynamicArrayOutputBytes = { read=FOutputBytes };
Remarks
Read the contents of this property after the operation has completed to read the produced output. This property will only be set if the OutputFile and OutputStream properties had not been assigned.
This property is read-only and not available at design time.
Data Type
Byte Array
OutputFile Property (XMLEncryptor Component)
Defines where to save the encrypted XML document.
Syntax
__property String OutputFile = { read=FOutputFile, write=FSetOutputFile };
Default Value
""
Remarks
Specifies the path where the encrypted XML document should be saved.
Data Type
String
UseGCM Property (XMLEncryptor Component)
Specifies if GCM mode is enabled.
Syntax
__property bool UseGCM = { read=FUseGCM, write=FSetUseGCM };
Default Value
false
Remarks
Use this property to enable Galois/Counter Mode (GCM) mode for AES encryption method.
Data Type
Boolean
XMLNode Property (XMLEncryptor Component)
Defines the XML element to encrypt.
Syntax
__property String XMLNode = { read=FXMLNode, write=FSetXMLNode };
Default Value
""
Remarks
Defines the XML element/node to encrypt or in case if cxedtExternal encryption data type is used where to save the encrypted data.
Supported values are:
"" | an empty string indicates the Document element |
"#id" | indicates an XML element with specified Id |
XPath expression | indicates an XML element selected using XPath expression. Use AddKnownNamespace method to specify Prefixes and NamespaceURIs
For example: "/root/data[1]" - indicates the second "data" element under the document element with a name "root" "//ns1:data" - indicates a data element. "ns1" prefix should be defined via AddKnownNamespace method. |
Node name | indicates an XML element selected using its NodeName.
For example: "data" - indicates an XML element with node name "data". |
Data Type
String
AddKnownNamespace Method (XMLEncryptor Component)
Adds known prefix and correspondent namespace URI.
Syntax
void __fastcall AddKnownNamespace(String Prefix, String URI);
Remarks
Use this method to add a known prefix and namespace URI that are used in XPath expression within XMLElement/XMLNode property, and within TargetXMLElement and XPathPrefixList properties of the references.
Config Method (XMLEncryptor Component)
Sets or retrieves a configuration setting.
Syntax
String __fastcall Config(String ConfigurationString);
Remarks
Config is a generic method available in every component. It is used to set and retrieve configuration settings for the component.
These settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the component, access to these internal properties is provided through the Config method.
To set a configuration setting named PROPERTY, you must call Config("PROPERTY=VALUE"), where VALUE is the value of the setting expressed as a string. For boolean values, use the strings "True", "False", "0", "1", "Yes", or "No" (case does not matter).
To read (query) the value of a configuration setting, you must call Config("PROPERTY"). The value will be returned as a string.
DoAction Method (XMLEncryptor Component)
Performs an additional action.
Syntax
String __fastcall DoAction(String ActionID, String ActionParams);
Remarks
DoAction is a generic method available in every component. It is used to perform an additional action introduced after the product major release. The list of actions is not fixed, and may be flexibly extended over time.
The unique identifier (case insensitive) of the action is provided in the ActionID parameter.
ActionParams contains the value of a single parameter, or a list of multiple parameters for the action in the form of PARAM1=VALUE1;PARAM2=VALUE2;....
Encrypt Method (XMLEncryptor Component)
Encrypts an XML document.
Syntax
void __fastcall Encrypt();
Remarks
Call this method to encrypt an XML document.
The component could be used to encrypt the SOAP message as well.
Example 1: Encrypting the SOAP message
void EncryptSOAPMessage(string inputFilename, string outputFilename, string cert, string certPassword)
{
string encKeyId = "EK-" + Guid.NewGuid().ToString();
string encDataId = "ED-" + Guid.NewGuid().ToString();
using (Xmlencryptor encryptor = new Xmlencryptor())
{
encryptor.InputFile = inputFilename;
encryptor.OutputFile = outputFilename;
string certB64;
using (Certificatemanager certMgr = new Certificatemanager())
{
certMgr.ImportFromFile(cert, certPassword);
encryptor.KeyEncryptionCertificate = certMgr.Certificate;
using (Utils utils = new Utils())
{
var certBytes = certMgr.Certificate.Bytes;
certB64 = utils.Base64Encode(certBytes, false);
}
}
encryptor.XMLNode = "/soapv11:Envelope/soapv11:Body";
encryptor.EncryptedDataType = XmlencryptorEncryptedDataTypes.cxedtContent;
encryptor.EncryptionMethod = "AES128";
encryptor.EncryptKey = true;
encryptor.KeyEncryptionType = XmlencryptorKeyEncryptionTypes.cxetKeyTransport;
encryptor.KeyTransportMethod = XmlencryptorKeyTransportMethods.cxktRSA15;
encryptor.Config($"EncryptedDataID={encDataId}");
encryptor.Config($"EncryptedKeyID={encKeyId}");
encryptor.Config("EncryptedKeyXMLElement=/soapv11:Envelope/soapv11:Header/wssev10:Security");
encryptor.Config("KeyInfoCustomXML=<wsse:SecurityTokenReference xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" " +
"xmlns:wsse11=\"http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd\" wsse11:TokenType=\"http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey\">" +
$"<wsse:Reference URI=\"#{encKeyId}\"/>" +
"</wsse:SecurityTokenReference>");
encryptor.Config("EncryptedKeyInfoCustomXML=<wsse:SecurityTokenReference xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
$"<ds:X509Data xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">{certB64}</ds:X509Data>" +
"</wsse:SecurityTokenReference>");
encryptor.Encrypt();
}
}
EncryptSOAPMessage(@"soap_test.xml", @"soap_encrypted.xml", @"cert.pfx", "password");
Note: The above code expects that the SOAP message has a WS Security header element.
Sample SOAP message:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="1"> </wsse:Security> </soap:Header> <soap:Body> <ns:Data xmlns:ns="http://test.com">Sample message</ns:Data> </soap:Body> </soap:Envelope>Sample encrypted SOAP message produced by the above code:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="1"> <xenc:EncryptedKey Id="EK-89565c75-9556-43d3-9de0-35ce6577e798" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"> <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <ds:X509Data xmlns:ds="http://www.w3.org/2000/09/xmldsig#">...</ds:X509Data> </wsse:SecurityTokenReference> </ds:KeyInfo> <xenc:CipherData> <xenc:CipherValue>...</xenc:CipherValue> </xenc:CipherData> </xenc:EncryptedKey> </wsse:Security> </soap:Header> <soap:Body> <xenc:EncryptedData Id="ED-90fe019e-0093-489d-a646-7ae0cee237c2" Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc"/> <ds:KeyInfo> <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" wsse11:TokenType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey"> <wsse:Reference URI="#EK-89565c75-9556-43d3-9de0-35ce6577e798"/> </wsse:SecurityTokenReference> </ds:KeyInfo> <xenc:CipherData> <xenc:CipherValue>...</xenc:CipherValue> </xenc:CipherData> </xenc:EncryptedData> </soap:Body> </soap:Envelope>Example 2: Decrypting the SOAP message
void DecryptSOAPMessage(string inputFilename, string outputFilename, string cert, string certPassword)
{
using (Xmldecryptor decryptor = new Xmldecryptor())
{
decryptor.InputFile = inputFilename;
decryptor.OutputFile = outputFilename;
using (Certificatemanager certMgr = new Certificatemanager())
{
certMgr.ImportFromFile(cert, certPassword);
decryptor.KeyDecryptionCertificate = certMgr.Certificate;
}
decryptor.XMLElement = "/soapv11:Envelope/soapv11:Body/xenc:EncryptedData";
decryptor.Config("EncryptedKeyXMLElement=/soapv11:Envelope/soapv11:Header/wssev10:Security");
decryptor.Decrypt();
}
}
DecryptSOAPMessage(@"soap_encrypted.xml", @"soap_decrypted.xml", @"cert.pfx", "password");
Example 3: Signing and encrypting the SOAP message
void SignAndEncryptSOAPMessage(string inputFilename, string outputFilename, string signingCert, string signingCertPassword, string encryptionCert, string encryptionCertPassword)
{
byte[] data;
string encKeyId = "EK-" + Guid.NewGuid().ToString();
string encDataId1 = "ED-" + Guid.NewGuid().ToString();
string encDataId2 = "ED-" + Guid.NewGuid().ToString();
// Step 1: Creating Web service security (WSS) signature
using (Soapsigner signer = new Soapsigner())
{
signer.InputFile = inputFilename;
// loading the signing certificate
using (Certificatemanager certMgr = new Certificatemanager())
{
certMgr.ImportFromFile(encryptionCert, encryptionCertPassword);
signer.SigningCertificate = certMgr.Certificate;
}
signer.NewSignature.SignatureType = SOAPSignatureTypes.sstWSSSignature;
signer.NewSignature.HashAlgorithm = "SHA256";
signer.NewSignature.XAdES = false;
signer.SecurityHeaderIndex = 0;
signer.AddBodyReference("ID-" + Guid.NewGuid().ToString(), false);
signer.Sign();
data = signer.OutputBytes;
}
using (Xmlencryptor encryptor = new Xmlencryptor())
{
// Step 2: loading the encryption certificate
string certB64;
using (Certificatemanager certMgr = new Certificatemanager())
{
certMgr.ImportFromFile(encryptionCert, encryptionCertPassword);
encryptor.KeyEncryptionCertificate = certMgr.Certificate;
using (Utils utils = new Utils())
{
var certBytes = certMgr.Certificate.Bytes;
certB64 = utils.Base64Encode(certBytes, false);
}
}
// Step 3: generating random key encryption key (128-bit length)
// this key will be used for both encryptions
byte[] KEK;
using (Rnd rnd = new Rnd())
{
KEK = rnd.NextBytes(16);
}
encryptor.KeyEncryptionKey = KEK;
// Step 4: encrypting Body element and placing encrypted key to the Security block in the SOAP Message Header
encryptor.XMLNode = "/soapv11:Envelope/soapv11:Body";
encryptor.EncryptedDataType = XmlencryptorEncryptedDataTypes.cxedtContent;
encryptor.EncryptionMethod = "AES128";
encryptor.EncryptKey = true;
encryptor.KeyEncryptionType = XmlencryptorKeyEncryptionTypes.cxetKeyTransport;
encryptor.KeyTransportMethod = XmlencryptorKeyTransportMethods.cxktRSA15;
encryptor.Config($"EncryptedDataID={encDataId1}");
encryptor.Config($"EncryptedKeyID={encKeyId}");
encryptor.Config("EncryptedKeyXMLElement=/soapv11:Envelope/soapv11:Header/wssev10:Security");
encryptor.Config("KeyInfoCustomXML=<wsse:SecurityTokenReference xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" " +
"xmlns:wsse11=\"http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd\" wsse11:TokenType=\"http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey\">" +
$"<wsse:Reference URI=\"#{encKeyId}\"/>" +
"</wsse:SecurityTokenReference>");
encryptor.Config("EncryptedKeyInfoCustomXML=<wsse:SecurityTokenReference xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
$"<ds:X509Data xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">{certB64}</ds:X509Data>" +
"</wsse:SecurityTokenReference>");
encryptor.InputBytes = data;
encryptor.Encrypt();
// Step 5: encrypting WSS Signature
encryptor.InputBytes = encryptor.OutputBytes;
// resetting settings
encryptor.Config("EncryptedKeyXMLElement=");
encryptor.Config("EncryptedKeyInfoCustomXML=");
encryptor.XMLNode = "/soapv11:Envelope/soapv11:Header/wsse:Security/ds:Signature";
encryptor.EncryptedDataType = XmlencryptorEncryptedDataTypes.cxedtElement;
encryptor.EncryptKey = false;
encryptor.Config($"EncryptedDataID={encDataId2}");
encryptor.Config("KeyInfoCustomXML=<wsse:SecurityTokenReference xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" " +
"xmlns:wsse11=\"http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd\" wsse11:TokenType=\"http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey\">" +
$"<wsse:Reference URI=\"#{encKeyId}\"/>" +
"</wsse:SecurityTokenReference>");
encryptor.Encrypt();
data = encryptor.OutputBytes;
}
// Step 6: miscellaneous XML DOM manipulations, not supported by XMLEncryptor, but may be required by SOAP standard
using (Soapsigner signer = new Soapsigner())
{
signer.InputBytes = data;
signer.OutputFile = outputFilename;
signer.Open();
// Adding xenc:ReferenceList element to xenc:EncryptedKey element
signer.SetInnerXML("/soapv11:Envelope/soapv11:Header/wssev10:Security/xenc:EncryptedKey",
signer.GetInnerXML("/soapv11:Envelope/soapv11:Header/wssev10:Security/xenc:EncryptedKey") +
"<xenc:ReferenceList>" +
$"<xenc:DataReference URI=\"#{encDataId1}\"/>" +
$"<xenc:DataReference URI=\"#{encDataId2}\"/>" +
"</xenc:ReferenceList>");
// swapping the order of elements in WSS Security header
// SOAP requires that items in the header are placed in the order that they will be processed, not the order they were generated
// because the decryption should be performed before veryfing SOAP message, the xenc:EncryptedKey element should be placed first
var encKeyContent = signer.GetOuterXML("/soapv11:Envelope/soapv11:Header/wssev10:Security/xenc:EncryptedKey");
var secContent = signer.GetInnerXML("/soapv11:Envelope/soapv11:Header/wssev10:Security");
var k = secContent.IndexOf(encKeyContent, StringComparison.Ordinal);
if (k != -1)
signer.SetInnerXML("/soapv11:Envelope/soapv11:Header/wssev10:Security", encKeyContent + secContent.Substring(0, k));
signer.Close(true);
}
}
SignAndEncryptSOAPMessage(@"soap_test.xml", @"soap_signed_encrypted.xml", @"cert.pfx", "password", @"cert2.pfx", "password2");
Sample SOAP message:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <ns:Data xmlns:ns="http://test.com">Sample message</ns:Data> </soap:Body> </soap:Envelope>Sample signed and encrypted SOAP message produced by the above code:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="1"> <xenc:EncryptedKey Id="EK-14e69f03-fc61-48f1-b825-b03ca613f0f8" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"> <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"/> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <ds:X509Data xmlns:ds="http://www.w3.org/2000/09/xmldsig#">...</ds:X509Data> </wsse:SecurityTokenReference> </ds:KeyInfo> <xenc:CipherData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"> <xenc:CipherValue>...</xenc:CipherValue> </xenc:CipherData> <xenc:ReferenceList> <xenc:DataReference URI="#ED-65385224-0bb5-43f0-b4bf-67a9e9452c10"/> <xenc:DataReference URI="#ED-4267b8f3-8662-4441-99ec-32a2e9180288"/> </xenc:ReferenceList> </xenc:EncryptedKey> <wsse:BinarySecurityToken ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" wsu:Id="id-1135467976" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">...</wsse:BinarySecurityToken> <xenc:EncryptedData Id="ED-4267b8f3-8662-4441-99ec-32a2e9180288" Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc"/> <ds:KeyInfo> <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" wsse11:TokenType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey"> <wsse:Reference URI="#EK-14e69f03-fc61-48f1-b825-b03ca613f0f8"/> </wsse:SecurityTokenReference> </ds:KeyInfo> <xenc:CipherData> <xenc:CipherValue>...</xenc:CipherValue> </xenc:CipherData> </xenc:EncryptedData> </wsse:Security> </soap:Header> <soap:Body wsu:Id="ID-5bbf3495-d919-416e-96c3-67759aab9cf8" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <xenc:EncryptedData Id="ED-65385224-0bb5-43f0-b4bf-67a9e9452c10" Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc"/> <ds:KeyInfo> <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" wsse11:TokenType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey"> <wsse:Reference URI="#EK-14e69f03-fc61-48f1-b825-b03ca613f0f8"/> </wsse:SecurityTokenReference> </ds:KeyInfo> <xenc:CipherData> <xenc:CipherValue>...</xenc:CipherValue> </xenc:CipherData> </xenc:EncryptedData> </soap:Body> </soap:Envelope>Example 4: Decrypting and verifying the SOAP message
void DecryptAndVerifySOAPMessage(string inputFilename, string outputFilename, string decryptionCert, string decryptionCertPassword)
{
byte[] data;
using (Xmldecryptor decryptor = new Xmldecryptor())
{
decryptor.InputFile = inputFilename;
decryptor.OutputFile = outputFilename;
using (Certificatemanager certMgr = new Certificatemanager())
{
certMgr.ImportFromFile(decryptionCert, decryptionCertPassword);
decryptor.KeyDecryptionCertificate = certMgr.Certificate;
}
decryptor.Config("EncryptedKeyXMLElement=/soapv11:Envelope/soapv11:Header/wssev10:Security");
decryptor.Decrypt();
}
using (Soapverifier verifier = new Soapverifier())
{
verifier.InputFile = outputFilename;
verifier.Verify();
if ((verifier.Signatures.Count != 1) || (verifier.Signatures[0].SignatureValidationResult != SignatureValidities.svtValid))
throw new Exception("Signature not found or failed to verify a signature");
}
}
DecryptAndVerifySOAPMessage(@"soap_signed_encrypted.xml", @"soap_signed_decrypted.xml", @"cert2.pfx", "password2");
Reset Method (XMLEncryptor Component)
Resets the component settings.
Syntax
void __fastcall Reset();
Remarks
Reset is a generic method available in every component.
Error Event (XMLEncryptor Component)
Information about errors during signing.
Syntax
typedef struct { int ErrorCode; String Description; } TsbxXMLEncryptorErrorEventParams; typedef void __fastcall (__closure *TsbxXMLEncryptorErrorEvent)(System::TObject* Sender, TsbxXMLEncryptorErrorEventParams *e); __property TsbxXMLEncryptorErrorEvent OnError = { read=FOnError, write=FOnError };
Remarks
The event is fired in case of exceptional conditions during signing.
ErrorCode contains an error code and Description contains a textual description of the error.
FormatElement Event (XMLEncryptor Component)
Reports the XML element that is currently being processed.
Syntax
typedef struct { String StartTagWhitespace; String EndTagWhitespace; int Level; String Path; bool HasChildElements; } TsbxXMLEncryptorFormatElementEventParams; typedef void __fastcall (__closure *TsbxXMLEncryptorFormatElementEvent)(System::TObject* Sender, TsbxXMLEncryptorFormatElementEventParams *e); __property TsbxXMLEncryptorFormatElementEvent OnFormatElement = { read=FOnFormatElement, write=FOnFormatElement };
Remarks
Path and Level specify the path to the XML element being processed and its nesting level, respectively.
HasChildElements specify if processed XML element has child elements.
Among other purposes, this event may be used to add whitespace formatting before or after a particular element in the signature.
FormatText Event (XMLEncryptor Component)
Reports XML text that is currently being processed.
Syntax
typedef struct { String Text; int TextType; int Level; String Path; } TsbxXMLEncryptorFormatTextEventParams; typedef void __fastcall (__closure *TsbxXMLEncryptorFormatTextEvent)(System::TObject* Sender, TsbxXMLEncryptorFormatTextEventParams *e); __property TsbxXMLEncryptorFormatTextEvent OnFormatText = { read=FOnFormatText, write=FOnFormatText };
Remarks
TextType parameter specifies the type of the XML text (normal or Base64-encoded) that is stored in the element; Path and Level specify the path to the XML element and its nesting level.
Among other purposes, this event may be used to add whitespace formatting before or after a particular element in the signature.
Notification Event (XMLEncryptor Component)
This event notifies the application about an underlying control flow event.
Syntax
typedef struct { String EventID; String EventParam; } TsbxXMLEncryptorNotificationEventParams; typedef void __fastcall (__closure *TsbxXMLEncryptorNotificationEvent)(System::TObject* Sender, TsbxXMLEncryptorNotificationEventParams *e); __property TsbxXMLEncryptorNotificationEvent OnNotification = { read=FOnNotification, write=FOnNotification };
Remarks
The component fires this event to let the application know about some event, occurrence, or milestone in the component. For example, it may fire to report completion of the document processing. The list of events being reported is not fixed, and may be flexibly extended over time.
The unique identifier of the event is provided in the EventID parameter. EventParam contains any parameters accompanying the occurrence. Depending on the type of the component, the exact action it is performing, or the document being processed, one or both may be omitted.
Config Settings (XMLEncryptor Component)
The component accepts one or more of the following configuration settings. Configuration settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the component, access to these internal properties is provided through the Config method.XMLEncryptor Config Settings
The empty elements in the custom XML content act as a placeholder for auto-generated elements.
For example to change the order of ds:KeyValue and ds:X509Data auto-generated elements use the value: "<X509Data/><KeyValue/>"
Supported values are:
"" | an empty string indicates the Document element |
"#id" | indicates an XML element with specified Id |
XPath expression | indicates an XML element selected using XPath expression. Use AddKnownNamespace method to specify Prefixes and NamespaceURIs
For example: "/root/data[1]" - indicates the second "data" element under the document element with a name "root" "//ns1:data" - indicates a data element. "ns1" prefix should be defined via AddKnownNamespace method. |
Node name | indicates an XML element selected using its NodeName.
For example: "data" - indicates an XML element with node name "data". |
Default value is "xenc". In this case "xenc:" prefix will be used.
Special values:
"#default" or "" | indicates that the prefix will be omitted. |
"#auto" | indicates that the prefix will be auto-detected based on the parent nodes. |
The empty elements in the custom XML content act as a placeholder for auto-generated elements.
For example to change the order of ds:KeyValue and ds:X509Data auto-generated elements use the value: "<X509Data/><KeyValue/>"
Default value is "ds". In this case "ds:" prefix will be used.
Special values:
"#default" or "" | indicates that the prefix will be omitted. |
"#auto" | indicates that the prefix will be auto-detected based on the parent nodes. |
Supported values:
"" or "none" | no formatting (by default). | |
"auto" | enables auto-formatting, equivalent to: "indent: 1; indent-char: tab; base64-max-length: 64; starting-level: node" |
indent | specifies indentation level (default is 1) | |
indent-char | specifies indentation character: "space" or "tab" (default) | |
base64-max-length | specifies max length of base64 encoded data, such as signature value, certificate data and etc. (default is 64) | |
starting-level | specifies starting indentation level: non-negative integer or "node" - detected based on parent node, or "root" - detected based on number of parent nodes to a document element (default is "node"). | |
indent-before-main | specifies if whitespace characters should be inserted before a main (ds:Signature) element: "auto" (default), "yes" or "no" |
Base Config Settings
You can switch this property off to improve performance if your project only uses known, good private keys.
Supported values are:
off | No caching (default) | |
local | Local caching | |
global | Global caching |
This setting only applies to sessions negotiated with TLS version 1.3.
Supported values are:
file | File | |
console | Console | |
systemlog | System Log (supported for Android only) | |
debugger | Debugger (supported for VCL for Windows and .Net) |
Supported values are:
time | Current time | |
level | Level | |
package | Package name | |
module | Module name | |
class | Class name | |
method | Method name | |
threadid | Thread Id | |
contenttype | Content type | |
content | Content | |
all | All details |
Supported filter names are:
exclude-package | Exclude a package specified in the value | |
exclude-module | Exclude a module specified in the value | |
exclude-class | Exclude a class specified in the value | |
exclude-method | Exclude a method specified in the value | |
include-package | Include a package specified in the value | |
include-module | Include a module specified in the value | |
include-class | Include a class specified in the value | |
include-method | Include a method specified in the value |
none | No flush (caching only) | |
immediate | Immediate flush (real-time logging) | |
maxcount | Flush cached entries upon reaching LogMaxEventCount entries in the cache. |
Supported values are:
none | None (by default) | |
fatal | Severe errors that cause premature termination. | |
error | Other runtime errors or unexpected conditions. | |
warning | Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". | |
info | Interesting runtime events (startup/shutdown). | |
debug | Detailed information on flow of through the system. | |
trace | More detailed information. |
The default value of this setting is 100.
none | No rotation | |
deleteolder | Delete older entries from the cache upon reaching LogMaxEventCount | |
keepolder | Keep older entries in the cache upon reaching LogMaxEventCount (newer entries are discarded) |
Supported values are:
none | No static DNS rules (default) | |
local | Local static DNS rules | |
global | Global static DNS rules |
This setting only applies to certificates originating from a Windows system store.
Trappable Errors (XMLEncryptor Component)
XMLEncryptor Errors
1048577 | Invalid parameter (SB_ERROR_INVALID_PARAMETER) |
1048578 | Invalid configuration (SB_ERROR_INVALID_SETUP) |
1048579 | Invalid state (SB_ERROR_INVALID_STATE) |
1048580 | Invalid value (SB_ERROR_INVALID_VALUE) |
1048581 | Private key not found (SB_ERROR_NO_PRIVATE_KEY) |
1048582 | Cancelled by the user (SB_ERROR_CANCELLED_BY_USER) |
1048583 | The file was not found (SB_ERROR_NO_SUCH_FILE) |
1048584 | Unsupported feature or operation (SB_ERROR_UNSUPPORTED_FEATURE) |
1048585 | General error (SB_ERROR_GENERAL_ERROR) |
39845889 | The input file does not exist (SB_ERROR_XML_INPUTFILE_NOT_EXISTS) |
39845890 | Data file does not exist (SB_ERROR_XML_DATAFILE_NOT_EXISTS) |
39845892 | Unsupported hash algorithm (SB_ERROR_XML_UNSUPPORTED_HASH_ALGORITHM) |
39845893 | Unsupported key type (SB_ERROR_XML_UNSUPPORTED_KEY_TYPE) |
39845895 | Unsupported encryption algorithm (SB_ERROR_XML_INVALID_ENCRYPTION_METHOD) |
39845896 | XML element not found (SB_ERROR_XML_NOT_FOUND) |
39845897 | XML element has no ID (SB_ERROR_XML_NO_ELEMENT_ID) |