<?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 Ken Gatimu on Medium]]></title>
        <description><![CDATA[Stories by Ken Gatimu on Medium]]></description>
        <link>https://medium.com/@kengatimu?source=rss-143b4d0b9a2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*R3liUjnjDC9uKnW4</url>
            <title>Stories by Ken Gatimu on Medium</title>
            <link>https://medium.com/@kengatimu?source=rss-143b4d0b9a2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:54:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kengatimu/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[Securing High-Throughput Middleware: Digital Signature vs JWT]]></title>
            <link>https://kengatimu.medium.com/securing-high-throughput-middleware-digital-signature-vs-jwt-edf257d9cf98?source=rss-143b4d0b9a2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/edf257d9cf98</guid>
            <dc:creator><![CDATA[Ken Gatimu]]></dc:creator>
            <pubDate>Sat, 10 May 2025 21:30:29 GMT</pubDate>
            <atom:updated>2025-05-10T21:49:18.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZXLlFH4tlV9iPgutKFwcA.png" /></figure><h3>Introduction</h3><p><strong>Trust</strong>.<br>It’s the invisible <strong>contract</strong> behind every API call — and the first thing to break when bad data slips through.</p><blockquote>As Niccolo Machiavelli once wrote in <strong>The Prince,</strong><br><strong>“The promise given was a necessity of the past: the word broken is a necessity of the present.”</strong></blockquote><blockquote>He wasn’t talking about software. He was talking about<strong> trust </strong>— and its fragility when stakes are high.</blockquote><p>When securing APIs, most teams reach for <strong>JWT</strong>. It’s widely used, well-documented, and fits naturally in <strong>user login flows</strong>.</p><p>But what if you’re building a <strong>high-throughput middleware</strong> — not for users, but for <strong>channels, transaction systems, and integrations</strong>?</p><p>No sessions. No identity. Just <strong>stateless</strong>,<strong> high-throughput validation </strong>and<strong> routing.</strong></p><p>In our case, we faced <strong>three possible approaches</strong>:</p><ul><li>Use <strong>signature validation</strong> using public-private keys (PKI)</li><li>Use <strong>JWT as a fallback</strong>, where PKI is not feasible</li><li>Use <strong>JWT on top of signature validation</strong> — a tempting but flawed design that should be avoided</li></ul><p>This article explains why we chose <strong>digital signatures </strong>as the core, why <strong>JWT </strong>can be a<strong> fallback</strong>, and why <strong>JWT on top of signature is not just redundant — it’s risky and discouraged</strong>.</p><p>To make it <strong>practical</strong>, we built a working Spring Boot project, <strong>signature-vs-jwt-demo</strong> with 3 services:</p><ul><li><strong>channel-service — </strong>Sends signed or JWT-authenticated transaction payloads</li><li><strong>signature-middleware-service</strong> — Validates using digital signatures (RSA PKI)</li><li><strong>jwt-middleware-service</strong> — Validates using HMAC-based JWT</li></ul><p>This project can be referenced on my GitHub below:</p><p><strong>GitHub project:</strong> <a href="https://github.com/kengatimu/signature-vs-jwt-demo">github.com/kengatimu/signature-vs-jwt-demo</a></p><h3>What We’ll Cover</h3><ul><li><strong>The Middleware</strong><br> Why JWT isn’t built for trust — and what middleware really needs.</li><li><strong>JWT: The Popular Choice (With a Hidden Cost)</strong><br> A deep dive into how JWT works, what it validates, and where it falls short.</li><li><strong>What JWT Actually Verifies (with Real Code)</strong><br> A real example showing how JWT looks correct — until it isn’t.</li><li><strong>The Dangers of JWT in Middleware</strong><br> Replay risk, weak binding, tight coupling — and why it all matters.</li><li><strong>Digital Signature Validation — PKI Done Right</strong><br> How to securely sign and verify the actual payload using RSA.</li><li><strong>PKI Signature: How We Sign the Request</strong><br> A walkthrough of the channel’s private key signing logic.</li><li><strong>Payload Signature Validation: How We Verify It</strong><br> How the middleware uses public keys to validate authenticity and integrity.</li><li><strong>JWT On Top of PKI: Please Don’t</strong><br> Why combining both makes things worse — not better.</li><li><strong>Conclusion</strong><br> A clear verdict: use JWT only if you must — and never on top of signatures.</li><li><strong>GitHub + Socials</strong><br> Try it yourself: <a href="https://github.com/kengatimu/signature-vs-jwt-demo">signature-vs-jwt-demo</a></li></ul><h3>The Middleware</h3><p>Middleware is <strong>not</strong> a login system. It <strong>doesn’t</strong> solve user <strong>login problems.</strong><br>It solves <strong>trust problems</strong> between systems.</p><p>In security, we often talk about the “<strong>5 A’s</strong>”:</p><ul><li><strong>Authentication</strong> — Proving who you are</li><li><strong>Authorization</strong> — Deciding what you’re allowed to do</li><li><strong>Accounting</strong> — Logging what you did (auditing)</li><li><strong>Availability</strong> — Making sure the system is up when it matters</li><li><strong>Assurance</strong> — Confidence that the system works securely and as intended</li></ul><p>These principles guide how we design secure systems.</p><p>But when it comes to <strong>middleware</strong>, not all of them apply the way they do in traditional<strong> user-based</strong> applications.</p><p>Middleware isn’t there to:</p><ul><li>Manage sessions</li><li>Track users</li><li>Hand out access tokens or roles</li></ul><p>Instead, it sits quietly between systems — acting like a <strong>smart pipe</strong> that <strong>receives, verifies, and routes requests</strong>.</p><p>Picture this:</p><p>Your internal channel (say <strong>OMNI</strong> or <strong>REMITTANCE</strong>) sends a transaction payload to the middleware.</p><p>The <strong>middleware</strong> needs to:</p><ul><li><strong>Validate</strong> that request</li><li><strong>Forward</strong> it to an external system (like Telco gateway, core banking, or a partner API)</li><li><strong>Wait</strong> for a response or <strong>callback</strong></li><li><strong>Log</strong> everything</li><li>And <strong>respond</strong> quickly — under load</li></ul><p>It’s not asking:<strong> Who is this user, and are they allowed to transfer money?</strong></p><p>Instead, it’s asking:</p><ul><li>Did <strong>OMNI</strong> really <strong>send</strong> this? → Authentication</li><li>Has this request been <strong>tampered</strong> with? → Integrity (part of Assurance)</li><li>Can <strong>OMNI</strong> later <strong>deny sending</strong> it? → Non-repudiation (also part of Assurance)</li><li>Are we <strong>logging</strong> this properly? → Accounting</li><li>Can we handle this at <strong>scale</strong>? → Availability</li></ul><p>And because we’re using TLS — <strong>confidentiality</strong> is already handled in transit</p><p>These are <strong>cryptographic trust problems</strong>, not login problems.</p><p>And here’s where most developers reach for <strong>JWT</strong>.</p><h3>JWT: The Popular Choice (With a Hidden Cost)</h3><p>Let’s break down how JWT works — and where it begins to fall apart when <strong>trust</strong> and <strong>throughput</strong> are the real challenges.</p><p>At a glance, <strong>JWT</strong> (JSON Web Token) looks like the perfect solution:</p><ul><li>It’s compact</li><li>It’s widely supported</li><li>It works out of the box with most frameworks</li><li>You can embed useful data (claims) inside the token itself</li></ul><p><strong>JWT</strong> is everywhere. It’s <strong>clean</strong>, <strong>stateless</strong>, and <strong>plays</strong> well with frontend-backend flows.</p><p>You <strong>issue</strong> a token, <strong>sign it</strong>, set an <strong>expiry</strong> — and you’re done.</p><p>So it’s no surprise that many engineers reach for JWT when trying to secure middleware.</p><p>It even feels like it works.</p><p>You can:</p><ul><li><strong>Add</strong> theright claims (like <strong>rrn</strong>, <strong>amount</strong>, or <strong>sender</strong>)</li><li><strong>Sign</strong> the token using HMAC or RSA</li><li><strong>Validate</strong> it on the receiving side</li></ul><p>But here’s the twist:</p><p><strong>JWT validates the token — not the request.</strong></p><p>That sounds subtle, but in middleware, it’s a <strong>crucial</strong> difference.</p><blockquote>JWT was designed to say “<strong>this token is trusted</strong>” — not “<strong>this exact payload is untouched.</strong>”</blockquote><p>In <strong>middleware</strong>, the <strong>payload</strong> <strong>is</strong> the trust contract.</p><p>You’re not managing sessions or users. You’re receiving critical instructions:</p><blockquote>“<strong>Debit</strong> this amount, from this sender, to that receiver.”</blockquote><p>And you need guarantees:</p><ul><li><strong>Authenticity</strong>: Did this really come from OMNI or REMITTANCE?</li><li><strong>Integrity</strong>: Has any of it been tampered with?</li><li><strong>Non-repudiation</strong>: Can they later deny sending it?</li></ul><p>With JWT, you’d have to:</p><ul><li>Mirror every payload field into the JWT claims</li><li>Make sure both sides agree on field names and formats</li><li>Hope nothing changes outside the token</li></ul><p>Even then, the risk is real: the token could be <strong>valid</strong>, but the request body <strong>altered</strong>.</p><blockquote>That’s why JWT in middleware <strong>starts to fall apart</strong> — especially under load, with many channels, and no room for mistakes.</blockquote><p>So before you settle for JWT, ask:</p><ul><li>Are you <strong>validating</strong> the <strong>token</strong>?</li><li>Or are you <strong>validating</strong> the <strong>data</strong> that actually matters?</li></ul><h3>What JWT Actually Verifies (with Real Code)</h3><p>Here’s how the JWT is generated in the <strong>channel service:</strong></p><pre>@Service<br>public class JwtTokenServiceImpl implements JwtTokenService {<br>    private static final long EXPIRATION_MILLIS = 5 * 60 * 1000; // 5 minutes<br>    private final Key hmacKey;<br><br>    public JwtTokenServiceImpl(@Value(&quot;${jwt.secret}&quot;) String base64Secret) {<br>        // Decode Base64 secret string into a raw byte array key<br>        byte[] decodedKey = Base64.getDecoder().decode(base64Secret.getBytes(StandardCharsets.UTF_8));<br>        this.hmacKey = Keys.hmacShaKeyFor(decodedKey);<br>    }<br><br>    @Override<br>    public String generateToken(ChannelRequestDto dto) {<br>        return Jwts.builder()<br>                .setSubject(&quot;channel-service&quot;)<br>                .setIssuedAt(new Date())<br>                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_MILLIS))<br>                .claim(&quot;rrn&quot;, dto.getRrn())<br>                .claim(&quot;amount&quot;, dto.getAmount())<br>                .claim(&quot;currency&quot;, dto.getCurrency())<br>                .claim(&quot;senderName&quot;, dto.getSenderName())<br>                .claim(&quot;receiverName&quot;, dto.getReceiverName())<br>                .claim(&quot;transactionType&quot;, TransactionType.CREDIT_TRANSFER.name())<br>                .signWith(hmacKey, SignatureAlgorithm.HS256)<br>                .compact();<br>    }<br>}</pre><h3>Step-by-Step Verification</h3><p>Let’s look at how our <strong>jwt-middleware-service </strong>handles a JWT-protected transaction.</p><p>1. <strong>RequestProcessorServiceImpl.java</strong></p><pre>@Override<br>public TransactionResponseDto processTransactionRequestForJwt(<br>                              String token,<br>                              TransactionRequestDto requestDto,<br>                              BindingResult bindingResult<br>) throws CustomException {<br>    // Step 1: Validate the request body fields<br>    checkForInputValidationErrors(bindingResult);<br><br>    // Step 2: Validate the JWT itself<br>    Jws&lt;Claims&gt; jws = jwtValidationService.validateToken(token);<br>    Claims claims = jws.getBody();<br><br>    // Step 3: Compare claims in the JWT to request body values<br>    validateClaimsAgainstRequest(claims, requestDto);<br><br>    // Step 4: If all matches, return success<br>    return composeChannelResponse(requestDto);<br>}</pre><p><strong>2. JwtValidationServiceImpl.java</strong></p><pre>@Service<br>public class JwtValidationServiceImpl implements JwtValidationService {<br>    private static final Logger log = LoggerFactory.getLogger(JwtValidationServiceImpl.class);<br><br>    private final Key hmacKey;<br><br>    public JwtValidationServiceImpl(@Value(&quot;${jwt.secret}&quot;) String base64Secret) {<br>        // Decode the base64-encoded secret into a cryptographic key<br>        byte[] decodedKey = Base64.getDecoder().decode(base64Secret.getBytes(StandardCharsets.UTF_8));<br>        this.hmacKey = Keys.hmacShaKeyFor(decodedKey);<br>    }<br><br>    @Override<br>    public Jws&lt;Claims&gt; validateToken(String token) throws CustomException {<br>        try {<br>            // Parse and validate JWT token using the secret HMAC key<br>            return Jwts.parserBuilder()<br>                    .setSigningKey(hmacKey)<br>                    .build()<br>                    .parseClaimsJws(token);<br>        } catch (JwtException e) {<br>            // Token is invalid (expired, malformed, wrong signature, etc.)<br>            log.error(&quot;JwtException Occurred During Jwt validation: {}&quot;, e.getMessage());<br>            throw new CustomException(JWT_VALIDATION_ERROR + &quot;JWT validation failed: &quot; + e.getMessage());<br>        } catch (IllegalArgumentException e) {<br>            // Token is null or empty<br>            log.error(&quot;IllegalArgumentException Occurred During Jwt validation: {}&quot;, e.getMessage());<br>            throw new CustomException(JWT_VALIDATION_ERROR + &quot;JWT token is missing or empty&quot;);<br>        }<br>    }<br>}</pre><p><strong>3. validateClaimsAgainstRequest()</strong></p><pre>// Compare JWT claims with incoming request fields<br>private void validateClaimsAgainstRequest(<br>             Claims claims, <br>             TransactionRequestDto dto) <br>throws CustomException {<br>    try {<br>        if (!dto.getRrn().equals(claims.get(&quot;rrn&quot;, String.class))) {<br>            throw new CustomException(JWT_VALIDATION_ERROR + &quot;RRN mismatch&quot;);<br>        }<br><br>        String tokenTransactionType = claims.get(&quot;transactionType&quot;, String.class);<br>        if (!dto.getTransactionType().name().equals(tokenTransactionType)) {<br>            throw new CustomException(JWT_VALIDATION_ERROR + &quot;Transaction type mismatch&quot;);<br>        }<br><br>        if (!dto.getCurrency().equals(claims.get(&quot;currency&quot;, String.class))) {<br>            throw new CustomException(JWT_VALIDATION_ERROR + &quot;Currency mismatch&quot;);<br>        }<br><br>        if (!dto.getSenderName().equals(claims.get(&quot;senderName&quot;, String.class))) {<br>            throw new CustomException(JWT_VALIDATION_ERROR + &quot;Sender name mismatch&quot;);<br>        }<br><br>        if (!dto.getReceiverName().equals(claims.get(&quot;receiverName&quot;, String.class))) {<br>            throw new CustomException(JWT_VALIDATION_ERROR + &quot;Receiver name mismatch&quot;);<br>        }<br><br>        BigDecimal claimAmount = new BigDecimal(claims.get(&quot;amount&quot;).toString());<br>        if (dto.getAmount().compareTo(claimAmount) != 0) {<br>            throw new CustomException(JWT_VALIDATION_ERROR + &quot;Amount mismatch&quot;);<br>        }<br><br>    } catch (NullPointerException | IllegalArgumentException e) {<br>        throw new CustomException(JWT_VALIDATION_ERROR + &quot;Invalid or missing claim values: &quot; + e.getMessage());<br>    }<br>}</pre><p>So far, so good. It looks clean and responsible.</p><h3>What You’re Doing Right</h3><ul><li>You’re taking values from the actual request (DTO) and embedding them into the JWT as claims.</li><li>You’re signing the JWT using a secret (HMAC key).</li><li>You’re validating the signature on the receiving side, and checking each claim manually.</li></ul><p>This is the right way to do HMAC-based JWT.</p><h3>What’s Still Missing: Cryptographic Binding</h3><p>Here’s the <strong>catch</strong>:</p><blockquote>The JWT is <strong>not cryptographically</strong> bound to the actual payload (body) of the HTTP request.</blockquote><p>The JWT is sent in the <strong>header</strong>. The payload (the body) is separate. You are manually hoping that the two match — and manually checking them.</p><p>But JWT doesn’t <strong>cryptographically</strong> bind the token to the actual payload.</p><p>Let’s say a <strong>valid</strong> <strong>request</strong> looks like this:</p><pre>{<br>  &quot;rrn&quot;: &quot;TX001&quot;,<br>  &quot;amount&quot;: 100<br>}</pre><p>The token has <strong>claims</strong> matching <strong>“TX001”</strong> and <strong>100</strong>, and is signed correctly.</p><p>Now imagine an <strong>attacker</strong> intercepts this request, keeps the JWT the same, but <strong>modifies</strong> the payload:</p><pre>{<br>  &quot;rrn&quot;: &quot;TX002&quot;,<br>  &quot;amount&quot;: 100000<br>}</pre><p>Unless you <strong>manually compare every field</strong> in the payload against the claim, which we are doing now, the backend would <strong>trust the JWT </strong>and process the altered body.</p><p>So the <strong>binding is only as strong as your code discipline</strong>, not as strong as <strong>cryptography</strong>.</p><p>You’re relying on <strong>code discipline, not</strong> <strong>cryptographic</strong> safety.</p><h3>The Dangers of This Approach</h3><p>Even if your claim checks are perfect, here’s what still remains risky:</p><ol><li><strong>The token is separate from the payload.</strong><br>No Binding Between Header and Payload and therefore, no there’s no cryptographic glue between the JWT and the body.</li></ol><p>This means:</p><ul><li>A valid token can be reused with a different body.</li><li>Your only <strong>safeguard is defensive coding</strong> .</li></ul><p><strong>2. Replays are possible.</strong><br>JWTs don’t auto-expire the moment they’re used. Unless you track token usage or timestamps, a malicious actor can:</p><ul><li>Resend the same token and payload combo.</li><li>Or worse, pair a valid token with a new payload.</li></ul><p><strong>3. Shared secret = shared risk.</strong><br> HS256 (HMAC) uses a <strong>shared secret key</strong>.<br> If either side leaks it, <strong>anyone</strong> can:</p><ul><li>Forge a valid token</li><li>Send it to middleware</li><li>Get past signature checks</li></ul><p>That’s why systems like OAuth 2 often prefer <strong>asymmetric</strong> keys (RS256).</p><p><strong>4. Blind trust in claims.</strong><br>Once the token is verified, teams tend to <strong>trust the claims blindly</strong>.</p><p>But claims are just fields — not proof.</p><p>Unless you <strong>tie</strong> them to the payload <strong>cryptographically</strong>, you’re trusting something you shouldn’t.</p><p><strong>5. Code duplication and tight coupling.</strong><br>You must duplicate the same field list and format on both ends. Any drift or change causes fragile failures.</p><p>Now both the sender and the middleware must agree on:</p><ul><li>The exact set of claims</li><li>The naming convention</li><li>The data format</li></ul><p>That tight coupling leads to broken integrations when things change.</p><h3>So… What’s the Alternative?</h3><p>Digital Signatures.</p><p>With signatures:</p><ul><li>You <strong>sign the payload itself</strong>, not a separate token.</li><li>The middleware <strong>verifies the exact bytes</strong> received.</li><li>Any tampering, <strong>even a single character, </strong>breaks the verification.</li><li>There’s <strong>no need to compare individual fields one by one, </strong>the signature is verified against the <strong>exact canonical payload</strong> (Clear text values). If anything changes, the verification fails.</li></ul><p>Let’s look at how that works next, and why it’s the better fit for high-throughput middleware.</p><h3>Digital Signature Validation — PKI Done Right</h3><blockquote><em>I</em>n the world of security design, <strong>timing</strong> matters. As <strong>Niccolo</strong> <strong>Machiavelli</strong> puts it:</blockquote><blockquote><strong>“The wise man does at once what the fool does finally.”</strong></blockquote><blockquote>It’s a principle we ignore most of the time in software, <strong>putting off</strong> real validation, saying “we’ll secure it later.”</blockquote><blockquote>Or, as <strong>Michael Scott</strong> would put it:</blockquote><blockquote><strong>“I’m not superstitious. But I am a little stitious.”</strong></blockquote><p>In <strong>high-throughput middleware</strong> systems, many teams delay implementing digital signatures. They say, “Let’s just use JWT for now” — hoping they’ll secure things later.</p><p>But waiting to add proper PKI validation is exactly what <strong>Niccolo</strong> <strong>Machiavelli</strong> warned against — and exactly what <strong>Michael Scott</strong> would accidentally endorse.</p><p>Fortunately, setting up PKI isn’t that hard. And once you do it, you gain real <strong>cryptographic</strong> <strong>trust</strong>.</p><p>Let’s walk through how we implemented it in our <a href="https://github.com/kengatimu/signature-vs-jwt-demo">git hub demo</a>.</p><h3>The Flow</h3><p>In our setup:</p><ul><li><strong>channel-service</strong> <strong>Generates</strong> a digital signature using its <strong>private key, </strong>stored in a keystore,<strong> </strong>and appends it to the payload.</li><li><strong>signature-middleware-service</strong> <strong>Verifies</strong> the signature using the corresponding <strong>public certificate</strong>, which it stores in a <strong>truststore</strong>.</li><li>All communication between the services is secured using <strong>mutual TLS (mTLS)</strong>.</li></ul><p>Here’s a quick overview of how we generated and structured our keys and certificates:</p><h3>Key and Certificate Generation</h3><ol><li>Generate the channel-service keystore:</li></ol><pre># Generate private key and csr for self signing<br>openssl req -newkey rsa:2048 -nodes -keyout channel-service.key -out channel-service.csr \<br>-subj &quot;/C=KE/ST=Nairobi/L=Nairobi/O=Channel Kenya Limited/OU=Channel/CN=*.channel.co.ke/emailAddress=info@channelgroup.co.ke&quot;<br><br># Self sign the generated csr<br>openssl x509 -req -in channel-service.csr -signkey channel-service.key -out channel-service.pem -days 3650<br><br># Generate p12 keystore and store the private key<br>openssl pkcs12 -export -in channel-service.pem -inkey channel-service.key -out channel-service.p12 -name channel-service -password &#39;pass:channel-service!&#39;</pre><p>2. Create certificates per channel (OMNI, REMITTANCE)</p><p>We created demo <strong>.crt versions</strong> of the certificate for <strong>OMNI</strong> and <strong>REMITTANCE</strong> (pretending each is a distinct channel).</p><p><strong>Note: </strong>We are using <strong>channel-service.pem</strong> to generate both certificates.</p><p>In the real world, <strong>OMNI</strong> and <strong>REMMITTANCE</strong> channels will provide, each a distinct <strong>certificate (crt) </strong>file.</p><pre>openssl x509 -in channel-service.pem -out OMNI.crt<br>openssl x509 -in channel-service.pem -out REMITTANCE.crt</pre><p>3. Import them into a truststore:</p><pre># OMNI<br>keytool -importcert \<br>  -alias omni \<br>  -file OMNI.crt \<br>  -keystore truststore-channel-service.p12 \<br>  -storetype PKCS12 \<br>  -storepass channel-verify!<br><br># REMITTANCE<br>keytool -importcert \<br>  -alias remittance \<br>  -file REMITTANCE.crt \<br>  -keystore truststore-channel-service.p12 \<br>  -storetype PKCS12 \<br>  -storepass channel-verify!</pre><p><strong>Optional: </strong>Verify the content of the truststore. You should see 2 entities:</p><pre>keytool -list -v \<br>  -keystore truststore-channel-service.p12 \<br>  -storetype PKCS12 \<br>  -storepass &#39;channel-verify!&#39;<br><br># Output extract<br>Keystore type: PKCS12<br>Keystore provider: SUN<br><br>Your keystore contains 2 entries<br><br>Alias name: omni<br>Creation date: 7 May 2025<br>Entry type: trustedCertEntry<br>--------<br>Alias name: remittance<br>Creation date: 7 May 2025<br>Entry type: trustedCertEntry</pre><p>4. For mutual TLS, trust the middleware certificate</p><ul><li><strong>signature-middleware-service</strong> will have provided a <strong>valid</strong> certificate file (<strong>middleware-service.crt</strong>) which we created a truststore and stored it.</li><li>This is for mutal TLS purposes.</li></ul><pre>keytool -importcert \<br>  -keystore truststore-middleware-service.p12 \<br>  -storetype PKCS12 \<br>  -storepass mytrustpass \<br>  -alias middleware \<br>  -file middleware-service.crt</pre><p><strong>Note: </strong>If the certificate was not provided, you can run this command, and store the certificate details in a file. You can name the file as <strong>middleware-service.crt</strong></p><pre>openssl s_client -connect localhost:65443 -showcerts<br><br># Copy everything from -----BEGIN CERTIFICATE----- to -----END CERTIFICATE----- </pre><p>Once saved, <strong>trust it</strong> by running the previous <strong>importcert</strong> command.</p><h3>Application Yaml Configurations</h3><ol><li>channel-service application-uat.yaml file:</li></ol><pre># ssl configs<br>server:<br>  port: 60443<br>  ssl:<br>    # key-store for ssl only<br>    enabled: true<br>    key-store: &#39;/Users/bishop/Articles/Demo-Projects/certs/ssl/channel-service.p12&#39;<br>    key-store-password: &#39;channel-service!&#39;<br>    key-store-type: PKCS12<br>    key-alias: &#39;channel-service&#39;<br><br>    # trust-store to trust middleware-service certificate during ssl handshake<br>    trust-store: &#39;/Users/bishop/Articles/Demo-Projects/certs/ssl/truststore-middleware-service.p12&#39;<br>    trust-store-password: &#39;mytrustpass&#39;<br>    trust-store-type: PKCS12<br>    trust-alias: &#39;middleware&#39;<br><br># enable this if you want to skip host verification during ssl handshake<br>http:<br>  ssl:<br>    skip-hostname-verification: true</pre><p>2. signature-middleware-service application-uat.yaml file:</p><pre># ssl configs<br>server:<br>  port: 65443<br>  ssl:<br>    # key-store for ssl only<br>    enabled: true<br>    key-store: &#39;/Users/bishop/Articles/Demo-Projects/certs/ssl/keystore-my-application.p12&#39;<br>    key-store-password: &#39;changeit!&#39;<br>    key-store-type: PKCS12<br>    key-alias: &#39;ssl&#39;<br><br>  # trust-store containing channel-service certificate for signature verification<br>  verification:<br>    trust-store: &#39;/Users/bishop/Articles/Demo-Projects/certs/verification/truststore-channel-service.p12&#39;<br>    trust-store-password: &#39;channel-verify!&#39;<br>    trust-store-type: PKCS12<br>    trust-alias: &#39;verify&#39;</pre><p>Now that we’ve got the <strong>infrastructure locked in</strong>, let’s walk through how signature-based validation works in code:</p><h3>PKI Signature</h3><p>With our <strong>PKI setup</strong> in place, let’s walk through how a <strong>transaction is signed</strong>, <strong>sent</strong>, and <strong>verified, </strong>using only the <strong>payload and cryptographic keys</strong>.</p><h3>Payload Signing</h3><blockquote>“Before you send it, sign it.”</blockquote><p>Unlike JWT, where the token is a separate object from the payload, a <strong>digital signature</strong> binds the exact contents of the request, <strong>field by field</strong>, using <strong>asymmetric cryptography</strong>.</p><p>Here’s how our <strong>channel-service</strong> does it behind the scenes.</p><pre>@Service<br>public class SignatureGenerationServiceImpl implements SignatureGenerationService {<br>    private static final Logger log = LoggerFactory.getLogger(SignatureGenerationServiceImpl.class);<br><br>    private final String keyAlias;<br>    private final String keyStorePath;<br>    private final String keyStoreType;<br>    private final String keyStorePassword;<br><br>    public SignatureGenerationServiceImpl(@Value(&quot;${server.ssl.key-alias}&quot;) String keyAlias,<br>                                          @Value(&quot;${server.ssl.key-store}&quot;) String keyStorePath,<br>                                          @Value(&quot;${server.ssl.key-store-type}&quot;) String keyStoreType,<br>                                          @Value(&quot;${server.ssl.key-store-password}&quot;) String keyStorePassword) {<br>        this.keyAlias = keyAlias;<br>        this.keyStorePath = keyStorePath;<br>        this.keyStoreType = keyStoreType;<br>        this.keyStorePassword = keyStorePassword;<br>    }<br><br>    @Override<br>    public String generateSignature(ChannelRequestDto requestDto, TransactionType type) throws CustomException {<br>        try (FileInputStream fis = new FileInputStream(keyStorePath)) {<br>            // Load keystore from file<br>            KeyStore keyStore = KeyStore.getInstance(keyStoreType);<br>            keyStore.load(fis, keyStorePassword.toCharArray());<br><br>            // Retrieve private key using alias and password<br>            Key key = keyStore.getKey(keyAlias, keyStorePassword.toCharArray());<br>            if (!(key instanceof PrivateKey)) {<br>                throw new CustomException(CERT_GENERATION_ERROR + &quot;Key in keystore is not a private key&quot;);<br>            }<br><br>            // Concatenate fields in exact order to create the clear text<br>            String clearText = generateClearTextValues(requestDto);<br>            log.info(&quot;Data to sign: {}&quot;, clearText);<br><br>            // Initialize and sign the data using RSA + SHA-256<br>            Signature signature = Signature.getInstance(&quot;SHA256withRSA&quot;);<br>            signature.initSign((PrivateKey) key);<br>            signature.update(clearText.getBytes());<br><br>            // Encode the resulting signature in Base64<br>            byte[] signedBytes = signature.sign();<br>            return Base64.getEncoder().encodeToString(signedBytes);<br><br>        } catch (KeyStoreException<br>                 | NoSuchAlgorithmException<br>                 | UnrecoverableKeyException<br>                 | CertificateException<br>                 | InvalidKeyException<br>                 | SignatureException<br>                 | IOException e) {<br>            log.error(&quot;Error generating signature: {}&quot;, e.getMessage());<br>            throw new CustomException(CERT_GENERATION_ERROR + &quot;Signature generation failed: &quot; + e.getMessage());<br>        }<br>    }<br><br>    private String generateClearTextValues(ChannelRequestDto requestDto) {<br>        // Compose canonical string to be signed (order matters)<br>        return requestDto.getRrn() +<br>                CHANNEL_ID +<br>                requestDto.getSenderName() +<br>                requestDto.getReceiverName() +<br>                requestDto.getAmount() +<br>                requestDto.getFeeAmount() +<br>                requestDto.getCurrency();<br>    }<br>}</pre><p>Let’s break it down what is happening in the above class, step by step:</p><h4><strong>Step 1: Load the private key</strong></h4><ul><li>From the <strong>channel’s .p12 keystore</strong> file (which only this channel holds), we securely <strong>load the private key</strong> using:</li></ul><pre>keyStore.getKey(keyAlias, keyStorePassword.toCharArray())</pre><h4><strong>Step 2: Build the canonical clear text</strong></h4><ul><li>We <strong>concatenate </strong>specific fields from the request (like rrn, amount, currency, etc.) in a fixed, agreed-upon <strong>order</strong>:</li></ul><pre>rrn + channelId + senderName + receiverName + amount + feeAmount + currency</pre><ul><li>This ordered string is what we’ll <strong>sign</strong> — it’s the <strong>source of truth.</strong></li></ul><h4><strong>Step 3: Create a SHA-256 hash</strong></h4><p>Using the <strong>algorithm SHA256withRSA</strong>, we:</p><ul><li>Generate a <strong>one-way hash</strong> of the clear text string</li><li>Then <strong>encrypt that hash</strong> using the <strong>channel’s private key</strong></li></ul><pre>Signature signature = Signature.getInstance(&quot;SHA256withRSA&quot;);<br>signature.initSign((PrivateKey) key);<br>signature.update(clearText.getBytes());</pre><p>This step ensures <strong>two things</strong>:</p><ul><li>The hash <strong>can’t be reversed </strong>(because it’s one-way)</li><li>Only the <strong>holder</strong> of the <strong>private key </strong>could have produced the encrypted hash</li></ul><h4><strong>Step 4: Base64 encode the signature</strong></h4><p>— The <strong>resulting</strong> signature bytes are <strong>encoded using Base64</strong>, making them safe to transmit as part of the payload:</p><pre>return Base64.getEncoder().encodeToString(signedBytes);</pre><h4>Why This Matters</h4><ul><li>We’re not signing a JWT.</li><li>We’re not trusting self-reported claims.</li><li>We’re <strong>signing the actual request </strong>content <strong>with a key</strong> that only this <strong>channel</strong> has.</li></ul><p>That’s strong, unforgeable proof that the request:</p><ul><li><strong>Came</strong> from the <strong>real</strong> sender</li><li>Was not <strong>tampered</strong> with</li></ul><p>And best of all?<br>The middleware can verify all of this <strong>without ever talking to the sender again</strong>.</p><h3>Payload Signature Validation</h3><p>When the signed payload arrives at the middleware, it’s <strong>not trusted</strong> automatically.</p><p>The class S<strong>ignatureValidationServiceImpl </strong>in <strong>signature-middleware-service</strong> does something quietly <strong>powerful</strong>:</p><p>It <strong>validates the request payload itself, </strong>using <strong>public key cryptography, </strong>without trusting claims, tokens, or client metadata.</p><pre>@Service<br>public class SignatureValidationServiceImpl implements SignatureValidationService {<br>    private static final Logger log = LoggerFactory.getLogger(SignatureValidationServiceImpl.class);<br><br>    private final String trustStorePath;<br>    private final String trustStoreType;<br>    private final String trustStorePassword;<br><br>    // Map channelId to its corresponding certificate alias in the trust store<br>    private final Map&lt;String, String&gt; channelCertAliasMap = Map.of(<br>            &quot;OMNI&quot;, &quot;omni&quot;,<br>            &quot;REMITTANCE&quot;, &quot;remittance&quot;<br>    );<br><br>    public SignatureValidationServiceImpl(@Value(&quot;${server.verification.trust-store}&quot;) String trustStorePath,<br>                                          @Value(&quot;${server.verification.trust-store-type}&quot;) String trustStoreType,<br>                                          @Value(&quot;${server.verification.trust-store-password}&quot;) String trustStorePassword) {<br>        this.trustStorePath = trustStorePath;<br>        this.trustStoreType = trustStoreType;<br>        this.trustStorePassword = trustStorePassword;<br>    }<br><br>    @Override<br>    public void validateSignature(TransactionRequestDto requestDto, TransactionType type) throws CustomException {<br>        String rrn = requestDto.getRrn();<br>        String channelId = requestDto.getChannelId();<br><br>        // Resolve the correct certificate alias based on channelId<br>        String resolvedAlias = channelCertAliasMap.get(channelId);<br>        if (resolvedAlias == null) {<br>            throw new CustomException(CERT_VERIFICATION_ERROR + &quot;Unrecognized channelId: &quot; + channelId);<br>        }<br><br>        try (FileInputStream fis = new FileInputStream(trustStorePath)) {<br>            // Load the trust store<br>            KeyStore trustStore = KeyStore.getInstance(trustStoreType);<br>            trustStore.load(fis, trustStorePassword.toCharArray());<br><br>            // Retrieve the certificate using the resolved alias<br>            X509Certificate cert = (X509Certificate) trustStore.getCertificate(resolvedAlias);<br>            if (cert == null) {<br>                throw new CustomException(CERT_VERIFICATION_ERROR + &quot;Certificate not found for alias: &quot; + resolvedAlias);<br>            }<br><br>            // Get the public key from the certificate<br>            PublicKey publicKey = cert.getPublicKey();<br><br>            // Construct the original clear text used during signing<br>            String clearText = generateClearTextValues(requestDto);<br>            log.info(&quot;Clear text for verification: {}&quot;, clearText);<br><br>            // Decode the Base64-encoded signature<br>            byte[] signatureBytes = Base64.getDecoder().decode(requestDto.getSignature());<br><br>            // Initialize the signature verification process<br>            Signature signature = Signature.getInstance(&quot;SHA256withRSA&quot;);<br>            signature.initVerify(publicKey);<br>            signature.update(clearText.getBytes());<br><br>            // Perform signature validation<br>            if (!signature.verify(signatureBytes)) {<br>                throw new CustomException(CERT_VERIFICATION_ERROR + &quot;Invalid signature&quot;);<br>            }<br><br>            log.info(&quot;{}: Signature validated successfully using alias &#39;{}&#39;&quot;, rrn, resolvedAlias);<br>        } catch (KeyStoreException<br>                 | NoSuchAlgorithmException<br>                 | CertificateException<br>                 | IOException<br>                 | InvalidKeyException<br>                 | SignatureException e) {<br>            // Log and rethrow custom exception if validation fails<br>            log.error(&quot;{}: Signature verification failed: {}&quot;, rrn, e.getMessage());<br>            throw new CustomException(CERT_VERIFICATION_ERROR + &quot;Signature validation failed: &quot; + e.getMessage());<br>        }<br>    }<br><br>    // Builds the canonical clear text string used for signature validation<br>    private String generateClearTextValues(TransactionRequestDto requestDto) {<br>        return requestDto.getRrn() +<br>                CHANNEL_ID +<br>                requestDto.getSenderName() +<br>                requestDto.getReceiverName() +<br>                requestDto.getAmount() +<br>                requestDto.getFeeAmount() +<br>                requestDto.getCurrency();<br>    }<br>}</pre><p>Let’s break it down.</p><h4>Step 1. Identify the Sender’s Certificate</h4><p>Is this really OMNI?</p><p>We only trust known senders. In this case:</p><pre>private final Map&lt;String, String&gt; channelCertAliasMap = Map.of(<br>    &quot;OMNI&quot;, &quot;omni&quot;,<br>    &quot;REMITTANCE&quot;, &quot;remittance&quot;<br>);</pre><ul><li>Each <strong>known sender</strong> (e.g., OMNI, REMITTANCE) has a corresponding <strong>public certificate</strong> imported into our <strong>truststore</strong>.</li><li>When a request arrives, we <strong>resolve the alias </strong>using the <strong>channelId</strong> in the request:</li></ul><pre>// Resolve the correct certificate alias based on channelId<br>String resolvedAlias = channelCertAliasMap.get(channelId);<br>if (resolvedAlias == null) {<br>    throw new CustomException(CERT_VERIFICATION_ERROR + &quot;Unrecognized channelId: &quot; + channelId);<br>}</pre><blockquote>This guarantees that only <strong>pre-registered, trusted clients</strong> are allowed to send signed transactions.</blockquote><blockquote>If the <strong>channelId</strong> isn’t known — the request is rejected immediately. <strong>No cert, no trust.</strong></blockquote><h4>Step 2: Load the Public Key</h4><ul><li>Using the <strong>alias</strong>, we load the corresponding <strong>X.509 certificate</strong> from the truststore, and extract the <strong>public key:</strong></li></ul><pre>X509Certificate cert = (X509Certificate) trustStore.getCertificate(resolvedAlias);<br>PublicKey publicKey = cert.getPublicKey();</pre><h4>Step 3: Rebuild the Clear Text</h4><ul><li>Just like the <strong>sender</strong>, we rebuild the <strong>canonical string</strong> from the request payload:</li></ul><pre>rrn + channelId + senderName + receiverName + amount + feeAmount + currency</pre><h4>Step 4: Decode the Signature</h4><ul><li>The incoming request contains a <strong>Base64-encoded signature</strong>. We decode it:</li></ul><pre>byte[] signatureBytes = Base64.getDecoder().decode(requestDto.getSignature());</pre><h4>Step 5: Verify the Signature (Integrity + Non-Repudiation)</h4><p>Using <strong>SHA256withRSA</strong>, we:</p><ul><li>Hash the clear text string</li><li>Decrypt the incoming signature using the <strong>public key </strong>to get the<strong> original hash</strong></li><li>Compare both hashes</li></ul><p>If they match — the request is <strong>authentic and untampered</strong>.</p><p>If <strong>not</strong> — something was changed, and the <strong>verification fails.</strong></p><pre>Signature signature = Signature.getInstance(&quot;SHA256withRSA&quot;);<br>signature.initVerify(publicKey);<br>signature.update(clearText.getBytes());<br><br>if (!signature.verify(signatureBytes)) {<br>    throw new CustomException(CERT_VERIFICATION_ERROR + &quot;Invalid signature&quot;);<br>}</pre><h3>What This Proves</h3><ul><li><strong>Authenticity</strong><br>Only the <strong>rightful sender</strong> could have signed this. <strong>Their private key isn’t shared.</strong></li><li><strong>Integrity</strong><br>Even a s<strong>ingle character (including a space) change</strong> in the payload (say, 1500 → 15000) would <strong>break</strong> the hash comparison.</li><li><strong>Non-repudiation</strong><br>Because the <strong>sender’s private key</strong> was used to sign, they can’t later claim: “<strong>That wasn’t me.</strong>”</li><li><strong>Confidentiality</strong><br> The payload was <strong>transmitted over mutual TLS (mTLS)</strong>. So the channel is encrypted end-to-end — cert-verified.</li></ul><h3>Bonus: No Replay Attacks</h3><ul><li>Replay is a common <strong>attack</strong>, but we guard against it by saving every transaction with a <strong>unique rrn.</strong></li><li>Before processing, we run:</li></ul><pre>@Override<br>@Transactional(readOnly = true)<br>public void checkTransactionExists(String rrn, TransactionType type) throws CustomException {<br>    boolean recordExists = transactionDetailsRepository.existsByRrnAndTransactionType(rrn, type);<br><br>    if (recordExists) {<br>        log.error(&quot;{}: Duplicate transaction found for RRN: {}&quot;, rrn, rrn);<br>        throw new CustomException(DUPLICATE_RECORD);<br>    }<br>}</pre><blockquote>If someone tries to resend the same rrn, the system rejects it immediately.</blockquote><h3>JWT On Top of PKI Signature</h3><p>Some teams ask:</p><blockquote>“What if we use <strong>JWT</strong> for structure, and then <strong>sign</strong> the whole request too — just to be extra secure?”</blockquote><p>It sounds cautious. Even smart.<br>But in practice, it’s a mistake.</p><p>You’re doing <strong>twice the work</strong> with <strong>zero added benefit</strong>.</p><p>You already have:</p><ul><li>A digital signature that proves <strong>authenticity</strong>, <strong>integrity</strong>, and <strong>non-repudiation</strong></li><li>TLS that handles <strong>confidentiality</strong></li><li>A truststore to validate <strong>who sent it</strong></li></ul><blockquote>As <strong>Michael Scott </strong>famously said:<br><strong>“Fool me once, strike one. But fool me twice… strike three.”</strong></blockquote><blockquote>Sometimes, layering JWT over signature is that third strike, as it adds nothing, except <strong>confusion</strong>.</blockquote><h3>Why It’s a Bad Design</h3><ul><li><strong>Double the validation logic</strong> — more places to fail</li><li><strong>No extra security</strong> — if the signature is valid, the JWT adds nothing</li><li><strong>Contradictory claims</strong> — now you have to reconcile JWT claims with signed data</li><li><strong>Wasted CPU cycles</strong> — in high-throughput middleware, that adds up</li></ul><blockquote>When the signature is in place, <strong>skip the JWT</strong>.<br>It’s not just unnecessary — it’s <strong>bad cryptographic hygiene</strong>.</blockquote><h3>Conclusion</h3><p>Digital signature validation isn’t new. It’s been powering secure systems for decades.</p><p>And for good reason.</p><p>With <strong>public-private key signatures</strong>, you get:</p><ul><li><strong>Authenticity</strong> — only the real channel can generate a valid signature.</li><li><strong>Integrity</strong> — if even a comma changes in the payload, the signature breaks.</li><li><strong>Non-repudiation</strong> — channels can’t deny sending the request later.</li><li><strong>Confidentiality</strong> — handled cleanly by mutual TLS (mTLS) at the transport layer.</li></ul><p>In contrast, <strong>JWT (especially HMAC-based JWT)</strong>:</p><ul><li>Validates a token, <strong>not the actual payload</strong>.</li><li>Requires <strong>manual claim comparisons</strong> to catch tampering.</li><li>Can pass even when critical fields are <strong>empty or missing</strong>, if your code doesn’t catch it.</li><li>Adds <strong>more code, more config, more room for mistakes</strong> — and still doesn’t offer non-repudiation.</li></ul><p>And if you <strong>add JWT on top of signature</strong>, hoping to get the “best of both”?<br>You’re just introducing complexity and redundancies without any added benefits.</p><p>Middleware needs <strong>trust</strong>, <strong>performance</strong>, and <strong>clarity</strong>. Not layered complexity.</p><blockquote>As Micheal Scott <strong>might</strong> say:</blockquote><blockquote>“Sometimes I start a security design, and I don’t even know where it’s going. I just hope I find it along the way.”</blockquote><blockquote>Don’t be like him.<br>Keep it simple. Keep it strong.</blockquote><blockquote><strong>Sign the payload. Verify the signature. And move on with confidence.</strong></blockquote><h3>Socials</h3><ul><li>You can explore the full working code and run both setups yourself in this demo project:</li><li><strong>GitHub: </strong><a href="https://github.com/kengatimu/signature-vs-jwt-demo">signature-vs-jwt-demo</a></li><li>I’ll also be sharing thoughts and updates on <strong>LinkedIn</strong>.</li><li>If this post helped or sparked ideas, feel free to <a href="https://www.linkedin.com/in/kengatimu/">connect or follow me there.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edf257d9cf98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot: Safe Database Updates in Multi-Threaded Environments]]></title>
            <link>https://kengatimu.medium.com/spring-boot-safe-database-updates-in-multi-threaded-environments-22129002aa32?source=rss-143b4d0b9a2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/22129002aa32</guid>
            <dc:creator><![CDATA[Ken Gatimu]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 18:09:26 GMT</pubDate>
            <atom:updated>2025-04-26T18:16:28.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Safe Database Updates in Multi-Threaded Environments" src="https://cdn-images-1.medium.com/max/1024/1*3FXqx_fIa3otq53CMUi71A.png" /></figure><h3>Introduction</h3><p>Have you ever seen your application work <strong>perfectly in</strong> <strong>development</strong> — <br> only for strange things to happen once it hits <strong>production?</strong></p><ul><li>Missing records</li><li>Half-saved updates</li><li>Transactions that sometimes fail under load</li><li>Slow, unpredictable database behavior</li></ul><p>You’re not alone.<br> Most systems start simple, one request comes in, we save it, we commit, and everything works neatly.</p><p>But as traffic grows, and we introduce <strong>multithreading</strong> and <strong>async processing</strong> to scale — <br>things begin to break in ways we didn’t expect.</p><p>You might lean on <strong>@Transactional</strong>, hoping it will shield your data.And sometimes it does — but not always.</p><p>In this article, we’ll explore:</p><ul><li>What <strong>@Transactional</strong> actually protects — and where it <strong>silently fails</strong></li><li>How <strong>threads</strong> and <strong>async</strong> operations change database behavior</li><li>How to <strong>safely</strong> manage updates even when multithreading gets involved</li><li>How <strong>TransactionTemplate</strong> saves the day when <strong>@Transactional</strong> isn’t enough</li></ul><p>This <strong>isn’t theory</strong> — I’ll show you real-world examples from a project I built to solve exactly these problems.</p><p>You can check it out here: <a href="https://github.com/kengatimu/safe-async-db-updates">Safe Async Database Updates — GitHub</a>.</p><p>Let’s jump in.</p><h3>What is @Transactional?</h3><p>In simple terms, <strong>@Transactional,</strong> is a promise you make with the database:</p><blockquote>“<strong>Either</strong> all the operations inside this method <strong>succeed</strong> — or <strong>none</strong> of them do.”</blockquote><p>Spring Boot manages this for you automatically, without requiring manual calls to start, commit, or rollback a transaction.</p><p>When you add <strong>@Transactional,</strong> to a method:</p><ul><li>Spring opens a new database transaction when the method starts.</li><li>It runs all the database operations inside that transaction.</li><li>If the method finishes normally, Spring commits the transaction.</li><li>If an exception occurs, Spring rolls back the transaction, discarding all changes.</li></ul><blockquote>This keeps your database in a <strong>safe, consistent state</strong>.</blockquote><h3>@Transactional vs @Transactional(readOnly = true)</h3><p>While <strong>@Transactional</strong>, covers both <strong>read </strong>and <strong>write</strong> operations, Spring also gives you a way to optimize <strong>pure read </strong>methods with <strong>@Transactional(readOnly = true).</strong></p><h4>@Transactional (default)</h4><p>When you use <strong>@Transactiona</strong>l by itself, Spring assumes your method might perform database changes — <strong>inserts, updates, or deletes</strong>.<br>This means:</p><ul><li>It tracks all changes made inside the persistence context.</li><li>It ensures that, when committing, any dirty changes are flushed to the database.</li></ul><p><strong>Example:</strong></p><pre>@Override<br>@Transactional<br>public void saveInitialCreditTransferEntity(String rrn, TransactionDetails entity) throws CustomException {<br>    transactionDetailsRepository.saveAndFlush(entity);<br>}</pre><blockquote><strong>Quick Note: </strong>Why I am using <strong>saveAndFlush</strong> Instead of <strong>save.</strong></blockquote><blockquote>In <strong>critical</strong> systems, you want to catch errors as early as possible.</blockquote><blockquote>While <strong>save</strong> delays writing to the database until later, <strong>saveAndFlush</strong> forces an immediate write — validating constraints and surfacing any failures right inside the method.</blockquote><blockquote>This is important because it:</blockquote><blockquote>— Catches errors early while the transaction is still active</blockquote><blockquote>— Makes rollbacks clean and predictable</blockquote><blockquote>— Breaks the thread immediately if an exception occurs</blockquote><blockquote>— Prevents delayed failures that are harder to trace</blockquote><blockquote>Whenever you need <strong>fast failure detection</strong>, especially in sensitive transactions, it’s <strong>safer</strong> to <strong>flush</strong> changes immediately.</blockquote><h4>@Transactional(readOnly = true)</h4><p>Sometimes, you only need to <strong>read </strong>data — no updates, no inserts, no deletes.</p><p>In those cases, setting <strong>readOnly = true</strong> helps Spring and the database optimize:</p><ul><li>Avoids unnecessary flushing of the persistence context.</li><li>Can reduce database locking overhead.</li><li>Slightly improves performance for heavy read operations.</li></ul><p><strong>Example:</strong></p><pre>@Override<br>@Transactional(readOnly = true)<br>public TransactionDetails getSavedRecord(String rrn, TransactionType type) {<br>    return transactionDetailsRepository.findByRrnAndTransactionType(rrn, type).orElse(null);<br>}</pre><blockquote>Because this method <strong>only fetches </strong>data, marking it <strong>readOnly = true</strong> allows Spring to optimize the transaction under the hood.</blockquote><h4>Quick Tip: Use @Transactional Only at Method Level</h4><p>While <strong>@Transactional</strong> is powerful, it’s best to annotate individual methods, not the entire class.</p><p>Placing it at the class level forces <strong>every method</strong>, even <strong>non-database</strong> ones, to run inside a transaction — causing unnecessary overhead and making your code harder to maintain.</p><p>Instead:</p><ul><li>Only annotate the methods that actually need database transactions.</li><li>Keep non-transactional methods clean and fast.</li></ul><blockquote>This keeps your service <strong>lightweight, efficient, and easy</strong> to manage.</blockquote><h3>How to Safely Update the Database in Async Mode</h3><p>In real-world systems, backend applications need to handle <strong>many users at the same time</strong>.</p><p>We achieve this through <strong>multithreading</strong> and <strong>asynchronous processing</strong> — running tasks in <strong>parallel</strong> and moving <strong>without blocking</strong>.</p><p>But when it comes to <strong>saving into the database</strong>, multithreading and async introduce a big risk:</p><blockquote>“The normal <strong>@Transactional </strong>protection can quietly fail.&quot;</blockquote><p><strong>Why?<br></strong>Because Spring manages transactions through <strong>proxies</strong>, and once you break into a new thread, Spring <strong>loses control</strong> of the transaction.</p><p>What is a <strong>proxy</strong>, you might ask:</p><blockquote>In Spring Boot, a <strong>proxy</strong> is a middleman object that sits between your code and the real method.</blockquote><blockquote>When you call a method like <strong>@Transactional,</strong> you’re actually calling the proxy first — and the proxy decides to start, commit, or rollback the database transaction.</blockquote><blockquote>If you call the method <strong>internally in the same class</strong>, or run it inside <strong>a new thread</strong>, you <strong>bypass</strong> the proxy — and Spring <strong>cannot manage the transaction</strong> anymore.</blockquote><blockquote>That’s why <strong>async</strong> or <strong>self-calls</strong> can silently break <strong>@Transactional,</strong></blockquote><h3>TransactionTemplate</h3><p>When <strong>@Transactional,</strong> is no longer reliable in async operations, we need a way to <strong>manually</strong> control database transactions.</p><p>That’s where <strong>TransactionTemplate</strong> comes in.</p><ul><li>It allows you to <strong>explicitly start, commit, or rollback</strong> a transaction inside any thread.</li><li>It gives you full control even when Spring’s automatic transaction management is not available.</li></ul><p>In simple terms:</p><blockquote>“<strong>TransactionTemplate</strong> is your manual gearbox when automatic gears (<strong>@Transactional</strong>) stop working.”</blockquote><h3>TransactionTemplate Configuration</h3><p>Before you can use it, you configure <strong>TransactionTemplate</strong> as a <strong>bean</strong>:</p><pre>@Configuration<br>public class TransactionTemplateConfig {<br><br>    // Provide a TransactionTemplate bean for manual transaction management<br>    @Bean(name = &quot;Transactional&quot;)<br>    public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {<br>        return new TransactionTemplate(transactionManager);<br>    }<br>}</pre><blockquote>This gives you a ready-to-use <strong>TransactionTemplate</strong> that can be injected anywhere.</blockquote><h3>TaskExecutor And Its Role In Background Threads</h3><p>Often, after processing a request, we still need to update the database.<br> But waiting for those updates to finish can slow down the user experience. Instead, we want to:</p><ul><li>Receive the request</li><li>Respond quickly to the user</li><li>Handle the heavy database update quietly in the background</li></ul><p>To do this cleanly, we need a <strong>TaskExecutor</strong>.</p><ul><li>It <strong>creates new threads</strong> to handle background work.</li><li>It <strong>keeps the main request fast</strong> by moving heavy tasks outside.</li><li>It <strong>manages threads efficiently</strong> using a thread pool — so we don’t crash the server under load.</li></ul><h4>Setting Up the TaskExecutor</h4><p>Before we can run background tasks, we need to configure a <strong>TaskExecutor</strong>.</p><blockquote><strong>Please Note: </strong>In real-world production systems, async processing isn’t just about creating threads — You also need to handle what happens when:</blockquote><blockquote>— Too many tasks are submitted at once</blockquote><blockquote>— Some background tasks fail with uncaught exceptions</blockquote><p>So in our project, we configure a strong and <strong>safe TaskExecutor:</strong></p><pre>@Configuration<br>@EnableAsync<br>public class AsyncConfigs implements AsyncConfigurer {<br>    private static final Logger log = LoggerFactory.getLogger(AsyncConfigs.class);<br><br>    // Provide a custom ThreadPoolTaskExecutor for @Async methods<br>    @Override<br>    @Bean(name = &quot;taskExecutor&quot;)<br>    @Primary<br>    public TaskExecutor getAsyncExecutor() {<br>        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();<br><br>        executor.setCorePoolSize(50); // Number of threads to keep in the pool<br>        executor.setMaxPoolSize(150); // Maximum number of allowed threads<br>        executor.setQueueCapacity(10000); // Size of the queue before rejecting tasks<br>        executor.setKeepAliveSeconds(60); // Time to keep idle threads alive<br>        executor.setThreadNamePrefix(&quot;AsyncExecutor-&quot;); // Prefix for thread names<br><br>        // Custom handler for rejected tasks<br>        executor.setRejectedExecutionHandler((r, ex) -&gt; {<br>            log.error(&quot;Task rejected from AsyncExecutor: {}&quot;, r.toString());<br>            throw new RejectedExecutionException(&quot;Task rejected due to overload: &quot; + ex);<br>        });<br><br>        // Ensure graceful shutdown<br>        executor.setWaitForTasksToCompleteOnShutdown(true);<br>        executor.setAwaitTerminationSeconds(60);<br><br>        executor.initialize();<br>        return executor;<br>    }<br><br>    // Provide custom exception handling for uncaught async errors<br>    @Override<br>    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {<br>        return (throwable, method, params) -&gt; log.error(<br>                &quot;Uncaught async error in method &#39;{}&#39; with params {}: {}&quot;,<br>                method.getName(),<br>                Arrays.toString(params),<br>                throwable.getMessage(),<br>                throwable<br>        );<br>    }<br>}</pre><p>What this configuration handles:</p><ul><li><strong>Normal async thread management</strong> (thread pool size, queue size, etc.)</li><li><strong>Rejected tasks</strong>: If the server is too busy, rejected tasks are logged and handled safely.</li><li><strong>Uncaught async exceptions</strong>: Any unexpected errors inside async methods are logged properly.</li></ul><blockquote>This makes the application more <strong>resilient</strong> even under <strong>high traffic</strong>.</blockquote><h3>Setting Up the Background Database Update</h3><p>After processing the incoming request, we update the database <strong>asynchronously</strong>, using the <strong>TaskExecutor</strong>, like this:</p><pre>@Override<br>public void updateDbStatus(String rrn, TransactionResponse response, TransactionType type) {<br>    taskExecutor.execute(() -&gt; {<br>        try {<br>            TransactionDetails entity = transactionMapperService.composeErrorStatusEntity(rrn, response, type);<br>            if (entity != null) {<br>                log.info(&quot;{}: Updating Database Status For Record With RRN: {}&quot;, rrn, rrn);<br>                databaseService.updateTransactionRecord(rrn, entity);<br>            } else {<br>                log.warn(&quot;{}: TransactionDetails Entity is null, skipping database update&quot;, rrn);<br>            }<br>        } catch (Exception e) {<br>            log.error(&quot;{}: Failed to update database record asynchronously. Error: {}&quot;, rrn, e.getMessage());<br>        }<br>    });<br>}</pre><p>In this method:</p><ul><li><strong>taskExecutor.execute()</strong> creates a new thread to perform the background task.</li><li>Inside the thread:</li></ul><p>— We prepare an updated <strong>TransactionDetails </strong>entity.</p><p>— Then call <strong>databaseService.updateTransactionRecord() </strong>to <strong>safely</strong> save to the database.</p><ul><li>Any exceptions are caught and logged without affecting the main request.</li></ul><blockquote>This setup ensures:</blockquote><blockquote><strong>— Fast user response</strong> (no blocking)</blockquote><blockquote><strong>— Safe database update</strong> (even when traffic is high)</blockquote><blockquote><strong>— Better performance</strong> (using controlled multithreading)</blockquote><h3><strong>TransactionTemplate And </strong>Background Thread</h3><p>Once we are inside the <strong>background</strong> thread, we <strong>can’t rely on</strong> <strong>@Transactional</strong> anymore.</p><p>Spring&#39;s transaction management <strong>won&#39;t</strong> catch us here — we’re outside the <strong>proxy</strong>.</p><p>If we just called <strong>save() </strong>blindly inside the thread, we would:</p><ul><li>Risk saving without a real transaction</li><li>Risk partial updates</li><li>Risk silent data corruption</li></ul><p>That’s why we use <strong>TransactionTemplate</strong> to manually manage the transaction.</p><p>Here’s how the database update is <strong>safely</strong> handled:</p><pre>@Override<br>public void updateTransactionRecord(String rrn, TransactionDetails entity) {<br>    try {<br>        transactionTemplate.executeWithoutResult(status -&gt; {<br>            transactionDetailsRepository.save(entity);<br>        });<br>        log.info(&quot;{}: Transaction updated successfully.&quot;, rrn);<br>    } catch (Exception e) {<br>        log.error(&quot;{}: Failed to update transaction record. Exception: {}&quot;, rrn, e.getMessage());<br>    }<br>}</pre><p>What’s happening here:</p><ul><li><strong>transactionTemplate.executeWithoutResult()</strong> starts a new database transaction manually.</li><li>Inside the transaction, we <strong>save</strong> the updated entity.</li><li>If anything goes wrong (exception inside lambda):</li></ul><p>— Spring <strong>automatically rolls back</strong> the transaction.</p><p>— If successful, Spring <strong>commits</strong> the changes safely.</p><h3>Bonus: Cleaning Up Async Threads Properly</h3><p>Background threads are powerful — but if not managed well, they can create big <strong>problems</strong> like:</p><ul><li>Zombie threads (wasting memory)</li><li>Task rejections (when too many tasks flood in)</li><li>Silent crashes (uncaught exceptions disappearing)</li></ul><p>To avoid these risks, we set up <strong>extra protections</strong> inside the <strong>AsyncConfigs</strong> class:</p><p><strong>Graceful shutdown</strong>:<br>We used <strong>setWaitForTasksToCompleteOnShutdown(true)</strong> to make sure all background tasks finish properly before the server shuts down.</p><p><strong>Task rejection handling</strong>:<br>We added a custom <strong>RejectedExecutionHandler</strong> to catch and log any rejected tasks when the thread pool gets full.</p><p><strong>Exception safety</strong>:<br>We configured an <strong>AsyncUncaughtExceptionHandler</strong> to log any unexpected errors inside async methods — no silent failures.</p><blockquote>Refer this to the <strong>TaskExecutor class </strong>where<strong>, </strong>all of this is neatly handled inside the same AsyncConfigs configuration — making the async system safe, reliable, and production-ready.</blockquote><h3>Conclusion</h3><p>We started with a simple but real-world challenge:<br>How do you <strong>safely update the database</strong> when your application runs background tasks and <strong>multiple threads?</strong></p><p>Here’s what we learned:</p><ul><li><strong>@Transactional</strong> alone isn’t enough once you move into a new thread.</li><li><strong>Async</strong> operations <strong>break</strong> the normal transaction handling in Spring Boot.</li><li><strong>Background</strong> threads must be managed properly to avoid hidden risks like task loss and silent failures.</li></ul><p>Instead of hoping for the best, we built a clean and reliable approach:</p><ul><li>We used <strong>TransactionTemplate</strong> to manually control transactions inside <strong>async</strong> tasks.</li><li>We configured a <strong>strong TaskExecutor</strong> to handle background work efficiently and safely.</li><li>We added <strong>protections</strong> against rejected tasks and <strong>uncaught exceptions</strong> inside the <strong>AsyncConfigs</strong> class.</li></ul><p>Now you have a simple but powerful pattern:</p><ul><li>Keep your applications fast and responsive</li><li>Protect your database even under high traffic</li><li>Scale safely with multithreading and async processing</li></ul><p>If you want to explore the full project, the complete code is available here:<br><a href="https://github.com/kengatimu/safe-async-db-updates">GitHub Repository — Safe Async DB Updates</a></p><p><strong>Thanks for reading. Happy building!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22129002aa32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTPS 101: Securing Microservice Communication with TLS 1.2]]></title>
            <link>https://kengatimu.medium.com/https-101-securing-microservice-communication-with-tls-1-2-2fa75ba9b133?source=rss-143b4d0b9a2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fa75ba9b133</guid>
            <dc:creator><![CDATA[Ken Gatimu]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 13:33:32 GMT</pubDate>
            <atom:updated>2025-04-15T13:07:33.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPqXgXpYKmYtTqbJcohPcA.png" /></figure><h3>Introduction</h3><p>Let’s be honest — HTTPS is one of those things most developers “use,” but few deeply understand. For many backend engineers (my past self included), it’s just something that magically “makes your API secure.”</p><p>But what really happens when your service hits an HTTPS endpoint?</p><p>What is <strong>TLS 1.2 </strong>doing under the hood?</p><p>And how do you set it up properly in Java — without running into scary SSL errors?</p><p>In this article, we break down HTTPS and TLS 1.2 from a backend engineer’s point of view.</p><p>We’ll walk step-by-step through the TLS handshake, explain how to generate and configure certificates using OpenSSL, and implement a working mutual TLS (mTLS) setup in Java (Spring Boot) — using a real-world example.</p><p>You’ll see how an <strong>OmniChannelClientService</strong> (OMNI) makes a secure call to a <strong>TransactionProcessorGatewayService</strong> (TPGS) over HTTPS, exchanging a JSON request and response — just like real services do in production.</p><p>Here’s the setup we’ll build, step by step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TjipL7pVJmlXq40tEgtWHQ.jpeg" /></figure><h3>What Is HTTPS and TLS?</h3><h3>HTTPS:</h3><p>HTTPS stands for HyperText Transfer Protocol Secure.</p><p>It’s just HTTP (the protocol used by web services to send/receive data) wrapped in a layer of encryption using TLS.</p><p>The “S” in HTTPS means that everything transmitted between client and server is encrypted and authenticated — no one in the middle can snoop or tamper with it.</p><h3>TLS:</h3><p>TLS (Transport Layer Security) is the protocol that does the actual encryption behind HTTPS.</p><p>When someone says “HTTPS,” what they really mean is “HTTP over TLS.”</p><p>TLS ensures:</p><ol><li><strong>Authentication:</strong> Are you really talking to the server you think you are</li><li><strong>Confidentiality:</strong> Can anyone read your data in transit? (Answer: nope.)</li><li><strong>Integrity: </strong>Has the data been modified or corrupted? (Also nope.)</li></ol><p><strong>NOTE:</strong></p><p>TLS Does <strong>NOT</strong> Handle <strong>Authorization:</strong></p><p>TLS ensures that communication is secure and authenticated, but it doesn’t decide what you’re allowed to do once the connection is established.</p><p>That’s handled at the <strong>application level </strong>— typically using tokens, sessions, roles, or other access control mechanisms.</p><h3>Where SSL Comes In</h3><p>You might still hear about <strong>SSL (Secure Sockets Layer) </strong>— that’s the <strong>older</strong> version of TLS.</p><p>SSL is <strong>deprecated</strong> and no longer secure.</p><p>Today, we use <strong>TLS 1.2 or TLS 1.3</strong> (depending on the system).</p><p>Despite this, people (and even error logs) often still say “SSL” when they mean “TLS.”</p><h3>How HTTPS Works (Simplified Flow with Mutual TLS)</h3><p>Here’s a breakdown of what happens under the hood when the <strong>client (OmniChannelClientService)</strong> connects securely to the <strong>server (TransactionProcessorGatewayService) </strong>using HTTPS with TLS 1.2 and mutual authentication.</p><h4>Here is a simple setup: From start to secure:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svO8fiuBYIHF-zReFbtKhw.jpeg" /></figure><h4>Step 1: TLS Handshake Begins: ClientHello</h4><p>The handshake starts when the <strong>client (OmniChannelClientService) </strong>sends a <strong>ClientHello</strong> message to the server.</p><p>This message includes:</p><ul><li>The TLS version(s) it supports (e.g., TLS 1.2, TLS 1.3)</li><li>A list of preferred cipher suites (encryption algorithms)</li><li>A random number (used later in session key generation)</li></ul><p>This message sets the stage for negotiation — the server will choose the best mutually supported options from this list.</p><blockquote><strong>Client → Server:</strong> “Hi, I’d like to establish a secure connection. Here’s what I support.”</blockquote><h4>Step 2: Server Responds — ServerHello + Certificate</h4><p>After receiving the ClientHello, the <strong>server (TransactionProcessorGatewayService) </strong>replies with a <strong>ServerHello</strong> message, indicating how it wants to proceed.</p><p>This response includes:</p><ul><li>The TLS version it has selected (e.g., TLS 1.2)</li><li>The chosen cipher suite for encryption</li><li>Its X.509 certificate, which contains:</li></ul><p>— The server’s public key</p><p>— The server’s identity (e.g., CN=<a href="http://transaction-gateway.com/">transaction-gateway.com</a>)</p><p>— Details about the Certificate Authority (CA) that issued the certificate</p><p>This is the server’s way of saying: “I’m ready to talk securely — here’s proof of who I am.”</p><blockquote><strong>Server → Client:</strong> “Let’s use TLS 1.2 with this cipher suite. Here’s my certificate so you can verify who I am.”</blockquote><h4>Step 3: Client Verifies the Server’s Certificate</h4><p>Once the server responds, the client (OmniChannelClientService) needs to decide whether it can trust the server’s identity.</p><p>It does this by performing several checks using its truststore:</p><ul><li><strong>Is the certificate valid?</strong> <em>Not expired, properly formatted, and within its valid date range</em></li><li><strong>Is the certificate signed by a trusted Certificate Authority (CA)?</strong> <em>The client uses its truststore to check if the issuing CA is trusted</em></li><li><strong>Does the domain name match?</strong> <em>If the client is calling </em><a href="https://transaction-gateway.company.com/"><em>https://transaction-gateway.com</em></a><em>, the certificate must be issued to </em><a href="http://transaction-gateway.com/"><em>transaction-gateway.com</em></a><em> domain (via the Common Name (CN) or Subject Alternative Name (SAN) fields)</em></li></ul><p>This domain check helps <strong>protect</strong> against <strong>man-in-the-middle attack</strong>s by ensuring the client is talking to the intended server.</p><p>If any of these checks fail, the handshake is immediately aborted, and the connection is rejected.</p><blockquote><strong>Client → (internally): </strong>“Can I trust this server? Is this really who they claim to be?”</blockquote><h4>Step 4: Client Sends Its Own Certificate (Mutual TLS)</h4><p>In a mutual TLS setup, both parties must authenticate each other — so now it’s the client’s turn to prove its identity.</p><p>The client presents its certificate, which is retrieved from its keystore, and contains:</p><ul><li>The client’s identity (e.g., CN=<a href="http://omnichannel-client.com/">omnichannel-client.com</a>)</li><li>The client’s public key</li><li>A digital signature from a trusted Certificate Authority (CA) — this could be an internal enterprise CA or an external one.</li></ul><p>This step only happens in mutual TLS (mTLS). In regular HTTPS, the client doesn’t send a certificate — only the server does.</p><blockquote><strong>Client → Server: </strong>“Here’s my certificate. You can verify me now.”</blockquote><h4>Step 5: Server Verifies Client’s Certificate</h4><p>In a mutual TLS setup, the server is responsible for validating the client’s identity.</p><p>To do this, it uses its truststore to:</p><ul><li>Check if the client certificate is trusted (i.e., signed by a known Certificate Authority)</li><li>Validate the certificate chain (ensures intermediate and root certs are in place)</li><li>Confirm the certificate is valid (not expired or not yet valid)</li></ul><p>If all checks pass, the client is considered authenticated, and the handshake continues.</p><p>If any check fails, the server terminates the connection and the handshake is aborted.</p><blockquote>This step ensures that only authorized clients (presenting valid, trusted certificates) can establish a secure connection to the server.</blockquote><h4>Step 6: Key Exchange and Session Key Generation</h4><p>Once both parties have verified each other’s certificates, they move on to generating a shared secret that will be used to encrypt the actual data.</p><p>The client and server use asymmetric cryptography (typically ECDHE or RSA) during the handshake phase.</p><p>They negotiate a shared session key — this is the key both sides will use for encryption and decryption.</p><p>After the session key is established, the communication switches to symmetric encryption, which is much faster and efficient for transmitting data.</p><blockquote><strong>Think of it this way: </strong>public/private key cryptography is used just to agree on a secret. The secret itself (session key) is then used to secure the conversation.</blockquote><h4>Step 7: Secure Tunnel Established — HTTPS Communication Begins</h4><p>At this point, both the client and server have:</p><ul><li>Successfully verified each other’s identities</li><li>Agreed on a shared session key</li><li>Switched to symmetric encryption</li></ul><p>Now, the TLS handshake is complete and a secure communication channel is established.</p><p>This is where the “S” in HTTPS finally kicks in — ensuring your sensitive data travels through a trusted, encrypted tunnel.</p><p>From here on:</p><ul><li>JSON (am using json in this example) requests and responses are transmitted securely</li><li>No one can read or tamper with the data in transit (even if intercepted)</li><li>Session integrity and confidentiality are fully enforced by TLS</li></ul><blockquote>All traffic between Client (OmniChannelClientService) and Server (TransactionProcessorGatewayService) is now encrypted.</blockquote><h3>Understanding Keystore vs Truststore</h3><p>Before diving into java implementation of HTTPS, Let us first understand what is a keystore and a truststore.</p><p>When working with HTTPS and TLS in Java, two terms keep popping up: keystore and truststore. They might sound similar (and even use the same file formats), but they play very different roles in securing communication between systems.</p><p>Let’s break it down clearly.</p><h3>Keystore – Your Identity and Private Keys</h3><p>A keystore is a secure file (typically .jks or .p12) that holds your application&#39;s credentials — specifically:</p><ul><li>Your private key (used to prove who you are)</li><li>Your public certificate (shared with others to verify your identity)</li><li>Optionally, the certificate chain (intermediate and root certs)</li></ul><p>In HTTPS:</p><ul><li>The server uses a keystore to present its identity to clients.</li><li>If you’re using mutual TLS (mTLS), the client will also have its own keystore.</li></ul><blockquote>Think of the keystore as your digital passport — it proves you are who you say you are.</blockquote><h3>Truststore – Who You Trust</h3><p>A truststore is also a secure file, but it plays the opposite role of a keystore.</p><p>It contains public certificates of other systems you trust, such as:</p><ul><li>Certificate Authorities (CAs)</li><li>External services you call</li><li>Client certificates (in case of mTLS)</li></ul><p>In HTTPS:</p><ul><li>The client uses a truststore to verify the server’s certificate.</li><li>The server (in mutual TLS) uses a truststore to verify the client’s certificate.</li></ul><blockquote>Think of the truststore as your trusted contacts list — you only communicate securely with people you’ve added here.</blockquote><h3>In the Java World</h3><p>Both keystores and truststores are essential when building secure Spring Boot applications. Java expects them in standard formats like:</p><ul><li>.jks – Java KeyStore (default)</li><li>.p12 or .pfx – PKCS#12 (modern, widely used)</li></ul><p>These are plugged into your application via configuration to enable HTTPS, TLS, and mutual TLS connections.</p><h3>Backend Implementation Using Java (Real Use Case)</h3><p>Now that we’ve walked through the TLS handshake conceptually, and learned the difference between keystore and truststore, let’s implement it in a Java Spring Boot backend setup using OpenSSL and Java-compatible formats.</p><p>We’re securing communication between two microservices:</p><ul><li>OmniChannelClientService → initiates the HTTPS call</li><li>TransactionProcessorGatewayService → receives the call over HTTPS using TLS 1.2</li></ul><p>We’ll use OpenSSL to generate certificates and keys in a proper, scalable way, then convert them into a .p12 keystore that Spring Boot understands (.p12 or .jks) using openssl pkcs12 and keytool.</p><h3>Setup Overview</h3><p>What You Need:</p><ul><li>A private key and certificate for each service</li><li>A keystore (containing private key + certificate) for the server (and client in mTLS)</li><li>A truststore (containing trusted certs/CA) for both parties</li></ul><h3>Certificate Creation with OpenSSL (Server Side)</h3><h4>Step 1: CSR Generation (with metadata)</h4><p>First, generate a<strong> private key</strong> and <strong>create a Certificate Signing Request </strong>(CSR) with meaningful subject information:</p><pre>openssl req -newkey rsa:2048 -nodes \<br>  -keyout server.key \<br>  -out server.csr \<br>  -subj &quot;/C=KE/ST=Nairobi/L=Nairobi/O=Transaction Gateway Limited/OU=TPGS/CN=transaction-gateway.com/emailAddress=info@tpgs.com&quot;</pre><ul><li><strong>server.key</strong> → your server’s private key</li><li><strong>server.csr</strong> → certificate request to be self-signed or sent to a CA</li></ul><h4>Step 2: Self-sign the CSR (10-year validity)</h4><p>We’ll self-sign the CSR to generate a certificate valid for 10 years, otherwise send the CSR to a valid CA for signing:</p><pre>openssl x509 -req \<br>  -in server.csr \<br>  -signkey server.key \<br>  -out server.pem \<br>  -days 3650</pre><ul><li><strong>server.pem </strong>→ self-signed certificate containing the public key and metadata</li></ul><h4>Step 3: Convert to a PKCS#12 Keystore (.p12)</h4><p>Java doesn’t use .<strong>pem</strong> and <strong>.key</strong> files directly — it expects them in PKCS#12 format:</p><pre>openssl pkcs12 -export \<br>  -in server.pem \<br>  -inkey server.key \<br>  -out server.p12 \<br>  -name server \<br>  -password pass:changeit</pre><ul><li><strong>server.p12</strong> now contains both the private key and the certificate, ready to be used as a Spring Boot keystore</li></ul><h4>Step 4: Truststore for the Client (OmniChannelClientService)</h4><p>To allow the OmniChannelClientService to trust the secure server (TransactionProcessorGatewayService), we need to import the server’s certificate into the client’s Java truststore.</p><p>The server certificate can be optained in either of below options:</p><h4>Option A: Server Shares the Certificate (Preferred)</h4><p>If the server provides the <strong>.crt </strong>or <strong>.pem</strong> file (usually named something like<strong> server.crt</strong> or <strong>server.pem</strong>), you can directly import it into a truststore using keytool.</p><h4>Option B: Extract the Certificate Yourself Using OpenSSL</h4><p>If the certificate isn’t shared, you can extract it from the running HTTPS server:</p><pre>openssl s_client -connect transaction-gateway.com:9443 -showcerts</pre><p>Copy the certificate content from:</p><pre>-----BEGIN CERTIFICATE-----<br>...<br>-----END CERTIFICATE-----</pre><p>Paste and save it as<strong> server.crt</strong> or<strong> server.pem</strong></p><h4>Import the Server Certificate into a Truststore (.jks format)</h4><pre>keytool -importcert \<br>  -alias transaction-gateway-cert \<br>  -file server.pem \<br>  -keystore client-truststore.jks \<br>  -storepass changeit \<br>  -noprompt</pre><blockquote>This creates a truststore file (.jks) that tells the client: “I trust any server using the certificate identified by this alias.”</blockquote><h4>Convert the Truststore from .jks to .p12 (optional but recommended)</h4><p>Many Spring Boot apps now prefer or require PKCS#12 (.p12) format instead of the legacy .jks.</p><p>Convert the .jks to .p12 using the following command:</p><pre>keytool -importkeystore \<br>  -srckeystore client-truststore.jks \<br>  -destkeystore client-truststore.p12 \<br>  -srcstoretype JKS \<br>  -deststoretype PKCS12 \<br>  -srcstorepass changeit \<br>  -deststorepass changeit</pre><blockquote><strong>client-truststore.p12</strong> can now be used directly in your Spring Boot configuration.</blockquote><h3>Certificate Creation with OpenSSL (Client Side)</h3><p>If you want mutual TLS, repeat the same steps for the client:</p><ul><li>Generate client.csr with metadata</li><li>Self sign the csr or send it to a valid CA for signing</li><li>Export to client-keystore.p12</li><li>Create server-truststore.jks</li><li>Convert the jks to p12 file</li></ul><h3>Secure Communication with Mutual TLS in Java (Client → Server)</h3><p>Once certificates are generated and stored in external keystores and truststores, the next step is wiring everything up in code.</p><p>In this section, we’ll configure the OmniChannelClientService to:</p><ul><li>Trust the server’s certificate</li><li>Present its own certificate for mutual authentication</li><li>Make a secure HTTPS call to <a href="https://localhost:9443/api/v1/post-request">https://localhost:9443/api/v1/post-request</a></li></ul><h3>CLIENT SIDE: OmniChannelClientService</h3><h4>Step 1: application.yml</h4><pre>server:<br>  port: 8443<br>  ssl:<br>    enabled: true<br>    key-store: /opt/config/certs/client/client.p12<br>    key-store-password: changeit<br>    key-store-type: PKCS12<br>    key-alias: client<br>    trust-store: /opt/config/certs/client/server-truststore.p12<br>    trust-store-password: changeit<br>    trust-store-type: PKCS12</pre><h4>Step 2: Configuratin class — HttpConfigs Class</h4><pre>@Configuration<br>public class HttpConfigs {<br>    private static final Logger log = LoggerFactory.getLogger(HttpConfigs.class);<br>    // Determines the timeout in milliseconds until a connection is established.<br>    private static final int CONNECT_TIMEOUT = 15000; // 15 seconds<br>    // The timeout in milliseconds for requesting a connection from the connection manager.<br>    private static final int REQUEST_TIMEOUT = 15000; // 15 seconds<br>    // The timeout in milliseconds for waiting for data from the server.<br>    private static final int SOCKET_TIMEOUT = 30000; // 30 seconds<br>    // The maximum number of total open connections managed by the connection manager.<br>    private static final int MAX_TOTAL_CONNECTIONS = 200;<br>    // The maximum number of concurrent connections per route (destination host).<br>    private static final int DEFAULT_MAX_PER_ROUTE = 50;<br>    // The default keep-alive time in milliseconds for persistent connections.<br>    private static final int DEFAULT_KEEP_ALIVE_TIME_MILLIS = 30000; // 30 seconds<br>   <br>   // Environment variables<br>    private final String keystoreLocation;<br>    private final String keystorePassword;<br>    private final String keystoreType;<br>    private final String truststoreLocation;<br>    private final String truststorePassword;<br>    private final String truststoreType;<br><br>    // Optional flag to disable hostname verification (e.g., when using IP in UAT)<br>    private final boolean skipHostnameVerification;<br>    @Autowired<br>    public HttpConfigs(@Value(&quot;${server.ssl.key-store}&quot;) String keystoreLocation,<br>                       @Value(&quot;${server.ssl.key-store-password}&quot;) String keystorePassword,<br>                       @Value(&quot;${server.ssl.key-store-type}&quot;) String keystoreType,<br>                       @Value(&quot;${server.ssl.trust-store}&quot;) String truststoreLocation,<br>                       @Value(&quot;${server.ssl.trust-store-password}&quot;) String truststorePassword,<br>                       @Value(&quot;${server.ssl.trust-store-type}&quot;) String truststoreType,<br>                       @Value(&quot;${http.ssl.skip-hostname-verification:false}&quot;) boolean skipHostnameVerification) {<br>        this.keystoreLocation = keystoreLocation;<br>        this.keystorePassword = keystorePassword;<br>        this.keystoreType = keystoreType;<br>        this.truststoreLocation = truststoreLocation;<br>        this.truststorePassword = truststorePassword;<br>        this.truststoreType = truststoreType;<br>        this.skipHostnameVerification = skipHostnameVerification;<br>    }<br>    @Bean<br>    public PoolingHttpClientConnectionManager poolingConnectionManager() {<br>        FileInputStream truststoreFis = null;<br>        FileInputStream keystoreFis = null;<br>        try {<br>            // 1. Load TRUSTSTORE (server side cert)<br>            KeyStore trustStore = KeyStore.getInstance(truststoreType);<br>            truststoreFis = new FileInputStream(truststoreLocation);<br>            trustStore.load(truststoreFis, truststorePassword.toCharArray());<br>            <br>            // 2. Load KEYSTORE (client side cert, which is stored in the keystore)<br>            KeyStore keyStore = KeyStore.getInstance(keystoreType);<br>            keystoreFis = new FileInputStream(keystoreLocation);<br>            keyStore.load(keystoreFis, keystorePassword.toCharArray());<br>            <br>            // 3. Configure SSLContext with BOTH keystore and truststore - Mutual-SSL<br>            SSLContext sslContext = SSLContexts.custom()<br>                    .loadKeyMaterial(keyStore, keystorePassword.toCharArray()) // My cert<br>                    .loadTrustMaterial(trustStore, null) // server side cert<br>                    .build();<br><br>            // Only when truststore needed - Not Mutual-SSL<br>//            SSLContext sslContext = SSLContexts.custom()<br>//                    .loadTrustMaterial(trustStore, null)<br>//                    .build();<br><br>            // 4. Configure hostname verification policy<br>            SSLConnectionSocketFactory sslConnectionFactory;<br>            if (!skipHostnameVerification) {<br>                // Enforce domain validation in production<br>                sslConnectionFactory = new SSLConnectionSocketFactory(<br>                        sslContext,<br>                        new String[]{&quot;TLSv1.2&quot;}, // Enforce TLS version 1.2<br>                        null,<br>                        new DefaultHostnameVerifier()<br>                );<br>                log.info(&quot;Hostname verification is ENABLED (recommended for production).&quot;);<br>            } else {<br>                // Optional: Disable only in UAT when using IP instead of DNS<br>                sslConnectionFactory = new SSLConnectionSocketFactory(<br>                        sslContext, NoopHostnameVerifier.INSTANCE);<br>                log.warn(&quot;Hostname verification is DISABLED (use only in UAT/IP scenarios).&quot;);<br>            }<br><br>            // 5. Register HTTP/HTTPS socket factories<br>            Registry&lt;ConnectionSocketFactory&gt; registry = RegistryBuilder<br>                    .&lt;ConnectionSocketFactory&gt;create()<br>                    .register(&quot;https&quot;, sslConnectionFactory)<br>                    .register(&quot;http&quot;, PlainConnectionSocketFactory.INSTANCE)<br>                    .build();<br><br>            // 6. Configure connection pooling<br>            PoolingHttpClientConnectionManager poolingConnectionManager =<br>                    new PoolingHttpClientConnectionManager(registry);<br>            poolingConnectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);<br>            poolingConnectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);<br>            return poolingConnectionManager;<br>        } catch (Exception e) {<br>            log.error(&quot;Error initializing SSL context&quot;, e);<br>            return new PoolingHttpClientConnectionManager(); // Fallback<br>        } finally {<br>            if (truststoreFis != null) {<br>                try {<br>                    truststoreFis.close();<br>                } catch (IOException e) {<br>                    log.error(&quot;Error closing truststore stream: {}&quot;, e.getMessage());<br>                }<br>            }<br>            if (keystoreFis != null) {<br>                try {<br>                    keystoreFis.close();<br>                } catch (IOException e) {<br>                    log.error(&quot;Error closing keystore stream: {}&quot;, e.getMessage());<br>                }<br>            }<br>        }<br>    }<br>    @Bean<br>    public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {<br>        // Configures and returns a strategy for managing the keep-alive duration of HTTP connections,<br>        // ensuring connections are kept alive for a specified period.<br>        return (HttpResponse response, HttpContext context) -&gt; {<br>            HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));<br>            while (it.hasNext()) {<br>                HeaderElement he = it.nextElement();<br>                String param = he.getName();<br>                String value = he.getValue();<br>                if (value != null &amp;&amp; param.equalsIgnoreCase(&quot;timeout&quot;)) {<br>                    return Long.parseLong(value) * 1000;<br>                }<br>            }<br>            return DEFAULT_KEEP_ALIVE_TIME_MILLIS;<br>        };<br>    }<br>    @Bean(&quot;closeableHttpClient1&quot;)<br>    public CloseableHttpClient closeableHttpClient() {<br>        RequestConfig requestConfig = RequestConfig<br>                .custom()<br>                .setConnectionRequestTimeout(REQUEST_TIMEOUT)<br>                .setConnectTimeout(CONNECT_TIMEOUT)<br>                .setSocketTimeout(SOCKET_TIMEOUT)<br>                .build();<br>        return HttpClients<br>                .custom()<br>                .setDefaultRequestConfig(requestConfig)<br>                .setConnectionManager(poolingConnectionManager())<br>                .setKeepAliveStrategy(connectionKeepAliveStrategy())<br>                .build();<br>    }<br>}</pre><h4>Step 3: Send Secure HTTPS Call — HttpServiceImpl Class</h4><pre>@Service<br>public class HttpServiceImpl {<br>    <br>    @Autowired<br>    @Qualifier(&quot;closeableHttpClient&quot;)<br>    private CloseableHttpClient httpClient;<br><br>    public String sendRequest(RequestObject requestObject) {<br>        String url = &quot;https://localhost:9443/api/v1/post-request&quot;;<br>        CloseableHttpResponse response = null;<br>        try {<br>            HttpPost post = new HttpPost(url);<br>            post.setHeader(&quot;Content-Type&quot;, &quot;application/json&quot;);<br><br>            ObjectMapper objectMapper = new ObjectMapper();<br>            String jsonPayload = objectMapper.writeValueAsString(requestObject);<br>           <br>            post.setEntity(new StringEntity(jsonPayload));<br>            response = httpClient.execute(post);<br>            return EntityUtils.toString(response.getEntity());<br>        } catch (Exception e) {<br>            return &quot;{\&quot;status\&quot;:\&quot;error\&quot;,\&quot;message\&quot;:\&quot;&quot; + e.getMessage() + &quot;\&quot;}&quot;;<br>        } finally {<br>            try {<br>                if (response != null) response.close();<br>                httpClient.close();<br>            } catch (IOException e) {<br>                // ignore<br>            }<br>        }<br>    }<br>}</pre><h4>Step 4: Web Controller — ClientController Class</h4><pre>@RestController<br>@RequestMapping(&quot;/api/v1&quot;)<br>public class ClientController {<br>      @Autowired<br>      private HttpServiceImpl httpService;<br><br>      @PostMapping(&quot;/send&quot;)<br>      public ResponseEntity&lt;?&gt; send(@RequestBody RequestObject requestObject) {<br>          Map&lt;String, Object&gt; response = new HashMap&lt;&gt;();<br>          try {<br>              String serverResponse = httpService.sendRequest(requestObject);<br>              response.put(&quot;status&quot;, &quot;success&quot;);<br>              response.put(&quot;server_response&quot;, new ObjectMapper().readValue(serverResponse, Map.class));<br>          } catch (Exception e) {<br>              response.put(&quot;status&quot;, &quot;error&quot;);<br>              response.put(&quot;message&quot;, e.getMessage());<br>          } finally {<br>              response.put(&quot;timestamp&quot;, Instant.now().toString());<br>          }<br>          return ResponseEntity.ok(response);<br>      }<br>}</pre><h3>Server Side — TransactionProcessorGatewayService</h3><h4>Step 1: application.yml</h4><pre>server:<br>  port: 9443<br>  ssl:<br>    enabled: true<br>    key-store: /opt/config/certs/server/server.p12<br>    key-store-password: changeit<br>    key-store-type: PKCS12<br>    key-alias: server<br>    trust-store: /opt/config/certs/server/client-truststore.p12<br>    trust-store-password: changeit<br>    trust-store-type: PKCS12</pre><h4>Step 2: Web Controller — RequestReceiverController</h4><pre>@RestController<br>@RequestMapping(&quot;/api/v1&quot;)<br>public class RequestReceiverController {<br><br>    @PostMapping(&quot;/post-request&quot;)<br>    public ResponseEntity&lt;?&gt; receiveRequest(@RequestBody RequestObject requestObject) {<br>        Map&lt;String, Object&gt; response = new HashMap&lt;&gt;();<br>        try {<br>            response.put(&quot;status&quot;, &quot;received&quot;);<br>            response.put(&quot;received_data&quot;, requestObject);<br>        } catch (Exception e) {<br>            response.put(&quot;status&quot;, &quot;error&quot;);<br>            response.put(&quot;message&quot;, e.getMessage());<br>        } finally {<br>            response.put(&quot;processed_at&quot;, Instant.now().toString());<br>        }<br>        return ResponseEntity.ok(response);<br>    }<br>}</pre><h3>Conclusion</h3><p>And there you have it — a fully working mutual TLS setup in Java using Spring Boot.</p><p>We didn’t just wire things blindly. We explored what HTTPS and TLS 1.2 actually do, how certificates work, and how to use OpenSSL and keytool to generate and configure your keystores and truststores. Most importantly, we built a secure, production-grade connection between two services — authenticated and encrypted end-to-end.</p><h3>What’s Next?</h3><p>In the next article, we’ll cover how to deal with common issues that arise when setting up mutual TLS, Including:</p><ul><li>Certificate validation failures</li><li>Hostname mismatches (especially when using IPs in UAT)</li><li>TLS version incompatibilities</li><li>And how to test mTLS endpoints using curl, Postman, and OpenSSL</li></ul><p>Stay tuned — or follow me to get notified when it’s live!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fa75ba9b133" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>