MATLAB XML DOM Creation & SOAP Digital Signature
Step-by-step guide to build, sign, and send SOAP messages with MATLAB
Highlights
- XML DOM Creation: Use MATLAB’s XML DOM functions to build and manipulate XML structures.
- Canonicalization & Digital Signature: Transform XML to canonical form, compute SHA-256 digest, and generate an RSA signature.
- SOAP Integration & HTTPS Posting: Embed the signature into a SOAP envelope and securely post using a .p12 certificate.
Introduction
In this detailed guide, we will describe the steps required to process XML data in MATLAB, canonically transform the DOM representation, compute a digital signature using RSA encryption of a SHA-256 digest, and finally, send the signed SOAP message over HTTPS using a .p12 certificate. This process is particularly useful when interacting with secure web services, where the integrity and authenticity of the message must be maintained.
Step 1: Creating the DOM Representation
Overview
MATLAB provides a package dedicated to XML manipulation, which includes creating a Document Object Model (DOM) representation. Our XML data, as provided, is:
% XML Data
xmlString = ['<CsbReport ApplicationType="CSB_REPORT" ParticipantName="PT_400198">', ...
'<ReportListRequest ReportType="STTL_STATEMENT" MarketName="BALIMB" ', ...
'RunType="INDICATIVE" StartDate="2024-06-09" EndDate="2024-06-09"/>', ...
'</CsbReport>'];
Using MATLAB’s matlab.io.xml.dom package, we can convert this string into a DOM document. The following example illustrates the process:
% Import the XML DOM package
import matlab.io.xml.dom.*
% Define the XML string as provided in the specification.
xmlString = ['<CsbReport ApplicationType="CSB_REPORT" ParticipantName="PT_400198">', ...
'<ReportListRequest ReportType="STTL_STATEMENT" MarketName="BALIMB" ', ...
'RunType="INDICATIVE" StartDate="2024-06-09" EndDate="2024-06-09"/>', ...
'</CsbReport>'];
% Create a parser and parse the XML string into a DOM object.
parser = matlab.io.xml.dom.Parser();
doc = parseString(parser, xmlString);
% Display the DOM document structure in the command window.
disp(doc);
This piece of code creates a DOM representation of the XML data. Notice how the XML string is concatenated, ensuring it is well-formed and suitable for parsing.
Step 2: Canonicalizing the XML Data
Canonicalization Overview
Canonicalization is essential for digital signatures because it ensures that the XML data is in a standardized format. According to the W3C specification (XML Canonicalization with Comments), specific transformations are applied to the XML so that semantically identical documents have a single canonical form.
Canonicalization in MATLAB
MATLAB does not have direct built-in support for full XML canonicalization as per the W3C specification. However, there are ways to work around this limitation:
- Method 1: Use external Java libraries such as Apache Santuario to perform canonicalization. MATLAB can interface with Java directly.
- Method 2: Assuming the XML data is simple and does not require complex canonicalization rules, use MATLAB’s
xmlwriteto output the XML in a consistent format.
For demonstration purposes, the following code segment shows how to output a canonical-like representation using xmlwrite:
% Canonicalize the XML by writing it as a string (this is a simplified approach)
canonicalizedXml = xmlwrite(doc);
disp(canonicalizedXml);
% When stricter canonicalization is required, you may need to use Java:
% Example (requires Apache Santuario library):
% import org.apache.xml.security.c14n.Canonicalizer;
% xmlString = char(doc.getXml);
% canonicalizer = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
% canonicalizedBytes = canonicalizer.canonicalize(xmlString.getBytes);
% canonicalizedXml = native2unicode(canonicalizedBytes, 'UTF-8');
Using an external Java library offers a robust solution to attain the exact canonical form demanded by the specification.
Step 3: Generating the Digital Signature
Digital Signature Process
The goal is to digitally sign the canonicalized XML data. This involves first computing the SHA-256 digest of the XML and then encrypting that digest using RSA with the participant’s private key. The process uses cryptographic functions available within MATLAB’s Java integration or third-party libraries that support cryptography.
a. Compute the SHA-256 Digest
Computing a SHA-256 digest transforms your canonical XML into a fixed-size binary representation that summarizes the data. MATLAB can interface with Java classes for this purpose:
% Import Java security classes
import java.security.*;
% Convert the canonicalized XML into bytes using UTF-8 encoding.
xmlBytes = uint8(canonicalizedXml);
% Create a MessageDigest instance for SHA-256
messageDigest = MessageDigest.getInstance('SHA-256');
% Compute the SHA-256 digest of the XML bytes.
digest = messageDigest.digest(xmlBytes);
% Display the digest (as numeric array)
disp(digest);
b. RSA Encryption with a Private Key
Encrypting the digest with RSA using the participant's private key ensures that the signature is uniquely associated with the sender. Typically, the private key is stored in a .p12 file. MATLAB can interface with Java’s security libraries to load and use this key. The following example illustrates the concept:
% Load the private key from a PKCS12 (.p12) certificate
% Replace 'path/to/certificate.p12' and 'your_password' with actual values.
p12File = 'path/to/certificate.p12';
p12Password = 'your_password';
import java.io.FileInputStream;
import java.security.KeyStore;
% Load the certificate file into a KeyStore object
p12InputStream = FileInputStream(p12File);
keyStore = KeyStore.getInstance('PKCS12');
keyStore.load(p12InputStream, p12Password.toCharArray());
% Retrieve the private key (replace 'alias' with the correct alias)
privateKey = keyStore.getKey('alias', p12Password.toCharArray());
% Create the Signature object for signing using SHA256withRSA algorithm
signatureObj = Signature.getInstance('SHA256withRSA');
signatureObj.initSign(privateKey);
signatureObj.update(digest);
% Generate the digital signature (binary format)
binarySignature = signatureObj.sign();
disp(binarySignature);
This segment of the code performs the RSA encryption on the SHA-256 digest. Note that the actual alias used in the KeyStore must match the certificate details.
Step 4: Base64-Encoding the Signature
Encoding Process
Before incorporating the digital signature into a SOAP message, it must be converted into a base64-encoded string. MATLAB offers built-in functions for this encoding process:
% Convert the binary signature into a base64-encoded string
base64Signature = matlab.net.base64encode(binarySignature);
% Print the base64-encoded signature
disp(base64Signature);
The base64 encoding ensures that the binary signature data remains intact across web protocols which may not handle raw binary appropriately.
Step 5: Embedding the Signature in a SOAP Message
SOAP Message Construction
A SOAP (Simple Object Access Protocol) envelope is typically used for exchanging structured information in web services. The following sample code builds a SOAP envelope, places the base64-encoded signature in the header, and includes the XML body:
% Construct the SOAP envelope with the signature embedded
soapEnvelope = sprintf(['<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/">' ...
'<soap:Header>' ...
'<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soap:mustUnderstand="true">' ...
'<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">' ...
'<ds:SignedInfo>' ...
'<ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xmlc14n-20010315"/>' ...
'<ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>' ...
'<ds:Reference URI="">' ...
'<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>' ...
'<ds:DigestValue>%s</ds:DigestValue>' ...
'</ds:Reference>' ...
'</ds:SignedInfo>' ...
'<ds:SignatureValue>%s</ds:SignatureValue>' ...
'</ds:Signature>' ...
'</wsse:Security>' ...
'</soap:Header>' ...
'<soap:Body>%s</soap:Body>' ...
'</soap:Envelope>'], ...
matlab.net.base64encode(digest), base64Signature, canonicalizedXml);
disp(soapEnvelope);
This code effectively builds a SOAP message embedding the generated signature. It follows a common structure whereby the digital signature is placed within the SOAP header under suitable namespace declarations to comply with the XML Digital Signature standard.
Step 6: POSTing the SOAP Message Using a .p12 Certificate
SOAP Message Transmission
For secure communication, the SOAP message must be sent over HTTPS using a .p12 certificate for authentication. MATLAB’s webwrite function can be utilized in combination with web options to specify the certificate for SSL encryption.
Sample Code for HTTPS POST
Below is a MATLAB snippet that demonstrates how to post the SOAP message:
% Define the endpoint URL where the SOAP message is to be sent
url = 'https://your-soap-endpoint.com/service';
% Configure web options to use the .p12 certificate and the associated password.
options = weboptions('CertificateFile', p12File, 'CertificatePassword', p12Password, 'MediaType', 'application/soap+xml');
% POST the SOAP message to the server
response = webwrite(url, soapEnvelope, options);
% Display the server response
disp(response);
This final code segment demonstrates posting the SOAP message using MATLAB’s webwrite function. Ensure that the certificate file path and password are correctly provided and that the SOAP service endpoint is accurate.
Comprehensive Overview Table
| Step | Description | MATLAB Function / Technique |
|---|---|---|
| 1. DOM Representation | Create a DOM from the provided XML data. | matlab.io.xml.dom.Parser, parseString |
| 2. Canonicalization | Transform XML into a standard format (with comments). | xmlwrite or Java library (Apache Santuario) |
| 3. Compute SHA-256 Digest | Hash the canonical XML to produce a digest. | Java Security: MessageDigest |
| 4. RSA Signature Generation | Encrypt the digest using RSA with the private key. | Java Security: Signature |
| 5. Base64 Encoding | Encode the binary signature for XML embedding. | matlab.net.base64encode |
| 6. SOAP Message Posting | Embed the signature in a SOAP envelope and POST securely. | webwrite with certificate options |
Conclusion
This guide has walked through the detailed workflow of using MATLAB for generating and sending a digital signature encapsulated in a SOAP message. We started by creating a DOM representation of the provided XML data and then generating a canonicalized representation to meet standards required for digital signing. With the help of MATLAB’s native XML capabilities and Java’s robust cryptographic libraries, we computed a SHA-256 digest and RSA-based digital signature. After base64 encoding the signature, we meticulously integrated it into a SOAP message structure, ensuring that the signature follows established XML Digital Signature standards.
Finally, by employing MATLAB’s secure web functions and using a .p12 certificate for authentication, the SOAP message can be safely transmitted over HTTPS. This comprehensive approach is essential for applications that require high-integrity communications between secure web services. The methods presented here illustrate a practical means to use MATLAB in educational, research, or production environments where advanced XML processing and digital security are requisites.
References
- Document Object Model - MATLAB Help
- Exporting to XML Documents - MATLAB Help
- webwrite - MATLAB Help
-
XML Canonicalization with Comments - W3C
Recommended Queries
Last updated February 24, 2025