<?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 Lakshan sandaruwan on Medium]]></title>
        <description><![CDATA[Stories by Lakshan sandaruwan on Medium]]></description>
        <link>https://medium.com/@lakshansandaruwan1998?source=rss-7076d4a19c7c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tS2jxU3sRlPSIsBAC1ThEw@2x.jpeg</url>
            <title>Stories by Lakshan sandaruwan on Medium</title>
            <link>https://medium.com/@lakshansandaruwan1998?source=rss-7076d4a19c7c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:23:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lakshansandaruwan1998/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[Type Classes: How Scala Achieves Polymorphism Without Inheritance]]></title>
            <link>https://medium.com/@lakshansandaruwan1998/type-classes-how-scala-achieves-polymorphism-without-inheritance-7a39943ec16f?source=rss-7076d4a19c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a39943ec16f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scala-programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[typeclass]]></category>
            <dc:creator><![CDATA[Lakshan sandaruwan]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 15:58:34 GMT</pubDate>
            <atom:updated>2025-12-23T15:58:34.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SlKJv0y12p4Jy8berdZ1cQ.png" /></figure><h3>The Problem We Never Knew We Had</h3><p>Imagine you’re working with a third-party library that provides a User class. You need to add JSON serialization to it, but you can&#39;t modify the source code. Of course you can create a wrapper class or extend it, but that feels clunky and breaks existing code that expects the original type.</p><p>This is where type classes shine. They’re one of Scala’s most powerful patterns, and they’re the secret ingredient in popular libraries like Cats, Scalaz, and Circe. By the end of this article, you’ll understand how type classes work and why they might change how you think about polymorphism.</p><h3>What Inheritance can’t do</h3><p>In Traditional OOP we use inheritance for polymorphism. If we want multiple types to share behavior we create an interface or abstract class.</p><pre>trait Printable {<br>  def print: String<br>}<br><br>case class User(name: String, age: Int) extends Printable {<br>  def print: String = s&quot;User($name, $age)&quot;<br>}</pre><p>This works fine when you control the types, but is has serious limitations:</p><p><strong>You can’t add interfaces to existing types </strong>— You cannot extend Int, Boolean or a library classes from Printable.</p><p><strong>Tight coupling</strong> — With inheritance, you need to modify the class definition every time you want to add or change behavior. With type classes, you have clear separation — you don’t need to touch the class definition at all.</p><p>Type classes solve all of these problems by separating the type from the behavior.</p><h3>What are Type Classes?</h3><p>A type class is a functional programming pattern that allows you to add functionality to existing types without modifying them. Despite the name, they’re not classes in the OOP sense. Instead, a type class consists of three parts:</p><ol><li><strong>The Type Class</strong> — A trait that defines the interface</li><li><strong>Type Class Instances</strong> — Implementations for specific types</li><li><strong>Interface Methods</strong> — Ways to use the type class</li></ol><p>Let’s dive in to a simple example.</p><h3>Building Your First Type Class</h3><p>We will create a Show type class that converts values to string for display, similar to Java toString</p><p>Step 1: Define the Type Class</p><pre>trait Show[A] {<br>  def show(value: A): String<br>}</pre><p>This trait is parameterized by type A. It says &quot;for some type A, I can show it as a string.&quot;</p><p>Step 2: Create Type Class Instances</p><p>Now we create instances for the types we want to support:</p><pre>object Show {<br>  // Instance for Int<br>  implicit val intShow: Show[Int] = new Show[Int] {<br>    def show(value: Int): String = s&quot;Int: $value&quot;<br>  }<br>  <br>  // Instance for String<br>  implicit val stringShow: Show[String] = new Show[String] {<br>    def show(value: String): String = s&quot;String: &#39;$value&#39;&quot;<br>  }<br>  <br>  // Instance for custom type<br>  implicit val userShow: Show[User] = new Show[User] {<br>    def show(value: User): String = j<br>      s&quot;User(name=${value.name}, age=${value.age})&quot;<br>  }<br>}<br><br>case class User(name: String, age: Int)</pre><p>Notice the implicit keyword. This tells Scala to provide these instances automatically when needed.</p><p>Step 3: Create Interface Method</p><p>Now we need a way to actually use our type class:</p><pre>object Show {<br>  // ... instances from above ...<br>  <br>  // Interface method<br>  def show[A](value: A)(implicit shower: Show[A]): String = {<br>    shower.show(value)<br>  }<br><br>}</pre><p>Putting It All Together</p><pre>import Show._<br><br>val x: Int = 40<br>val s: String = &quot;hello&quot;<br>val u: User = User(&quot;Jon&quot;, 30)<br><br>println(Show.show(x))      // Int: 40<br>println(Show.show(s))      // String: &#39;hello&#39;<br>println(Show.show(u))      // User(name=Jon, age=30)</pre><p>The magic here is that we’ve added show functionality to Int, String and User without modifying any of them!</p><h3>The Magic of Implicits</h3><p>You might be wondering how Scala knows which Show instance to use. This is where implicit resolution comes in.</p><p>When you call Show.show(42), Scala looks for an implicit value of type Show[Int]. It searches in :</p><ul><li>The local scope</li><li>Companion objects of the type class (Show)</li><li>Companion objects of the type parameter (Int)</li></ul><p>This happens at compile time, so there’s no runtime overhead, and you get type safety for free</p><h3>Another Example: CSV Encoder</h3><p>Let’s build a simple CSV encoder that can convert any type to CSV format, So we can understand this type class pattern further.</p><pre>trait CsvEncoder[A] {<br>  def encode(value: A): String<br>}<br><br>object CsvEncoder {<br>  // Type class instances for the types<br>  implicit val intEncoder: CsvEncoder[Int] = <br>    (value: Int) =&gt; value.toString<br>  <br>  implicit val stringEncoder: CsvEncoder[String] = <br>    (value: String) =&gt; s&quot;&quot;&quot;&quot;$value&quot;&quot;&quot;&quot;  // Quote strings for CSV safety<br>  <br>  implicit val booleanEncoder: CsvEncoder[Boolean] = <br>    (value: Boolean) =&gt; value.toString<br>  <br>  implicit val longEncoder: CsvEncoder[Long] = <br>    (value: Long) =&gt; value.toString<br>  <br>  // Encoder for lists - converts to CSV rows (one per line)<br>  implicit def listEncoder[A](implicit encoder: CsvEncoder[A]): CsvEncoder[List[A]] = <br>    (values: List[A]) =&gt; values.map(encoder.encode).mkString(&quot;\n&quot;)<br>  <br>  // Encoder for custom types - these produce single CSV rows<br>  implicit val personEncoder: CsvEncoder[Person] = <br>    (person: Person) =&gt; s&quot;&quot;&quot;&quot;${person.name}&quot;,${person.age}&quot;&quot;&quot;<br>  <br>  implicit val addressEncoder: CsvEncoder[Address] = <br>    (address: Address) =&gt; s&quot;&quot;&quot;&quot;${address.street}&quot;,&quot;${address.city}&quot;&quot;&quot;&quot;<br>  <br>  // Interface method<br>  def encode[A](value: A)(implicit encoder: CsvEncoder[A]): String = <br>    encoder.encode(value)<br>  <br><br>  /** An extension method for convenient syntax<br>    * Implicit classes like these can be used to enrich existing types with our own custom methods<br>    */<br>  implicit class CsvEncoderOps[A](value: A) {<br>    def toCsv(implicit encoder: CsvEncoder[A]): String = <br>      encoder.encode(value)<br>  }<br>}<br><br>case class Person(name: String, age: Int)<br>case class Address(street: String, city: String)</pre><p>Usage:</p><pre>import CsvEncoder._<br><br>// Encoding primitives<br>println(encode(42))                  // 42<br>println(encode(&quot;hello&quot;))             // &quot;hello&quot;<br>println(encode(true))                // true<br><br>// We can also use toCsv method from CsvEncoderOps implicit class<br>println(42.toCsv)                    // 42<br>println(&quot;hello&quot;.toCsv)               // &quot;hello&quot;<br>println(true.toCsv)                  // true<br><br>// Encoding custom types<br>val person = Person(&quot;Robert&quot;, 30)<br>println(person.toCsv)                // &quot;Robert&quot;,30<br><br>val address = Address(&quot;123 High Level Rd&quot;, &quot;Maharagama&quot;)<br>println(address.toCsv)               // &quot;123 High Level Rd&quot;,&quot;Maharagama&quot;<br><br>// Encoding lists with type class composition<br>val people = List(<br>  Person(&quot;Eddard&quot;, 30),<br>  Person(&quot;Jaime&quot;, 25),<br>  Person(&quot;Jon&quot;, 35)<br>)<br>println(people.toCsv)<br>// Output: <br>// &quot;Eddard&quot;,30<br>// &quot;Jaime&quot;,25<br>// &quot;Jon&quot;,35<br><br>val numbers = List(1, 2, 3, 4, 5)<br>println(numbers.toCsv)               <br>// Output:<br>// 1<br>// 2<br>// 3<br>// 4<br>// 5</pre><p>Notice how listEncoder is itself parameterized and requires a CsvEncoder[A] to create a CsvEncoder[List[A]]. This is called type class composition, and it&#39;s incredibly powerful. The compiler automatically finds the right encoder for the list&#39;s element type and uses it to encode each element.</p><h3>Scala Libraries That Love Type Classes</h3><p>Popular Scala libraries are built on type classes:</p><ul><li><strong>Cats</strong> provides type classes for functional programming (Functor, Monad, Semigroup, etc.)</li><li><strong>Circe</strong> uses type classes for JSON encoding/decoding</li><li><strong>Http4s</strong> uses type classes for HTTP request/response handling</li><li><strong>Doobie</strong> uses type classes for database mapping</li></ul><h3>Benefits and Trade-offs</h3><h4>Benefits</h4><ol><li>Add behavior to any type, even ones you don’t own, without wrapper classes or inheritance.</li><li>Keep business logic separate from data structures. Your domain models can be simple case classes without behavior.</li><li>The compiler ensures type class instances exist at compile time. No runtime errors from missing implementations.</li><li>Multiple implementations can exist for the same type. You can have different JSON encoders for different contexts.</li><li>Type classes compose naturally. Complex behaviors build from simple ones.</li></ol><h4>Trade-offs</h4><ol><li>Type classes and implicits can be confusing for newcomers. Takes bit time to get the hang of it.</li><li>Debugging implicit resolution can be challenging. The compiler doesn’t always give clear error messages.</li><li>Defining type classes requires more boilerplate than simple inheritance.</li></ol><h3>Conclusion</h3><p>Type classes represent a fundamental shift in how we think about polymorphism. Instead of asking “what is this object?”, we ask “what can we do with this type?” This inversion leads to more flexible, extensible, and maintainable code.</p><p>The pattern takes practice to master, but once it clicks, you’ll start seeing opportunities everywhere.</p><blockquote>That third-party library that’s missing a feature? Type class. Need to add serialization without polluting your domain model? Type class. Want uniform behavior across different types? Type class.</blockquote><h3>Further Reading</h3><ul><li><a href="https://docs.scala-lang.org/scala3/book/ca-type-classes.html">Type Classes</a> — Official Scala docs for type classes</li><li><a href="https://docs.scala-lang.org/overviews/core/implicit-classes.html">Implicit classes</a> — Official Scala docs for implicit classes (Extension method syntax)</li><li><a href="https://typelevel.org/cats/">Cats Documentation</a> — The definitive guide to functional type classes</li></ul><p>Now go forth and add type classes to your code. Your future self will thank you. :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a39943ec16f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sign and Encrypt Soap Envelopes with apache wss4j in Scala]]></title>
            <link>https://medium.com/@lakshansandaruwan1998/sign-and-encrypt-soap-envelopes-with-apache-wss4j-in-scala-2b5b1f6a58c2?source=rss-7076d4a19c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b5b1f6a58c2</guid>
            <category><![CDATA[soap]]></category>
            <category><![CDATA[ws-security]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[web-services]]></category>
            <dc:creator><![CDATA[Lakshan sandaruwan]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 18:58:57 GMT</pubDate>
            <atom:updated>2025-10-31T18:58:57.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*MyBllbfeRQDtOSlyxsCtcw@2x.jpeg" /></figure><h3>Introduction</h3><p>In modern web services, security is a critical concern, especially when dealing with sensitive data. For this SOAP-based services use WS-Security (WSS) to ensure message integrity, confidentiality, and authentication.</p><p>WS-Security is an extension of SOAP that defines a standard way to secure messages using XML Signature, XML Encryption, and security tokens. In this article, we will explore how to sign and encrypt a SOAP envelopes using Apache WSS4J library in Scala. First, we’ll briefly cover how WS-Security works and then dive into the implementation.</p><h3>Understanding SOAP WS-Security</h3><p>SOAP WS-Security (WSS) is a set of security mechanisms designed to protect SOAP messages at the message level, rather than just relying on transport layer security(TLS) like HTTPS. This means that even if the message passes through multiple intermediaries, it remains protected.</p><p>Two main features of WSS are digital signature and encryption.</p><ol><li><strong>Digital Signature (Message Integrity &amp; Authenticity)</strong></li></ol><p>Digital signature ensures that the SOAP message has not been altered while sending and verify the sender’s identity.</p><p>The process works as follows:</p><ul><li>The sender signs the message using their <strong>private key</strong></li><li>The recipient verifies the signature using the sender’s <strong>public key</strong></li><li>If the signature is valid, the recipient can be confident that the message came from the claimed sender and hasn’t been tampered with</li></ul><p><strong>2. Encryption (Message Confidentiality)</strong></p><p>Encryption protects the contents of a SOAP message from unauthorized access.</p><p>Since the SOAP body can be quite large, asymmetric encryption (e.g., RSA) is not used to encrypt it directly due to performance concerns. Instead, a more efficient hybrid encryption approach is used:</p><p>1. The sender generates a random <strong>symmetric key</strong> for each request.</p><p>2.	The SOAP body is encrypted using this symmetric key with a fast encryption algorithm like AES.</p><p>3.	The symmetric key itself is then encrypted using the recipient’s public key (asymmetric encryption, e.g., RSA).</p><p>4.	The encrypted symmetric key is included in the SOAP security header, while the encrypted body remains in the message.</p><p>5.	Upon receiving the message, the recipient:</p><p>•	Decrypts the symmetric key using their private key.</p><p>•	Uses the decrypted symmetric key to decrypt the SOAP body.</p><p>This hybrid approach combines the speed of symmetric encryption with the security of asymmetric encryption.</p><p>Since now we know how SOAP WSS works, Let’s dive into the coding stuff.</p><h3>Prerequisites</h3><p>Before we begin, make sure you have:</p><ul><li>Scala (2.12 or higher)</li><li>SBT (Scala Build Tool)</li><li>Apache WSS4J library</li><li>A Java keystore containing your certificates and private keys</li></ul><p>Add the following dependencies to your build.sbt</p><pre>libraryDependencies ++= Seq(<br>  &quot;org.apache.ws.security&quot;     % &quot;wss4j&quot;                      % &quot;1.6.19&quot;,<br>  &quot;jakarta.xml.soap&quot;           % &quot;jakarta.xml.soap-api&quot;       % &quot;3.0.2&quot;,<br>  &quot;com.sun.xml.messaging.saaj&quot; % &quot;saaj-impl&quot;                  % &quot;3.0.4&quot;<br>)</pre><h3>Setting Up the Key store</h3><p>WSS4J uses Java key-stores to manage certificates and private keys. You’ll need:</p><ul><li><strong>For signing</strong>: Your private key and certificate</li><li><strong>For encryption</strong>: The recipient’s public certificate</li><li><strong>For decryption</strong>: Your private key</li><li><strong>For signature verification</strong>: The sender’s public certificate</li></ul><p>You can create a key-store for testing using the Java keytool.</p><pre># Create sender&#39;s keystore<br>keytool -genkeypair \<br>  -alias senderkey \<br>  -keyalg RSA \<br>  -keysize 2048 \<br>  -validity 365 \<br>  -keystore sender-keystore.jks \<br>  -storepass changeit \<br>  -keypass changeit \<br>  -dname &quot;CN=Sender, OU=Dev, O=MyCompany, L=City, ST=State, C=US&quot;<br><br># Create recipient&#39;s keystore<br>keytool -genkeypair \<br>  -alias recipientkey \<br>  -keyalg RSA \<br>  -keysize 2048 \<br>  -validity 365 \<br>  -keystore recipient-keystore.jks \<br>  -storepass changeit \<br>  -keypass changeit \<br>  -dname &quot;CN=Recipient, OU=Dev, O=PartnerCompany, L=City, ST=State, C=US&quot;<br><br># Export certificates<br>keytool -exportcert \<br>  -alias senderkey \<br>  -keystore sender-keystore.jks \<br>  -storepass changeit \<br>  -file sender.crt \<br>  -rfc<br><br>keytool -exportcert \<br>  -alias recipientkey \<br>  -keystore recipient-keystore.jks \<br>  -storepass changeit \<br>  -file recipient.crt \<br>  -rfc<br><br># Import partner certificates<br>keytool -importcert \<br>  -alias recipientcert \<br>  -file recipient.crt \<br>  -keystore sender-keystore.jks \<br>  -storepass changeit \<br>  -noprompt<br><br>keytool -importcert \<br>  -alias sendercert \<br>  -file sender.crt \<br>  -keystore recipient-keystore.jks \<br>  -storepass changeit \<br>  -noprompt</pre><p>Now you will have two keys stores.</p><p><strong>Sender’s Keystore (sender-keystore.jks) </strong>contains senderkey (PrivateKeyEntry), recipientcert (trustedCertEntry)</p><p><strong>Recipient’s Keystore (recipient-keystore.jks) </strong>contains<strong> </strong>recipientkey (PrivateKeyEntry), sendercert (trustedCertEntry)</p><h3>Implementation</h3><p>Now let’s dive into the code. We’ll create utility functions to sign and encrypt outgoing SOAP messages, and decrypt and verify incoming responses.</p><h3>1. Helper Utilities</h3><p>First, let’s create some utility classes to convert between Scala XML and Java DOM:</p><pre>import org.apache.ws.security.components.crypto.{CryptoFactory, Merlin}<br>import org.w3c.dom.Document<br><br>import java.io.{ByteArrayInputStream, StringWriter}<br>import java.security.KeyStore<br>import java.util.Properties<br>import javax.xml.parsers.DocumentBuilderFactory<br>import javax.xml.transform.dom.DOMSource<br>import javax.xml.transform.stream.StreamResult<br>import javax.xml.transform.{OutputKeys, TransformerFactory}<br>import scala.util.Using<br><br>object SoapUtil {<br><br>  implicit class RichString(str: String) {<br>    def toDocument: Document = {<br>      val factory = DocumentBuilderFactory.newInstance()<br>      factory.setNamespaceAware(true)<br>      val builder = factory.newDocumentBuilder()<br>      val in = new ByteArrayInputStream(str.getBytes(&quot;UTF-8&quot;))<br>      builder.parse(in)<br>    }<br>  }<br><br>  implicit class RichDocument(document: Document) {<br>    def toXmlString: String = {<br>      val transformer = TransformerFactory.newInstance().newTransformer()<br>      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, &quot;yes&quot;)<br>      val stringWriter = new StringWriter()<br>      transformer.transform(new DOMSource(document), new StreamResult(stringWriter))<br>      stringWriter.toString<br>    }<br>  }<br><br>  def createCrypto(keystorePath: String, keystorePassword: String): Merlin = {<br>    val properties = new Properties()<br>    properties.setProperty(&quot;org.apache.wss4j.crypto.provider&quot;,<br>      &quot;org.apache.ws.security.components.crypto.Merlin&quot;)<br>    properties.setProperty(&quot;org.apache.wss4j.crypto.merlin.keystore.type&quot;, &quot;JKS&quot;)<br>    properties.setProperty(&quot;org.apache.wss4j.crypto.merlin.keystore.password&quot;, keystorePassword)<br><br>    val crypto = CryptoFactory.getInstance(properties).asInstanceOf[Merlin]<br><br>    // Load keystore from classpath<br>    val keystoreStream = Option(getClass.getClassLoader.getResourceAsStream(keystorePath)).getOrElse {<br>      throw new IllegalArgumentException(s&quot;Keystore not found in resources: $keystorePath&quot;)<br>    }<br><br>    Using(keystoreStream) { stream =&gt;<br>      val keystore = KeyStore.getInstance(&quot;JKS&quot;)<br>      keystore.load(stream, keystorePassword.toCharArray)<br>      crypto.setKeyStore(keystore)<br>    }.get<br><br>    crypto<br>  }<br>}</pre><h3>2. Signing and Encrypting SOAP Messages</h3><p>Here’s how to add signature and encryption to an outgoing SOAP message:</p><pre><br>import SoapUtil.*<br>import org.apache.ws.security.WSConstants<br>import org.apache.ws.security.message.{WSSecEncrypt, WSSecHeader, WSSecSignature}<br><br>import scala.util.Try<br><br>object SoapSecurity {<br><br>  def signAndEncryptMessage(<br>                             soapMessage: String,<br>                             keystorePath: String,<br>                             keystorePassword: String,<br>                             signKeyAlias: String,<br>                             signKeyPassword: String,<br>                             encryptCertAlias: String<br>                           ): Try[String] = Try {<br><br>    // Convert string to DOM Document<br>    val document = soapMessage.toDocument<br><br>    // Create security header<br>    val secHeader = new WSSecHeader()<br>    secHeader.insertSecurityHeader(document)<br><br>    // Load keystore<br>    val crypto = createCrypto(keystorePath, keystorePassword)<br><br>    // Add signature<br>    val signature = new WSSecSignature()<br>    signature.setUserInfo(signKeyAlias, signKeyPassword)<br>    signature.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE)<br>    signature.build(document, crypto, secHeader)<br><br>    // Add encryption<br>    val encrypt = new WSSecEncrypt()<br>    encrypt.setUserInfo(encryptCertAlias)<br>    encrypt.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE)<br>    encrypt.setSymmetricEncAlgorithm(WSConstants.AES_256)<br>    encrypt.build(document, crypto, secHeader)<br><br>    // Convert back to string<br>    document.toXmlString<br>  }<br>}</pre><h3>3. Decrypting and Verifying SOAP Responses</h3><p>For incoming messages, we need to verify signatures and decrypt content:</p><pre>import SoapUtil.*<br>import org.apache.ws.security.{WSPasswordCallback, WSSecurityEngine}<br><br>import javax.security.auth.callback.{Callback, CallbackHandler, UnsupportedCallbackException}<br>import scala.util.Try<br><br>object SoapResponseHandler {<br><br>  def decryptAndVerifyResponse(<br>                                encryptedResponse: String,<br>                                keystorePath: String,<br>                                keystorePassword: String,<br>                                decryptKeyAlias: String,<br>                                decryptKeyPassword: String,<br>                                verifyCertAlias: Option[String] = None<br>                              ): Try[String] = Try {<br><br>    val document = encryptedResponse.toDocument<br>    val secEngine = new WSSecurityEngine()<br><br>    // Create crypto with keystore<br>    val crypto = createCrypto(keystorePath, keystorePassword)<br><br>    // Create password callback handler<br>    val callbackHandler = new PasswordCallbackHandler(decryptKeyAlias, decryptKeyPassword)<br><br>    // Process security header (decrypts and verifies)<br>    secEngine.processSecurityHeader(document, null, callbackHandler, crypto)<br><br>    document.toXmlString<br>  }<br>}<br><br>// Callback handler for providing passwords<br>class PasswordCallbackHandler(alias: String, password: String) extends CallbackHandler {<br>  override def handle(callbacks: Array[Callback]): Unit = {<br>    callbacks.foreach {<br>      case pc: WSPasswordCallback if pc.getIdentifier == alias =&gt;<br>        pc.setPassword(password)<br>      case pc: WSPasswordCallback =&gt;<br>        throw new UnsupportedCallbackException(pc, s&quot;Unknown alias: ${pc.getIdentifier}&quot;)<br>      case other =&gt;<br>        throw new UnsupportedCallbackException(other, &quot;Unsupported callback type&quot;)<br>    }<br>  }<br>}</pre><h3>4. Putting It All Together</h3><p>Here’s a complete example of securing a SOAP request and processing the response:</p><pre>import scala.util.{Success, Failure}<br>import scala.io.Source<br><br>object SoapClientExample extends App {<br><br>  private val requestFileStream = Option(getClass.getClassLoader.getResourceAsStream(&quot;example-soap-request.xml&quot;)).getOrElse {<br>    throw new IllegalArgumentException(s&quot;Example response file not found in resources&quot;)<br>  }<br>  private val responseFileStream = Option(getClass.getClassLoader.getResourceAsStream(&quot;example-encrypted-and-signed-soap-response.xml&quot;)).getOrElse {<br>    throw new IllegalArgumentException(s&quot;Example response file not found in resources&quot;)<br>  }<br><br>  private val soapRequest: String = Source.fromInputStream(requestFileStream, &quot;UTF-8&quot;).mkString<br>  private val soapEncryptedResponse: String = Source.fromInputStream(responseFileStream, &quot;UTF-8&quot;).mkString<br><br>  requestFileStream.close()<br>  responseFileStream.close()<br><br>  // Sender&#39;s keystore (contains the sender&#39;s private key and recipient&#39;s public certificate)<br>  // This keystore is loaded from the classpath resources folder<br>  val keystorePath = &quot;sender-keystore.jks&quot;<br>  val keystorePassword = &quot;changeit&quot;  // Password to access the keystore file<br>  <br>  // Sender&#39;s private key (used for signing outgoing messages and decrypting incoming responses)<br>  // - Alias: identifies which key entry to use from the keystore<br>  // - Password: protects the private key entry within the keystore<br>  val myKeyAlias = &quot;senderkey&quot;<br>  val myKeyPassword = &quot;changeit&quot;<br>  <br>  // Recipient&#39;s public certificate (used for encrypting outgoing messages and verifying incoming signatures)<br>  // This certificate is also stored in the sender&#39;s keystore for convenience<br>  val recipientCertAlias = &quot;recipientcert&quot;<br><br>  // ============================================================================<br>  // Outgoing Request: Sign and Encrypt<br>  // ============================================================================<br>  // Operation flow:<br>  // 1. Sign with sender&#39;s private key (myKeyAlias) - proves message authenticity<br>  // 2. Encrypt with recipient&#39;s public certificate (recipientCertAlias) - ensures confidentiality<br>  // Only the recipient with the matching private key can decrypt this message<br>  SoapSecurity.signAndEncryptMessage(<br>    soapRequest,<br>    keystorePath,<br>    keystorePassword,<br>    myKeyAlias,<br>    myKeyPassword,<br>    recipientCertAlias<br>  ) match {<br>    case Success(securedMessage) =&gt;<br>      println(&quot;Secured SOAP message:&quot;)<br>      println(securedMessage)<br><br>      // Send securedMessage to web service...<br>      // val response = sendToWebService(securedMessage)<br><br>    case Failure(ex) =&gt;<br>      println(s&quot;Failed to secure message: ${ex.getMessage}&quot;)<br>  }<br><br>  // ============================================================================<br>  // Incoming Response: Decrypt and Verify<br>  // ============================================================================<br>  // Operation flow:<br>  // 1. Decrypt with sender&#39;s private key (myKeyAlias) - the response was encrypted with sender&#39;s public certificate<br>  // 2. Verify signature with recipient&#39;s public certificate (recipientCertAlias) - confirms response authenticity<br>  // This ensures the response came from the expected recipient and was not tampered with<br>  SoapResponseHandler.decryptAndVerifyResponse(<br>    soapEncryptedResponse,<br>    keystorePath,<br>    keystorePassword,<br>    myKeyAlias,<br>    myKeyPassword,<br>    Some(recipientCertAlias)<br>  ) match {<br>    case Success(decryptedResponse) =&gt;<br>      println(&quot;Decrypted response:&quot;)<br>      println(decryptedResponse)<br>    case Failure(ex) =&gt;<br>      println(s&quot;Failed to process response: ${ex.getMessage}&quot;)<br>  }<br>}</pre><h3>Key Configuration Options</h3><h4>Key Identifier Types</h4><p>WSS4J supports different ways to reference keys in the security header:</p><ul><li>WSConstants.BST_DIRECT_REFERENCE - Embeds the certificate directly</li><li>WSConstants.ISSUER_SERIAL - References by issuer DN and serial number</li><li>WSConstants.X509_KEY_IDENTIFIER - Uses key identifier</li><li>WSConstants.THUMBPRINT_IDENTIFIER - Uses certificate thumbprint</li></ul><h4>Encryption Algorithms</h4><p>Common symmetric encryption algorithms:</p><ul><li>WSConstants.AES_128 - AES with 128-bit keys</li><li>WSConstants.AES_192 - AES with 192-bit keys</li><li>WSConstants.AES_256 - AES with 256-bit keys (recommended)</li></ul><h3>Best Practices</h3><ol><li><strong>Always use strong encryption</strong>: Use AES-256 for symmetric encryption</li><li><strong>Protect your keystore</strong>: Store keystore passwords securely (environment variables, secret management systems)</li><li><strong>Use separate keys</strong>: Use different key pairs for signing and encryption when possible</li><li><strong>Validate certificates</strong>: Always verify certificate chains and check for revocation</li><li><strong>Handle errors gracefully</strong>: Wrap security operations in Try/Either for proper error handling</li><li><strong>Log security events</strong>: Log signature verification and decryption attempts for auditing</li><li><strong>Keep libraries updated</strong>: Regularly update WSS4J and related security libraries</li></ol><h3>Conclusion</h3><p>Securing SOAP messages with Apache WSS4J provides enterprise-grade security for web services communication. By combining digital signatures and encryption, you can ensure that your messages remain confidential, authentic, and tamper-proof throughout their journey.</p><p>The hybrid encryption approach used by WS-Security strikes an excellent balance between security and performance, making it suitable for production environments handling sensitive data.</p><p>The code examples provided here give you a solid foundation for implementing SOAP security in Scala. Remember to adapt them to your specific requirements and always follow security best practices in production environments.</p><p>You can find the complete example repository here: <a href="https://github.com/sandaruwan98/soap-web-security-exmaple.git">https://github.com/sandaruwan98/soap-web-security-exmaple.git</a></p><h3>Resources</h3><ul><li><a href="https://ws.apache.org/wss4j/">Apache WSS4J Documentation</a></li><li><a href="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0.pdf">WS-Security Specification</a></li><li><a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/crypto/CryptoSpec.html">Java Cryptography Architecture</a></li></ul><p>Happy Coding with WSS!🔒</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b5b1f6a58c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>