<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bandaru Srikanth on Medium]]></title>
        <description><![CDATA[Stories by Bandaru Srikanth on Medium]]></description>
        <link>https://medium.com/@srikanthbandaru79?source=rss-d81737462528------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h6WVHJ8jlkFq1Q-8irTV2g.webp</url>
            <title>Stories by Bandaru Srikanth on Medium</title>
            <link>https://medium.com/@srikanthbandaru79?source=rss-d81737462528------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:27:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srikanthbandaru79/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Definitive Guide to Peppol AS4 SOAP Security: End-to-End Signing & Encryption]]></title>
            <link>https://medium.com/@srikanthbandaru79/the-definitive-guide-to-peppol-as4-soap-security-end-to-end-signing-encryption-b03276c9f97a?source=rss-d81737462528------2</link>
            <guid isPermaLink="false">https://medium.com/p/b03276c9f97a</guid>
            <category><![CDATA[peppol-e-invoicing]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[4s-as]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Bandaru Srikanth]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 16:06:10 GMT</pubDate>
            <atom:updated>2026-06-07T16:06:10.049Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a custom AS4 sender for the Peppol network is a rite of passage for enterprise backend engineers. Unlike standard web APIs that rely purely on transport-layer security (HTTPS), AS4 mandates <strong>Message-Level Security</strong>. This means your payload is cryptographically secured before it even touches the network wire, ensuring complete non-repudiation and end-to-end confidentiality.</p><p>If you don’t orchestrate your cryptographic steps in the exact sequence mandated by the Peppol AS4 profile, receiving Access Points will aggressively reject your network connections.</p><p>Here is the complete engineering blueprint to implementing the signing and encryption pipeline flawlessly.</p><h3>1. The Key Landscape: Who Owns Which Key?</h3><p>Before writing a single line of code, you must understand your cryptographic inventory. An AS4 handshake requires two distinct X.509 digital certificates.</p><h4>The Sender’s Private Key (Your Certificate)</h4><ul><li><strong>What it is:</strong> A certificate issued by an authorized Peppol PKI (Certificate Authority), typically an AS4 AP certificate. You hold the private key securely in your KeyStore (PKCS12 or JKS).</li><li><strong>What it is used for:</strong> <strong>Signing</strong>. You use your private key to generate the digital signatures for the message. This proves to the receiver that <em>you</em> sent the message and that it hasn’t been altered.</li></ul><h4>The Receiver’s Public Key (Their Certificate)</h4><ul><li><strong>What it is:</strong> The public certificate belonging to the target receiving Access Point. In production, you dynamically lookup and extract this certificate from the Peppol Service Metadata Publisher (SMP) using the receiver’s Peppol ID.</li><li><strong>What it is used for:</strong> <strong>Encryption</strong>. You use their public key to encrypt the ephemeral session key that scrambles the business document. This ensures that <em>only</em> the intended receiver can decrypt the payload.</li></ul><h3>2. The Blueprint: What to Sign and What to Encrypt?</h3><p>The Peppol AS4 Profile enforces a strict <strong>“Sign-Then-Encrypt”</strong> specification. Leaving a required component unsigned or unencrypted will break protocol compliance.</p><h4>What Must Be Signed?</h4><p>You must calculate digital signatures (using RSA-SHA256) for three distinct structural components of your message:</p><ol><li><strong>The SOAP Body:</strong> The root container of your SOAP message.</li><li><strong>The ebMS3 Messaging Header:</strong> The XML metadata block containing your Peppol routing info (Service, Action, From/To parties, Message ID).</li><li><strong>The Attachment(s):</strong> The actual compressed business invoice (the raw business payload) attached as a MIME component.</li></ol><h4>What Must Be Encrypted?</h4><p>You must encrypt (using AES-128-GCM or AES-256-GCM) only one specific thing:</p><ol><li><strong>The Attachment(s):</strong> The business document. The core SOAP envelope itself (including the ebMS3 routing headers) <strong>must remain unencrypted text</strong> so that intermediate network routers and firewalls can read the routing headers to direct the traffic.</li></ol><h3>3. The End-to-End Security Flow Architecture</h3><p>Here is the exact runtime lifecycle your code pipeline must execute in sequence.</p><h4>Step 1: Document Aggregation &amp; DOM Indexing</h4><p>You construct your raw SOAP envelope and build your ebMS3 &lt;eb3:Messaging&gt; metadata.</p><ul><li><strong>The Critical Move:</strong> Before passing the document to your security framework, you must find your Messaging header tag and programmatically flag its ID via setIdAttributeNS(). If you miss this step, your signature engine will throw a WSSecurityException because it won&#39;t be able to locate the element to hash it.</li></ul><h4>Step 2: The Signing Phase (Using Your Private Key)</h4><p>WSS4J scans the document and computes cryptographic digests:</p><ol><li>It hashes the text of your SOAPHeader elements and the SOAPBody.</li><li>It streams your external invoice attachment file and hashes its binary data blocks.</li><li>It bundles these hashes into a &lt;ds:Signature&gt; block, signs the block with your <strong>Sender Private Key</strong>, and appends your public certificate chain into a &lt;wsse:BinarySecurityToken&gt; inside the security header.</li></ol><h4>Step 3: The Encryption Phase (Using Their Public Key)</h4><p>With the signatures securely locked in place, the engine initiates data wrapping:</p><ol><li>WSS4J generates a random, highly secure, one-time symmetric session key (a secret key).</li><li>It encrypts your raw binary attachment stream with this secret key, morphing it into raw ciphertext blocks.</li><li>It encrypts that temporary secret key itself using the <strong>Receiver’s Public Key</strong>. This wrapped key is placed into a &lt;xenc:EncryptedKey&gt; element block inside the &lt;wsse:Security&gt; header.</li></ol><h4>Step 4: The Reactive Callback Harvest</h4><p>Because streaming security frameworks operate on asynchronous output streams, you must use a custom CallbackHandler to intercept the freshly generated encrypted attachment chunks. You capture the AttachmentResultCallback stream and pass it down to your transport packing layer.</p><h4>Step 5: Compliant MIME Boundary Packaging</h4><p>Finally, you feed the secured components into a JavaMail multi-part builder. You enforce base64 transfer encoding on the encrypted attachment part to prevent internet proxies from corrupting your ciphertext blocks, and you explicitly set the HTTP Content-Type header’s start parameter to target your primary SOAP envelope root.</p><h3>Architectural Engineering Summary</h3><p>Implementing a Peppol AS4 Sender requires strict adherence to cryptographic boundaries. By keeping your security pipeline completely separated from your transport packaging layer — treating input elements as configuration blueprints and relying entirely on the streaming tokens and ciphertext payloads pushed back by your security engine — you eliminate silent encryption leaks and build an incredibly stable, compliant, and rock-solid B2B communications gateway.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b03276c9f97a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Base64 and the “start” Parameter: Shipping AS4 Encrypted Streams via JavaMail MIME]]></title>
            <link>https://medium.com/@srikanthbandaru79/base64-and-the-start-parameter-shipping-as4-encrypted-streams-via-javamail-mime-8dc7d970dc4e?source=rss-d81737462528------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dc7d970dc4e</guid>
            <category><![CDATA[4s-as]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[peppol-e-invoicing]]></category>
            <category><![CDATA[web-services]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Bandaru Srikanth]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 09:41:56 GMT</pubDate>
            <atom:updated>2026-06-05T09:41:56.144Z</atom:updated>
            <content:encoded><![CDATA[<p>You have finally done it: you successfully imported your metadata, resolved your DOM ID index errors, and verified that your Apache WSS4J engine successfully generated encrypted binary ciphertext chunks. You bundle everything into an HTTP payload, transmit it over the web, and wait. Instantly, the receiving remote Access Point drops the connection and returns unhelpful, low-level decryption or parsing failure responses.</p><p>When you test it locally, everything matches perfectly. Why does it corrupt the moment it traverses the internet wire? The answer lies in the subtle formatting pitfalls of packaging multi-part internet mail extensions (MIME) for high-entropy binary transport.</p><h3>The Two Wire Pitfalls of Encrypted B2B Deliveries</h3><p>When an AS4 message is prepared for wire transmission, it must be bundled into a multipart/related format. This acts as a single shipping container holding two distinct packages: your public SOAP XML envelope, and your encrypted business document attachment. If your transport configuration leaves out specific packaging headers, web infrastructure will silently break the message in two specific ways.</p><h3>1. Raw Ciphertext Mangling</h3><p>Encryption transforms plain text into completely scrambled binary streams (application/octet-stream). Standard web firewalls, routers, and proxies expect text-friendly characters. If you push raw binary streams over a basic HTTP post line, downstream network appliances will attempt to format-normalize line breaks, null terminators, or character spaces—permanently altering your bytes and destroying your cryptographic hashes.</p><h3>2. The Multi-part Entry Point Guessing Game</h3><p>A MIME multipart message contains distinct split boundaries. When a receiving server intercepts the incoming request, it gets a collection of parts. If you don’t explicitly tell its low-level HTTP parsing engine which part is the root control center, it will often default to reading the first physical block or throw an unhandled parsing crash.</p><h3>Forcing WS-I Attachments Profile Compliance</h3><p>To ship secure data cleanly over standard internet protocols without corruption, your transport-layer builder (typically using JavaMail or Jakarta Mail) must enforce strict <a href="https://ws-i.org/Profiles/AttachmentsProfile-1.0.html"><strong>WS-I Attachments Profile 1.0</strong></a> configurations.</p><p>Rather than relying on proprietary messaging contexts or custom tracking properties, you can handle this directly inside a clean, transport-focused JavaMail utility method using standard input streams.</p><pre>package com.openutils.xml.transport;<br>import javax.activation.DataHandler;<br>import javax.mail.internet.MimeBodyPart;<br>import javax.mail.internet.MimeMultipart;<br>import javax.mail.util.ByteArrayDataSource;<br>/**<br> * A generic transport payload factory responsible for packaging secure <br> * binary artifacts into WS-I compliant MIME envelopes.<br> */<br>public class MimePackageBuilder {<br>    /**<br>     * Packages a signed SOAP envelope and an encrypted payload into a <br>     * valid, network-safe multipart transport container.<br>     *<br>     * @param multipart       The target container to assemble.<br>     * @param encryptedBytes  The raw ciphertext bytes generated by the security pipeline.<br>     * @param secureId        The unique Content-ID assigned to the attachment part.<br>     * @param boundaryString  The unique delimiter marking the MIME parts.<br>     * @return The formatted HTTP Content-Type header string required for transmission.<br>     * @throws IllegalArgumentException If any configuration parameter is null.<br>     */<br>    public String buildMimePayload(MimeMultipart multipart, byte[] encryptedBytes, String secureId, String boundaryString) throws Exception {<br>        if (multipart == null || encryptedBytes == null || secureId == null || boundaryString == null) {<br>            throw new IllegalArgumentException(&quot;MIME configurations and byte payloads must not be null.&quot;);<br>        }<br>        // Phase 1: Enforce Base64 on Ciphertext Attachments to protect against network mangling<br>        MimeBodyPart attachmentPart = new MimeBodyPart();<br>        attachmentPart.setHeader(&quot;Content-ID&quot;, &quot;&lt;&quot; + secureId + &quot;&gt;&quot;);<br>        attachmentPart.setHeader(&quot;Content-Transfer-Encoding&quot;, &quot;base64&quot;); // THE SAFE GUARD<br>        <br>        attachmentPart.setDataHandler(new DataHandler(<br>            new ByteArrayDataSource(encryptedBytes, &quot;application/octet-stream&quot;)<br>        ));<br>        multipart.addBodyPart(attachmentPart);<br>        // Phase 2: Explicitly construct the &#39;start&#39; parameter string to map the entry node<br>        String formattedContentType = &quot;multipart/related; type=\&quot;application/soap+xml\&quot;; &quot;<br>                                    + &quot;start=\&quot;&lt;root&gt;\&quot;; &quot; // THE NAVIGATOR<br>                                    + &quot;boundary=\&quot;&quot; + boundaryString + &quot;\&quot;; &quot;<br>                                    + &quot;start-info=\&quot;application/soap+xml\&quot;&quot;;<br>        return formattedContentType;<br>    }<br>}</pre><h3>Demystifying the Core Safeguards</h3><p>Let’s look at exactly how these two precise header declarations protect your transmission pipeline from breaking during public internet transport:</p><h3>Content-Transfer-Encoding: base64</h3><p>This wraps your high-entropy, randomized encryption blocks inside safe, completely predictable alphanumeric text characters. By re-encoding raw binary into standard ASCII blocks, network proxies, content-filtering firewalls, and legacy web routing components can inspect and forward the data stream without attempting to “correct” line breaks, normalize trailing whitespaces, or drop null terminators. Not a single bit of your ciphertext is distorted.start=&quot;&lt;root&gt;&quot;</p><p>This acts as an explicit navigation command line directed right at the receiving server’s HTTP parsing engine:</p><blockquote>“Do not try to interpret or process the raw binary chunk yet. Locate the multipart boundary matching Content-ID <em>&lt;root&gt;</em>, pull down the signed SOAP XML header first, and read our ebMS3 metadata roadmap.&quot;</blockquote><p>By establishing this clear layout hierarchy, the remote Access Point instantly knows how to route the message internally. It processes the security header tokens, extracts the key configurations, and successfully decrypts your base64-encoded attachment stream without a single processing collision.</p><h3>Architectural Engineering Takeaway</h3><p>When building enterprise e-delivery systems like a Peppol AS4 Sender, remember that code-level encryption correctness is only half the battle. Your payload must survive the harsh formatting rules of real-world internet networks.</p><p>By wrapping raw cryptographic bytes in a base64 transfer encoding layout and providing an unambiguous start entry pointer, you guarantee complete compliance with WS-I transport specifications. This defensive design completely eliminates mysterious parsing failures and ensures reliable, automated web handshakes across any standard business document network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dc7d970dc4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing WRONG_DOCUMENT_ERR When Customizing SOAP Headers in Java]]></title>
            <link>https://medium.com/@srikanthbandaru79/fixing-wrong-document-err-when-customizing-soap-headers-in-java-750ebb4b1bdc?source=rss-d81737462528------2</link>
            <guid isPermaLink="false">https://medium.com/p/750ebb4b1bdc</guid>
            <category><![CDATA[4s-as]]></category>
            <category><![CDATA[web-services]]></category>
            <category><![CDATA[peppol-e-invoicing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Bandaru Srikanth]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 15:02:37 GMT</pubDate>
            <atom:updated>2026-06-04T15:02:37.224Z</atom:updated>
            <content:encoded><![CDATA[<p>When engineering highly complex B2B messaging engines like a custom <strong>Peppol AS4 Sender</strong>, your pipeline will inevitably handle different sections of your outbound message independently. A common pattern is to construct your routing metadata blocks (such as ebMS3 headers) inside isolated factory classes or template builders before attempting to merge them into your primary outbound SAAJ SOAP container.</p><p>If you attempt to link these two independently constructed XML sections together natively using standard DOM additions:</p><pre>// Naive attachment of external components<br>soapMessage.getSOAPHeader().appendChild(myMessagingElement);</pre><p>Your execution runtime will crash instantly with a jarring, low-level W3C structural exception:</p><pre>org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.</pre><p>This error is incredibly frustrating for integration engineers. The external XML elements are perfectly well-formed, valid according to the schema, and completely clear of typos. Why does the Java Virtual Machine care <em>where</em> these nodes were built if the layout perfectly aligns?</p><p>The answer lies in understanding Java’s strict, underlying document ownership boundaries.</p><h3>The Sovereign Document Boundary</h3><p>In the standard Java W3C DOM architecture, XML nodes do not exist as free-floating, detached objects in memory. Every single element, attribute, processing instruction, and text block is permanently owned by the specific factory instance (org.w3c.dom.Document) that originally birthed it.</p><p>Even if you are just constructing simple text properties using a basic utility DocumentBuilder instance, those nodes are bound for life to that temporary builder&#39;s distinct memory document tree.</p><p>The SAAJ framework (javax.xml.soap.SOAPMessage) manages its own independent internal implementation factory context. When you attempt to execute a simple appendChild() using a node birthed by an entirely separate document environment, the underlying DOM manager flags an structural integrity violation. It blocks the operation directly to prevent cross-document contamination.</p><p>Think of it like trying to graft a branch from one live tree directly onto another without a formal cultivation process; the host tree rejects the foreign tissue immediately.</p><h3>💡 The Solution: Inline Document Adoption</h3><p>To move a custom element safely across document boundaries without crashing, you must perform a formal document adoption. You accomplish this by asking the target host document context to deep-clone the foreign structure and take full legal ownership of its nodes directly.</p><p>Instead of introducing external utility frameworks or custom wrapper classes, you can execute this defensive migration inline with just two standard lines of native JDK code.</p><p>Here is how to safely wire up your outbound message manipulation logic to cross this barrier seamlessly:</p><pre>// 1. Fetch the underlying owner document that governs the SAAJ SOAP universe<br>Document saajDocument = soapMessage.getSOAPHeader().getOwnerDocument();<br><br>// 2. THE CRITICAL FIX: Deep-clone and adopt the foreign node into the SAAJ universe<br>// Setting the second parameter to &#39;true&#39; ensures a deep-recursive copy of all child tags<br>Node imported = saajDocument.importNode(myMessagingElement, true);<br><br>// 3. Ownership is now perfectly aligned; this call succeeds flawlessly!<br>soapMessage.getSOAPHeader().appendChild(imported);</pre><h3>Why This Works</h3><p>By leveraging saajDocument.importNode(myMessagingElement, true), you decouple the element from its original factory document context. The JVM allocates a new segment in memory under the target SAAJ document&#39;s namespace pool, recursively clones all child metadata elements, and re-maps the entire hierarchy&#39;s owner-document reference pointer.</p><p>Because the resulting imported node is now legally owned by the SOAP document context, the subsequent appendChild() operation clears validation checks and structures your headers flawlessly for the network wire.</p><h3>Architectural Takeaway</h3><p>When writing low-level messaging pipelines, remember that structural correctness is only half the battle. Java’s XML manipulation layer treats document boundaries as hard isolation walls.</p><p>Whenever you are aggregating XML fragments from different microservices, templates, or external factories, always pass them through an explicit <strong>Document Adoption Phase</strong> before grafting them onto your core transport structures. This simple defensive step eliminates runtime DOM exceptions entirely and maintains an immaculate, predictable thread model across your outbound gateway.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=750ebb4b1bdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Streaming Trap: Why Your Outbound AS4 Attachments Are Leaving Unencrypted]]></title>
            <link>https://medium.com/@srikanthbandaru79/the-streaming-trap-why-your-outbound-as4-attachments-are-leaving-unencrypted-2c70aad82bcf?source=rss-d81737462528------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c70aad82bcf</guid>
            <category><![CDATA[wss4j]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[4s-as]]></category>
            <category><![CDATA[peppol-e-invoicing]]></category>
            <dc:creator><![CDATA[Bandaru Srikanth]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 05:59:48 GMT</pubDate>
            <atom:updated>2026-06-04T05:59:48.700Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are currently building a custom <strong>Peppol AS4</strong> or <strong>ebMS3</strong> messaging gateway from scratch in Java, let me warn you about a silent, devastating architectural trap that has cost enterprise integration developers days of soul-crushing debugging.</p><p>You write clean, modular logic to compress your business’s outbound XML invoices. You bundle those streams into standard SAAJ SOAPMessage payload parts. You instantiate the high-performance <strong>Apache WSS4J Streaming API (StAX)</strong> pipeline to sign and encrypt the message data. You execute your pipeline, and the runtime console returns zero exceptions. Printing out your outbound SOAP envelope XML reveals a beautiful, cryptographically pristine &lt;wsse:Security&gt; header containing valid digital signatures, token references, and key configurations.</p><p>But when you sniff the final network packets hitting the HTTP wire transport layer, your heart drops: <strong>the payload attachment is flying across the public internet in completely unencrypted plaintext or raw GZIP format.</strong> The cryptography never touched it.</p><p>Even worse, your compilation checks cleared, and your code failed completely silently. Let’s break down why this optical illusion occurs inside Java memory models and look at the explicit decoupled architecture required to fix it.</p><h3>The Mental Model Illusion: SAAJ vs. WSS4J StAX Pipelines</h3><p>Most developers approach Java XML handling with a stateful mental model. When passing an object instance like a SAAJ SOAPMessage or its initial AttachmentPart collections into a security utility, the procedural assumption is:</p><blockquote>“The framework interceptor will act as an in-place mutator, altering the byte payload data stored inside my original message object.”</blockquote><p><strong>With a streaming, event-driven security architecture (StAX), it simply does not work that way.</strong></p><p>WSS4J’s streaming engine (OutboundWSSec) functions as a non-mutating pipeline processor, not an in-place object modifier. It opens a transient, unidirectional read-stream over your original XML and attachment elements, calculates cryptographic hashes, generates ephemeral symmetric keys on the fly, and constructs an entirely distinct output stream containing the randomized ciphertext bytes (application/octet-stream).</p><p>If you assemble your final outbound multi-part internet mail extension (MIME) message by pulling attachment handles back out of your initial raw input SAAJ object containers, you will inadvertently transmit your unencrypted origin data every single time.</p><h3>The Missing Link: Intercepting the Asynchronous Callback</h3><p>To bridge the operational gap between the non-mutating encryption engine and your final wire transport layer, you must design your application around a reactive push-and-pull callback workflow.</p><p>When WSS4J processes attachment elements sequentially to minimize your JVM heap signature, it never attempts to save those encrypted results back into the primary DOM document. Instead, the framework emits an asynchronous AttachmentResultCallback event containing the newly created ciphertext data stream.</p><p>If your message processing framework does not actively intercept this callback and harvest the generated ciphertext stream, that secured dataset evaporates into the ether the moment the execution context updates.</p><pre>[Original SAAJ Attachment] <br>       │<br>       ▼<br> WSS4J StAX Engine Processes Stream<br>       │<br>       ▼<br>[Encrypted Ciphertext Stream Generated]<br>       │<br>       ▼<br> WSS4J fires AttachmentResultCallback ──► [Your Callback Handler Captures It]<br>                                                               │<br>   ┌───────────────────────────────────────────────────────────┘<br>   ▼<br>[Stored in a separate Secured Map] ──► Used to build final MimeMultipart!</pre><h3>🛠️ The Solution: The Secure Interceptor and MIME Builder Utilities</h3><p>To resolve this silent vulnerability permanently, you need to decouple your application’s input structures from its output transport containers. The pipeline must be split into a two-part decoupled utility structure.</p><h3>Phase 1: Harvesting the Ciphertext with a Custom Callback Interceptor</h3><p>Your security initialization pipeline requires a dedicated, standard CallbackHandler that actively listens for cryptographic output events. When WSS4J pushes a successful ciphertext transformation, the handler must intercept the byte stream and cache it into an independent runtime map:</p><pre>package com.openutils.xml.security;<br>import org.apache.wss4j.common.ext.Attachment;<br>import org.apache.wss4j.common.ext.AttachmentRequestCallback;<br>import org.apache.wss4j.common.ext.AttachmentResultCallback;<br>import javax.security.auth.callback.Callback;<br>import javax.security.auth.callback.CallbackHandler;<br>import javax.security.auth.callback.UnsupportedCallbackException;<br>import java.io.IOException;<br>import java.util.Collections;<br>import java.util.HashMap;<br>import java.util.Map;<br>/**<br> * A generic, independent CallbackHandler built to harvest encrypted <br> * streams emitted by streaming cryptographic engines.<br> */<br>public class SecurityAttachmentCallbackHandler implements CallbackHandler {<br>    // The single source of truth for secure outbound payload streams<br>    private final Map&lt;String, Attachment&gt; securedStreamMap = new HashMap&lt;&gt;();<br>    @Override<br>    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {<br>        for (Callback callback : callbacks) {<br>            if (callback instanceof AttachmentRequestCallback) {<br>                // Supply the raw payload stream to the security engine<br>                AttachmentRequestCallback request = (AttachmentRequestCallback) callback;<br>                String id = request.getAttachmentId();<br>                if (id != null &amp;&amp; securedStreamMap.containsKey(id)) {<br>                    request.setAttachments(Collections.singletonList(securedStreamMap.get(id)));<br>                }<br>            } else if (callback instanceof AttachmentResultCallback) {<br>                // THE CRITICAL FIX: Intercept and store the newly generated encrypted stream<br>                AttachmentResultCallback result = (AttachmentResultCallback) callback;<br>                Attachment securedArtifact = result.getAttachment();<br>                if (securedArtifact != null) {<br>                    securedStreamMap.put(securedArtifact.getId(), securedArtifact);<br>                }<br>            }<br>        }<br>    }<br>    /**<br>     * Exposes the safely compiled map of secure cryptographic streams.<br>     */<br>    public Map&lt;String, Attachment&gt; getSecuredAttachments() {<br>        return this.securedStreamMap;<br>    }<br>    <br>    /**<br>     * Seed the initial map with the raw source attachment prior to processing.<br>     */<br>    public void registerInitialAttachment(String id, Attachment rawAttachment) {<br>        this.securedStreamMap.put(id, rawAttachment);<br>    }<br>}</pre><h3>Phase 2: Assembling the Multi-part Wire Message from the Secured Map</h3><p>Once the encryption processor completes its streaming sweep, your transport utility — leveraging standard JavaMail packages — must explicitly bypass the original message context. You must build your outbound multipart boundaries exclusively from the stream cache populated by the callback handler:</p><pre>package com.openutils.xml.transport;<br>import org.apache.wss4j.common.ext.Attachment;<br>import javax.activation.DataHandler;<br>import javax.mail.internet.MimeBodyPart;<br>import javax.mail.internet.MimeMultipart;<br>import javax.mail.util.ByteArrayDataSource;<br>import java.io.ByteArrayOutputStream;<br>import java.io.InputStream;<br>import java.util.Map;<br>/**<br> * A generic transport companion utility that serializes secure attachments <br> * into production-ready multi-part wire payloads.<br> */<br>public class SecureMimePayloadBuilder {<br>    /**<br>     * Loops over the collected cryptographic artifacts to assemble wire-safe MIME parts.<br>     */<br>    public void compileMultipartPayload(MimeMultipart multipartContainer, Map&lt;String, Attachment&gt; secureMap) throws Exception {<br>        if (secureMap == null || secureMap.isEmpty()) {<br>            return;<br>        }<br>        for (Map.Entry&lt;String, Attachment&gt; entry : secureMap.entrySet()) {<br>            String contentId = entry.getKey();<br>            Attachment cryptographicAttachment = entry.getValue();<br>            MimeBodyPart wirePart = new MimeBodyPart();<br>            <br>            // Set required B2B routing transport headers<br>            wirePart.setHeader(&quot;Content-ID&quot;, &quot;&lt;&quot; + contentId + &quot;&gt;&quot;);<br>            wirePart.setHeader(&quot;Content-Transfer-Encoding&quot;, &quot;base64&quot;);<br>            wirePart.setHeader(&quot;Content-Disposition&quot;, &quot;attachment; filename=\&quot;payload.xml\&quot;&quot;);<br>            // Consume the streaming ciphertext from the callback source<br>            byte[] ciphertextBytes;<br>            try (InputStream input = cryptographicAttachment.getSourceStream();<br>                 ByteArrayOutputStream output = new ByteArrayOutputStream()) {<br>                byte[] buffer = new byte[4096];<br>                int bytesRead;<br>                while ((bytesRead = input.read(buffer)) != -1) {<br>                    output.write(buffer, 0, bytesRead);<br>                }<br>                ciphertextBytes = output.toByteArray();<br>            }<br>            // Encapsulate the raw ciphertext blocks into a safe transport handler<br>            wirePart.setDataHandler(new DataHandler(<br>                new ByteArrayDataSource(ciphertextBytes, cryptographicAttachment.getMimeType())<br>            ));<br>            multipartContainer.addBodyPart(wirePart);<br>        }<br>    }<br>}</pre><h3>Architectural Engineering Takeaway</h3><p>Silent infrastructure errors represent the single most dangerous class of software engineering bugs because compilation correctness and local string logging hide an explicit violation of technical security specifications.</p><p>When working with high-performance, low-memory streaming utilities like Apache WSS4J StAX, establish a strict architectural boundary: <strong>The output stream is your only source of truth.</strong> Treat your initial structural payload instances purely as configuration maps, and construct your final outbound transport packages exclusively from the encrypted artifacts returned by your callback handlers. Your production transport layer audits will thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c70aad82bcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why WSS4J Can’t Find Your SOAP Headers: The Critical DOM Step You’re Missing]]></title>
            <link>https://medium.com/@srikanthbandaru79/why-wss4j-cant-find-your-soap-headers-the-critical-dom-step-you-re-missing-8e1c5b0b383f?source=rss-d81737462528------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e1c5b0b383f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[peppol-e-invoicing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[peppol]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Bandaru Srikanth]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 13:24:08 GMT</pubDate>
            <atom:updated>2026-06-04T06:02:17.091Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have ever tried to implement a custom digital signature pipeline using <strong>Apache WSS4J</strong> or standard Java XML Security utilities within a Peppol AS4 gateway, you have likely run straight into this infuriating runtime wall:</p><pre>org.apache.wss4j.common.ext.WSSecurityException: No message with ID &quot;msgHeader-XYZ&quot; found in document</pre><p>When this happens, your first instinct is to pause the application and print the outbound XML string to the console. You stare at the raw text, and everything looks structurally flawless. The target element explicitly contains the exact matching attribute string: wsu:Id=&quot;msgHeader-XYZ&quot;. The namespaces are correct, the configuration map is spotless, and yet the security engine aggressively insists that the element does not exist.</p><p>It feels like a phantom bug. However, the root cause is a fundamental disconnect between how we look at XML as a text string versus how the Java Virtual Machine (JVM) indexes elements in memory.</p><h3>The Illusion of Textual Attributes</h3><p>As software engineers, we often fall into the trap of viewing XML simply as a serialized text string structured by angle brackets. We assume that if we programmatically add an attribute named wsu:Id to an XML element, the underlying document context inherently understands that the element now possesses that unique identifier.</p><p><strong>To the JVM’s memory-resident Document Object Model (DOM) tree, an attribute is just passive text unless it is formally indexed.</strong></p><p>When an XML digital signature framework like WSS4J encounters a security rule instructing it to sign a specific part of a message — such as an ebMS3 routing header — it parses the signature reference path. If that reference tells the engine to locate an anchor hash like #msgHeader-XYZ, the engine does not run a brute-force string search or an expensive XPath scan through the raw document text. Instead, it relies directly on the standard, high-performance W3C DOM lookup method:</p><pre>document.getElementById(&quot;msgHeader-XYZ&quot;);</pre><p>Here is the catch: even if an attribute is textually named wsu:Id or Id in the serialized output, the DOM engine’s internal registry lookup will return null unless that specific attribute has been programmatically flagged as an <strong>ID-type</strong> attribute.</p><p>Without that explicit registration step, the underlying memory index treats your custom string as a generic, unindexed attribute node. To the internal lookup tree, your identifier is a ghost.</p><h3>💡 The Solution: Bridging the Wire vs. Memory Disconnect</h3><p>To ensure a dynamically generated XML element is discoverable by cryptographic pipelines, your codebase must explicitly bridge two entirely separate worlds: <strong>The Wire World (Serialized Text)</strong> and <strong>The Memory World (The JVM Lookup Registry)</strong>. This requires a strict, multi-phase execution utility.</p><p>Below is a clean, fully generic implementation pattern using the standard Java W3C DOM API to handle this dual-action registration safely, completely decoupled from any proprietary enterprise domain configurations:</p><pre>package com.openutils.xml.security;<br>import org.w3c.dom.Document;<br>import org.w3c.dom.Element;<br>import org.w3c.dom.NodeList;<br>/**<br> * A generic utility class responsible for locating elements dynamically and <br> * registering cryptographic anchor identifiers inside the JVM&#39;s DOM registry.<br> * * This ensures that streaming XML processing frameworks (such as Apache WSS4J StAX) <br> * can seamlessly resolve document elements via standard lookup maps.<br> */<br>public class DomAnchorConfigurator {<br>    // Globally recognized WS-Security Utility Namespace<br>    public static final String SECURITY_UTIL_NS = <br>        &quot;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd&quot;;<br>    /**<br>     * Locates an XML element by its namespace URI and local tag name, assigns a qualified <br>     * identifier attribute, and forces the DOM registry to index it as a strict entity ID.<br>     *<br>     * @param domDocument      The active XML Document tree.<br>     * @param targetNamespace  The strict Namespace URI of the element to find (e.g., ebMS3 core URI).<br>     * @param localTagName     The raw XML tag name (e.g., &quot;Messaging&quot; or &quot;Body&quot;).<br>     * @param uniqueIdentifier The string identifier to assign (e.g., a dynamically generated UUID token).<br>     * @return The updated Element if successfully indexed, or null if the element was not found.<br>     * @throws IllegalArgumentException If any required input parameter is null.<br>     */<br>    public Element locateAndIndexElement(Document domDocument, String targetNamespace, String localTagName, String uniqueIdentifier) {<br>        if (domDocument == null || targetNamespace == null || localTagName == null || uniqueIdentifier == null) {<br>            throw new IllegalArgumentException(&quot;All tracking parameters and the DOM document must not be null.&quot;);<br>        }<br>        // Phase 1: Namespace-aware element lookup<br>        // Using getElementsByTagNameNS ensures we find the node regardless of arbitrary text prefixes (e.g., eb3 vs eb)<br>        NodeList nodeList = domDocument.getElementsByTagNameNS(targetNamespace, localTagName);<br>        if (nodeList == null || nodeList.getLength() == 0) {<br>            // Element not present in this specific document instance; return null to let handlers skip safely<br>            return null;<br>        }<br>        // Extract the target element instance from the node map<br>        Element targetElement = (Element) nodeList.item(0);<br>        // Phase 2: Textual Declaration (The Wire World)<br>        targetElement.setAttributeNS(<br>            SECURITY_UTIL_NS, <br>            &quot;wsu:Id&quot;, <br>            uniqueIdentifier<br>        );<br>        // Phase 3: Programmatic Indexing (The Memory World)<br>        targetElement.setIdAttributeNS(<br>            SECURITY_UTIL_NS, <br>            &quot;Id&quot;, <br>            true<br>        );<br>        return targetElement;<br>    }<br>}</pre><h3>Breaking Down the Mechanics: setAttributeNS vs setIdAttributeNS</h3><p>Let’s look at exactly what happens inside the JVM’s memory heap during Phase 2 and Phase 3, and why omitting either method breaks the transmission pipeline.</p><h3>1. Phase 2: setAttributeNS (Textual Declaration)</h3><ul><li><strong>The Action:</strong> This method physically injects a namespace-qualified attribute key-value pair into the raw XML element node.</li><li><strong>The “Wire” Impact:</strong> If you serialize your DOM document into a string right after this line executes, the characters literally appear on your screen:</li></ul><pre>&lt;eb3:Messaging wsu:Id=&quot;msgHeader-XYZ&quot;&gt;</pre><ul><li><strong>Why it matters:</strong> This satisfies structural <strong>wire compliance</strong>. When the payload travels across the network to the receiving Access Point, their system relies on this text string to locate and verify the signature on their side.</li><li><strong>The Trap:</strong> In the sender’s local JVM memory, the DOM engine treats this as a generic text property — no different than a custom label like color=&quot;blue&quot;. It has no idea this string is meant to be a unique lookup key, meaning the document&#39;s internal ID index remains completely empty.</li></ul><h3>2. Phase 3: setIdAttributeNS (Programmatic Indexing)</h3><ul><li><strong>The Action:</strong> This method changes nothing about how the XML text looks when sent over the network. Instead, it alters the <em>internal memory metadata</em> of the Java XML Document structure.</li><li><strong>The “Memory” Impact:</strong> By passing true as the final parameter, you instruct the internal architecture of the Java XML Document:</li></ul><blockquote>“Scan the attribute named ‘Id’ within the security utility namespace on this element. Take its string value (‘msgHeader-XYZ’) and explicitly register it inside your internal fast-lookup identifier map.”</blockquote><ul><li><strong>Why it matters:</strong> This forces the DOM tree to explicitly link that string value directly to this specific Java element object instance inside the JVM’s background memory registry.</li></ul><h3>How This Helps Your Cryptographic Pipeline</h3><p>When your application hands this document over to a security framework like Apache WSS4J, the processing engine encounters your signing configuration and internally invokes:</p><pre>Element target = domDocument.getElementById(&quot;msgHeader-XYZ&quot;);</pre><ul><li><strong>Without Phase 3 (</strong>setIdAttributeNS<strong>):</strong> The lookup fails. WSS4J checks the fast-lookup map, finds nothing registered under that string, returns null, and instantly panics with a WSSecurityException.</li><li><strong>With Phase 3 (</strong>setIdAttributeNS<strong>):</strong> The lookup succeeds instantly. WSS4J pulls the exact object pointer from memory, tracks down the node, calculates the canonicalized SHA-256 hashes, and embeds the digital signature seamlessly.</li></ul><p>By running both methods, you satisfy both environments: setAttributeNS puts the ID on the wire for the receiver, and setIdAttributeNS registers the ID in memory for your local security engine.</p><h3>Architectural Takeaway</h3><p>When writing low-level messaging frameworks or protocol integrations (such as AS4 or custom SOAP engines), it is vital to remember that <strong>textual correctness does not equal memory readiness</strong>.</p><p>Whenever your application modifies or generates XML structural boundaries that subsequent security interceptors need to sign or encrypt, you must explicitly manage the lifecycle of your DOM indices.</p><p>Adding that single indexing method guarantees that your elements remain perfectly visible to your cryptographic pipelines, eliminating phantom lookup errors and ensuring seamless automated handshakes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e1c5b0b383f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>