Testing Java XML signatures and encryption with sample data
Java services often exchange XML whose integrity, origin, and confidentiality all matter. An XML signature can prove that a document or selected content has not changed and can identify the key used to sign it. XML encryption hides selected elements or their text while preserving a decryptable XML structure. A Java test suite therefore needs separate expectations for each mechanism, plus scenarios that combine them. Treating both as “encrypt or sign” checks misses the ordering, canonicalisation, and key-management rules that make these documents trustworthy.
The most useful fixtures resemble real business payloads without containing real customer information. They should be deterministic enough to diagnose a failure, varied enough to expose parser and namespace bugs, and safe to commit or generate inside a build. That balance is particularly important for teams in Sydney and Melbourne, where shared Java services may process Australian customer records while operating across systems with different privacy, retention, and release requirements.
Set the security contract
Start by writing the security contract as assertions. For a signature, require canonicalisation to succeed, the Reference URI to resolve to the intended node, digest validation to pass, and signature validation to identify the expected certificate or public key. For encryption, require the designated plaintext element to decrypt exactly, then assert the resulting XML structure and business values. Avoid using “document parses” as the only oracle because well-formed ciphertext can still be attached to the wrong key or element.
For a document that is both signed and encrypted, define the production sequence. A common sequence signs an order, encrypts the signed element, and later decrypts before verifying the signature. The reverse sequence protects different XML and needs its own fixture. Tests should make this sequence explicit through method names such as decryptThenVerifySignedOrder and verifyDetachedPurchaseOrder, rather than leaving security intent buried in setup code.
Pin permitted algorithms instead of accepting whatever the installed provider selects by default. The test configuration should record the digest, signature, encryption, and canonicalisation choices, while a negative fixture confirms that a prohibited legacy algorithm is rejected.
Create deterministic sample data
Build sample documents from small domain objects rather than giant string templates. A builder can populate customer, invoice, and audit elements, assign namespaces, and control whitespace. Keeping those choices in code makes it easy to generate a valid baseline and deliberately altered variants while ensuring every change is intentional.
<invoice id="AU-2026-0041" issued="2026-07-04"
xmlns="urn:example:invoice">
<customer>
<name>Priya Patel</name>
<address>45 George Street, Sydney NSW 2000</address>
<phone>+61 2 9000 0000</phone>
</customer>
<total currency="AUD">149.90</total>
<note>Call before the arvo delivery</note>
</invoice>
The sample uses Australian realities deliberately: a Sydney address and NSW postcode, a fictional +61 number, AUD, and a day-first presentation date of 04/07/2026. The XML keeps the machine-readable date in ISO form while a renderer can display the local format. “Arvo” gives the fixture a natural Australian voice, and a Melbourne team can use the same generator with a VIC address. These details create useful variation without pulling live personal data into source control.
Use a fixed seed, stable identifiers, and a test-only key pair. Generate malformed or boundary payloads separately, including missing namespaces, empty totals, duplicate IDs, unexpected Unicode, and oversized encrypted content. If a production service reads Australian mobile numbers or bank details, use reserved test ranges and synthetic tax identifiers rather than realistic records that could still identify somebody.
Test signatures by changing meaning
For enveloped signatures, sign the canonical form of the chosen element, embed the signature, and verify it with the same canonicalisation algorithm used by production. The test should inspect properties such as algorithm URIs, digest values, and Reference URIs, but it should calculate expected digests independently when practical. This prevents a test from reproducing a faulty signing implementation line for line.
The mutation set should change one factor at a time: alter the total, add an attribute, rename a namespace prefix, change indentation, reorder unrelated siblings, or replace the certificate. Some changes must invalidate the signature; others should leave it valid if the XML canonicalisation contract permits them. Namespace and whitespace changes can alter canonical XML even when the visible invoice looks identical, while changing an unsigned audit element may not affect a correctly restricted Reference.
Also attempt a signature-wrapping attack by moving signed content beneath a replacement wrapper. The verifier should bind the signature to the expected business element, not accept any protected node that happens to contain a valid digest. Cover enveloped, detached, and enveloping signatures with separate fixtures, including XML that uses exclusive canonicalisation.
Signature bytes can vary with randomised signing, particularly for ECDSA, so compare verification outcomes and decoded key information rather than an entire stored signature string. Apache Santuario and the JDK’s XML Signature APIs are both practical choices in Java test suites, provided the provider configuration remains explicit.
Compare signatures and encrypted XML
Encryption tests follow a different success path. Encrypt the selected node with a known test key, locate the resulting EncryptedData, decrypt it, and compare the plaintext XML with the expected business document. XMLUnit can perform namespace-aware comparisons after parsing, while business assertions should target fields such as the invoice total. Use a fresh data-encryption key for each run where the provider supports generated keys.
| Concern | XML signature | XML encryption |
|---|---|---|
| Primary goal | Integrity and signer or key assurance | Confidentiality of selected XML |
| Typical result | Signature and reference structures added to XML | Ciphertext and encrypted-key structures |
| Good assertion | Verify the reference and signature | Decrypt and compare semantic XML |
| Typical mutation | Change signed content or namespace context | Replace ciphertext, key, or encrypted element |
| Common pitfall | Treating visual equality as canonical equality | Treating parseable ciphertext as correct decryption |
The encrypted representation can contain random initialisation material, key-wrap details, and serialisation differences, so exact ciphertext comparison is usually the wrong assertion. When both features are present, order the assertions to match the business workflow. If the signed element is encrypted, decrypt first and verify the signature second. Add negative cases that decrypt successfully but fail signature verification, catching insecure key selection and confused processing paths.
Exercise failures and key handling
Fault injection deserves its own fixture matrix. Corrupt one byte in ciphertext, swap an encrypted key, remove an EncryptedKey, use a certificate with the wrong purpose, or feed oversized XML. For signatures, remove the KeyInfo, substitute a different public key, introduce an invalid canonicalisation URI, and tamper with the Reference URI. Each case should state the expected exception or validation failure rather than merely recording that something went wrong.
Parser hardening needs explicit checks as well. Disable external entities and verify that hostile DTD, external entity, and XInclude payloads are rejected rather than fetched. A valid signature does not make an XML parser safe, and encryption can conceal a malicious payload without removing it.
Keep private keys out of the repository and production secret stores. Generate an ephemeral PKCS#12 keystore or in-memory key pair for integration tests, and provide a separate trusted key to verify that an unknown signer fails. In CI, rotate these test credentials on a schedule and scan fixture directories for accidental .p12, .jks, or PEM files. When a fixture needs to demonstrate certificate expiry, construct it with controlled validity dates rather than waiting for time to pass.
Clock and locale behaviour can create false alarms in Australian deployments. A service run in Brisbane may see a different UTC offset from a colleague in Melbourne during daylight-saving time, while date rendering may expect 04/07/2026 rather than 2026-07-04. Supply an explicit Clock, locale, and time zone in tests, then add cases around Australian daylight-saving transitions and the Australian Eastern Standard Time zone. Keep XML signatures on UTC instants even when the surrounding application displays local times.
Make the checks repeatable in delivery
Organise the JUnit suite around observable outcomes: fixture builders, signing helpers, encryption helpers, and assertions that inspect XML semantically. A helper that decrypts and parses the result should return a domain invoice or document rather than a generic node tree. That keeps cryptographic mechanics at the edge and makes a failure report say “invoice total changed after decryption” instead of exposing a long XPath stack. The practical automation patterns on Test Detective fit this outcome-focused approach well.
Run one fast, deterministic fixture on every pull request and schedule the broader algorithm, malformed-input, and timing matrix before release. Publish the exact Java version, provider, algorithm settings, and fixture revision with the test report so a failure can be reproduced.
The next step is to add one Java test that signs the sample invoice, encrypts the signed element, decrypts it, verifies the signature, and mutates the total before the final verification so the expected failure is demonstrated.