<?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 Kasun Dharmadasa on Medium]]></title>
        <description><![CDATA[Stories by Kasun Dharmadasa on Medium]]></description>
        <link>https://medium.com/@kasunpdh?source=rss-6f61588ade99------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*e4MqmcgoQSXiSGWRHGAPFw.jpeg</url>
            <title>Stories by Kasun Dharmadasa on Medium</title>
            <link>https://medium.com/@kasunpdh?source=rss-6f61588ade99------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 17:31:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kasunpdh/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[Modern Encryption is at risk: Understanding the Quantum Computing Threat]]></title>
            <link>https://medium.com/@kasunpdh/modern-encryption-is-at-risk-understanding-the-quantum-computing-threat-1d3f02ae0d4b?source=rss-6f61588ade99------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d3f02ae0d4b</guid>
            <dc:creator><![CDATA[Kasun Dharmadasa]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 16:52:03 GMT</pubDate>
            <atom:updated>2025-04-21T16:56:01.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*BapST64lNdB-jjWQdY_5Gg.jpeg" /><figcaption><em>Credit: J. Wang/NIST and Shutterstock</em></figcaption></figure><p>Most of us are relying heavily on public key cryptography systems such as <strong>RSA, Elliptic Curve Cryptography (ECC), and Diffie-Hellman (DH) </strong>that were developed decades ago. These systems have withstood decades of cryptanalysis from conventional computers, but quantum computing introduces an entirely new threat model.</p><h3>Quantum Computing</h3><p>Quantum computers operate using quantum bits or “qubits” that can exist in multiple states simultaneously through a property called superposition. This enables certain calculations to be performed exponentially faster than with classical computers.</p><p>In 1994, mathematician Peter Shor developed an <a href="https://www.historyofinformation.com/detail.php?entryid=4336">algorithm</a> that, when run on a sufficiently powerful quantum computer, could efficiently solve both the factoring problem (affecting RSA) and the discrete logarithm problem (affecting DH and ECC). Shor’s algorithm essentially means that quantum computers could break all these cryptographic systems in hours or days rather than billions of years.</p><h3>Is this really a threat?</h3><p>While fully functional quantum computers capable of breaking these cryptosystems don’t exist yet, significant progress is being made.</p><p>In May 2024, a <a href="https://www.scmp.com/news/china/science/article/3282051/chinese-scientists-hack-military-grade-encryption-quantum-computer-paper">paper</a> published by researchers at Shanghai University demonstrates an approach for factoring integers up to 50 bits in length using an innovative combination of quantum and classical algorithms techniques. This poses an incremental threat to algorithms such as RSA which are based on the computational difficulty of factoring large prime numbers. However, factoring a 50-bit integer is a far cry from breaking the 2048-bit encryption used in modern implementations of the cryptographic algorithms.</p><p>Even though we can rest till quantum computers catch up, there is still the threat of <strong>“harvest now, decrypt later”</strong>. Adversaries can collect encrypted data today with the intention of decrypting it once quantum computing capabilities become available, putting long-term sensitive information at risk.</p><h3>Solution: Post-Quantum Cryptography (PQC)</h3><p>The National Institute of Standards and Technology (NIST) has been leading efforts to standardise quantum-resistant cryptographic algorithms. In 2022, NIST selected <a href="https://www.nist.gov/news-events/news/2022/07/nist-announces-first-four-quantum-resistant-cryptographic-algorithms">initial algorithms for standardisation</a>, including <strong>CRYSTALS-Kyber</strong> for general encryption and <strong>CRYSTALS-Dilithium</strong>, <strong>FALCON</strong>, and <strong>SPHINCS+</strong> for digital signatures. In 2024, they published the <a href="https://www.nist.gov/news-events/news/2024/08/nist-releases-first-3-finalized-post-quantum-encryption-standards">First 3 Finalised Post-Quantum Encryption Standards</a>.</p><blockquote>“These finalized standards include instructions for incorporating them into products and encryption systems,” said NIST mathematician Dustin Moody, who heads the PQC standardization project. “We encourage system administrators to start integrating them into their systems immediately, because full integration will take time.”</blockquote><p><strong>Hybrid Approach<br></strong>Post-quantum algorithms are still new and<strong> </strong>they have<strong> </strong>not been battle-tested like the existing cryptographic algorithms. As a result, fully migrating to these new PQC algorithms carries some risk. To address this, organisations are adopting a hybrid model that combines both classical and post-quantum algorithms. This ensures that an attacker would need to break both algorithms to gain access to the data. Few such implementations are as follows.</p><ol><li><a href="https://blog.cloudflare.com/towards-post-quantum-cryptography-in-tls/">Google’s CECPQ2 </a>(Combined Elliptic-Curve and Post-Quantum Cryptography)</li><li><a href="https://github.com/aws/s2n-tls/blob/main/docs/USAGE-GUIDE.md#kyber-kem">AWS s2n-tls Hybrid PQ Key Exchange</a></li><li><a href="https://github.com/google/boringssl/blob/master/ssl/test/runner/key_agreement.go">BoringSSL’s Hybrid PQC Implementation</a></li></ol><h3>The Path Forward</h3><p>The race between quantum computing and quantum-resistant cryptography is already underway. Quantum computing may seem distant now, but who knows how quickly it might catch up? Just think about how little attention most people paid to AI just a few years ago.</p><p>Now is the time to assess your risk exposure, build crypto-agility, and experiment with post-quantum algorithms for your solutions. Then only you will be best positioned to maintain robust security in the quantum era.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d3f02ae0d4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Java Memory Consistency with happens-before relationship]]></title>
            <link>https://medium.com/@kasunpdh/handling-java-memory-consistency-with-happens-before-relationship-95ddc837ab13?source=rss-6f61588ade99------2</link>
            <guid isPermaLink="false">https://medium.com/p/95ddc837ab13</guid>
            <category><![CDATA[java-concurrency]]></category>
            <category><![CDATA[synchronized]]></category>
            <category><![CDATA[volatile]]></category>
            <category><![CDATA[happens-before]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kasun Dharmadasa]]></dc:creator>
            <pubDate>Mon, 31 Dec 2018 13:51:32 GMT</pubDate>
            <atom:updated>2018-12-31T13:51:32.851Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*iBLVixcJeIsb_6yG" /><figcaption>Source: <a href="http://digitalhealthage.com/how-digital-technologies-can-support-mental-health-patients/">http://digitalhealthage.com/how-digital-technologies-can-support-mental-health-patients/</a></figcaption></figure><p>If you are developing multi-threaded applications in Java, you need to have an understanding of how the shared variables are handled inside the memory of Java. One important factor is the happens-before relationship. In order to understand the happens-before relationship in Java, you need to be familiar with the concept of visibility in concurrent programming.</p><h4>Visibility</h4><blockquote>If an action in one thread is <em>visible</em> to another thread, then the result of that action can be observed by the second thread.</blockquote><p>To understand more on the above statement, let’s have a look at the architecture of a modern shared-memory multiprocessor.</p><p>Almost all of the computers today have multiple cores inside their processors, inside their processors, each capable of handling multiple threads of execution. For each of this core, there exist several levels of caches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*iqPb69ZRrNgy_-5b.jpg" /><figcaption>Source: <a href="https://wiki.sei.cmu.edu/confluence/display/java/Concurrency%2C+Visibility%2C+and+Memory">https://wiki.sei.cmu.edu/confluence/display/java/Concurrency%2C+Visibility%2C+and+Memory</a></figcaption></figure><p>The visibility of writing operations on shared variables can cause problems during delays that occur when writing to the main memory due to caching in each core. This can result in another thread reading a stale value (not the last updated value) of the variable.</p><p>Let’s consider a situation where two threads perform a read an write operation to the same variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/323f16811fdb8d4b7b8e913ac75ec323/href">https://medium.com/media/323f16811fdb8d4b7b8e913ac75ec323/href</a></iframe><p>In the above example from the book “Effective Java by Joshua Bloch”, there is a background thread (backgroundThread) that will increment the value of “i” until the “stopRequested” boolean becomes true. After starting the thread by the main thread of the program, it sleeps for 1 second and makes the “stopRequested” to true.</p><p>What would be the outcome? Ideally, the program should run for 1 second and after the “stopRequested” has become true, the “backgroundThread” should end, terminating the whole program.</p><p>But if you run the above on a computer with multiple cores, you will observe that the program keeps on executing without getting terminated. The problem occurs with the write operation on the “stopRequested” variable. There is no guarantee that the change of the value in “stopRequested” variable (from the main thread) becoming <strong>visible</strong> to the “backgroundThread” that we created. As the write operation to the “stopRequested” variable to true from the main method is invisible to the “backgroundThread”, it will go into an infinite loop.</p><p>As the main thread and our “backgroundThread” is running on two different cores inside the processor, the “stopRequested” will be loaded into the cache of the core that executes the “backgroundThread”. The main thread will keep the updated value of the “stopRequested” value in a cache of a different core. Since now the “stopRequested” value resides in two different caches, the updated value may not be visible to the “backgroundThread”.</p><p>To avoid these type of memory inconsistencies, Java has introduced the happens-before relationship.</p><h3><strong>Happens-before relationship</strong></h3><p>Java defines a happens-before relationship as follows.</p><blockquote>Two actions can be ordered by a <em>happens-before</em> relationship. If one action <em>happens-before</em> another, then the first is visible to and ordered before the second.</blockquote><p>According to this, if there is a happens-before relationship between a write and read operation, the results of a write by one thread are guaranteed to be visible to a read by another thread. Therefore, we will be able to maintain the memory consistency if we are able to have the happens-before relationship between our actions.</p><h4><strong>Synchronizing</strong></h4><p>“Synchronized” keyword is widely used to achieve mutual exclusion among threads. This means that using synchronized keyword we have the ability to limit the access of a particular block of code or a method to only one thread. A single lock is passed around the threads that wish to access a particular synchronized block or a method. Each thread will have wait until the other thread finishes executing the synchronized block/method and release the lock.</p><p>However, synchronizing has another important use. It can also be used to achieve a happens-before relationship between code blocks or methods. If there are two synchronized blocks/methods having the same lock, there is a happens-before relationship between the actions inside the synchronization blocks/methods. This is due to the fact that an unlock on an object lock (exiting synchronized block/method) happens before every subsequent acquiring on the same object lock.</p><p>Let’s change our initial code to include synchronized methods for read and write operations of the “stopRequested” variable</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/918fb029c919fd6b967f0baccdae3c50/href">https://medium.com/media/918fb029c919fd6b967f0baccdae3c50/href</a></iframe><p>Since now both read and write operations to the “stopRequested” variable is synchronized, a happens-before relationship has been established between the read/write operations of the “stopRequested” variable enabling the visibility to all the threads. It is important to note that <strong>both</strong> of the read and write operations need to be synchronized in order to achieve a happens-before relationship.</p><p>For situations similar to our example, using the synchronized keyword just to have visibility might not be the optimum solution. Synchronization has a performance impact due to the threads getting blocked while acquiring a lock. Hence, the synchronized keyword is more suitable when mutual exclusiveness (where only one thread is allowed to access a given resource at a time) is required.</p><p>For situations which require only visibility, Java has introduced a simple new keyword called “volatile”.</p><h4>Volatile Fields</h4><blockquote>A write to a volatile field happens-before every subsequent read of that same field.</blockquote><p>We can use the “volatile” keyword to make “stopRequested” variable a volatile field creating a happens-before relationship with the write and read operations for “stopRequested”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3beb4f9ae3d72e5e694807389cda648d/href">https://medium.com/media/3beb4f9ae3d72e5e694807389cda648d/href</a></iframe><p>However, it is important to keep note that the volatile keyword is not a replacement for synchronized blocks/methods. It will be useful only when achieving visibility for shared variables using a happens-before relationship. We will still have to use the synchronization when we need to achieve mutual exclusiveness between threads.</p><p>Consider the below example of a serial number generator</p><pre>private static int <em>nextSerialNumber </em>= 0;<br><br>public static int generateSerialNumber() { <br>    return <em>nextSerialNumber</em>++;<br>}</pre><p>The above code is not thread safe due to lack of <a href="http://jeremymanson.blogspot.com/2007/08/atomicity-visibility-and-ordering.html">atomicity</a> (not happening all read-modify-write operations at once) in the increment operator (++). Various threads can end up in different states (read or write) when executing the following line.</p><pre>return <em>nextSerialNumber</em>++;</pre><p>However, making the “<em>nextSerialNumber” </em>volatile will not achieve mutual exclusiveness during the increment operation (as volatile keyword can only be used to achieve visibility). A proper fix would be to make the generateSerialNumber() method synchronized.</p><p>Apart from the synchronization and volatility, Java defines several sets of rules for a happens-before relationship. You can find them in detail from the <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5">Oracle Docs</a>.</p><h3>References</h3><p>[1] Effective java (2nd edition) by joshua bloch</p><p>[2] <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5">https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5</a></p><p>[3] <a href="https://wiki.sei.cmu.edu/confluence/display/java/Concurrency%2C+Visibility%2C+and+Memory">https://wiki.sei.cmu.edu/confluence/display/java/Concurrency%2C+Visibility%2C+and+Memory</a></p><p>[4] <a href="http://jeremymanson.blogspot.com/2007/08/atomicity-visibility-and-ordering.html">http://jeremymanson.blogspot.com/2007/08/atomicity-visibility-and-ordering.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95ddc837ab13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Lambda Expressions]]></title>
            <link>https://medium.com/@kasunpdh/java-lambda-expressions-3195f677ed38?source=rss-6f61588ade99------2</link>
            <guid isPermaLink="false">https://medium.com/p/3195f677ed38</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[lambda-expressions]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kasun Dharmadasa]]></dc:creator>
            <pubDate>Sat, 29 Dec 2018 15:26:10 GMT</pubDate>
            <atom:updated>2018-12-29T15:41:41.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*_oeWCAMYCVzv3L3v.png" /></figure><p>Lambda expressions are known to be the biggest feature introduced with Java 8. This was the Java’s first step to Functional Programming.</p><p>As most of us are used to write code using Object Oriented Programming, it’s a bit hard at first to understand these Lambda expressions. We are used to using functions only after defining them inside a class, create an object of the class to call the method. But that’s going to change now.</p><h3>Understanding the Lambda Syntax</h3><p>Consider a variable defined in Java.</p><pre>Object myObject</pre><p>We usually use them to assign an object reference to it.</p><pre>Object myObject = new Object();</pre><p>Now, instead of assigning a reference of an object to the variable, what will happen if we assign a <strong>method</strong> to it?</p><p>Consider the following function</p><pre>public void myFunction(String s1, String s2) {<br>    System.<em>out</em>.println(&quot;String1 = &quot; + s1 + &quot; and String2 = &quot; + s2);<br>}</pre><p>Let’s assign the above method definition to a variable. For simplicity, let’s just focus on the lambda expression syntax. We can later investigate more on the <strong>type of the variable</strong> that it needs to be assigned. Till then, I have used a dummy variable name “aBlockOfCode”</p><pre>aBlockOfCode = public void myFunction(String s1) {<br>    System.<em>out</em>.println(&quot;Hi &quot; + s1);<br>}</pre><p>Since now the method has been assigned to the variable, there are several details that we can omit. The modifier “public” will be useless as the visibility of this method will be decided by the access modifiers defined for the variable (not for the function).</p><p>We can also remove the function name (myFunction) as nobody else is going to use this function with its name (We can reference it with the variable name instead).</p><p>After removing the above two parts now the code looks like this</p><pre>aBlockOfCode = void (String s1) {<br>    System.<em>out</em>.println(&quot;Hi &quot; + s1);<br>}</pre><p><strong>What else can we omit?</strong></p><p>The Java 8 compiler is now much smart. It doesn’t require the method return type. The Java 8 compiler can detect the return type by inspecting the method body. Also, it doesn’t require the type of the method argument. So, we can reduce the above expression further</p><pre>aBlockOfCode = (s1) {<br>    System.<em>out</em>.println(&quot;Hi &quot; + s1);<br>}</pre><p>One more additional detail is required before calling this as a lambda expression. There needs to be a “-&gt;” sign after the input variable declaration. Our final lambda expression will be</p><pre>aBlockOfCode = (s1) -&gt; {<br>    System.<em>out</em>.println(&quot;Hi &quot; + s1);<br>}</pre><p>If there is only one line in the body of the method, we can remove the curly brackets as well</p><p>Finally, the simplified lambda expression for our <strong>myFunction</strong> method will be as follows.</p><pre>aBlockOfCode = s1 -&gt; System.<em>out</em>.println(&quot;Hi &quot; + s1);</pre><p>As you can see, the lambda expressions have made our code much smaller and simpler.</p><p><strong>More examples on Lambda Expressions</strong></p><p><strong>a</strong>. If there are no input parameters the, the syntax would be</p><pre>aBlockOfCode = () -&gt; System.<em>out</em>.println(&quot;Hello World&quot;);</pre><p>b<strong>.</strong> If there needs to be return statement the lambda expression can be written as</p><pre>aBlockOfCode = (s1, s2) -&gt; {<br>    String myString = &quot;String1 = &quot; + s1 + &quot; and String2 = &quot; + s2;<br>    return myString;<br>}</pre><p>Now you may have some understanding about the syntax of a lambda expression. Let’s dig into the left side of the assignment expression (what is the actual type of the variable “aBlockOfCode”?)</p><h3>Functional Interfaces</h3><p>Functional interfaces are defined as interfaces that are having only <strong>one</strong> abstract method. In Java 8, they are annotated by <strong>@FunctionalInterface</strong> annotation. A sample Functional Interface can be created as follows.</p><pre>@FunctionalInterface<br>public interface SampleFunctionalInterface {<br><br>    abstract String foo(String s1);<br>}</pre><p>Turns out these type of Functional Interfaces can be used to assign lambda expression. If we look back at our previous sample lambda expression, we can now do the actual assignment to our SampleFunctionalInterface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12934433a0ac74c944ac1f421f828d10/href">https://medium.com/media/12934433a0ac74c944ac1f421f828d10/href</a></iframe><p>Running the above code will provide the following output</p><pre>&quot;Hi Alice&quot;</pre><p>Now we understand that we need a Functional Interface to write a lambda expression. But,</p><p><strong>Do I have to create a new functional interface every time I write a Lambda expression?</strong></p><p>Fortunately, NO.</p><p>Java 8 has a built in collection of Functional Interfaces that can be used to write most of the Lambda expressions.</p><h3>Support from Java</h3><p>java.util.function package in Java packs a list of Functional Interfaces out of the box. As it turns out there is already a Functional Interface provided by Java that acts similar to our “SampleFunctionalInterface”.</p><p>The Consumer&lt;T&gt; interface in java.util.function package takes up a single argument of any given type and provides a void method that consumes the provided argument.</p><pre>@FunctionalInterface<br>public interface Consumer&lt;T&gt; {<br>    void accept(T var1);<br>}</pre><p>We can use this Consumer&lt;T&gt; interface to rewrite our first Lambda expression as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a38ca053d0844267e6631ba7f3107edc/href">https://medium.com/media/a38ca053d0844267e6631ba7f3107edc/href</a></iframe><p>Another such example is the java.util.function.Function&lt;T,R&gt; interface</p><pre>@FunctionalInterface<br>public interface Function&lt;T, R&gt; {<br>    R apply(T var1);<br>}</pre><p>Using this interface we can write a lambda expression that takes up one argument of any type and returns a value of any type.</p><p>Let’s create a lambda expression that takes a String as an argument and returns the length of the provided String (“MyString”).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad41b107dbd379f383f924dc5f90c882/href">https://medium.com/media/ad41b107dbd379f383f924dc5f90c882/href</a></iframe><p>The output of the above code will print “8” to the console.</p><h3>The Purpose</h3><p>The introduction of lambda expressions paved the way for Functional Programming by passing functions as arguments for another function. Java 8 introduced a stream package that improved the <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html">collection</a> libraries in Java with new concurrency features that boosted the performance in multi-core environments.</p><h3>References</h3><p>[1] <a href="https://javabrains.io/courses/java_lambdabasics/">https://javabrains.io/courses/java_lambdabasics/</a></p><p>[2] <a href="https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html">https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3195f677ed38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Garbage Collection: How it’s done?]]></title>
            <link>https://medium.com/@kasunpdh/garbage-collection-how-its-done-d48135c7fe77?source=rss-6f61588ade99------2</link>
            <guid isPermaLink="false">https://medium.com/p/d48135c7fe77</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kasun Dharmadasa]]></dc:creator>
            <pubDate>Wed, 26 Dec 2018 16:22:38 GMT</pubDate>
            <atom:updated>2018-12-26T16:27:35.227Z</atom:updated>
            <content:encoded><![CDATA[<h3>Garbage Collection: How it’s done</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*f3waGGq2zA9yTGBn.png" /></figure><p>If you are familiar with the basics of the memory allocation in programming languages, you know that there are two parts in the memory defined as Heap and Stack.</p><p>The stack memory is used for execution of a thread. When a function is called, a block of memory is allocated in the stack to store the local variables of the function. The allocated memory gets freed when the function is returned. In contrast to the Stack, Heap memory is used for dynamic allocation (usually when creating objects with “new” or “malloc” keyword) and memory deallocation needs to be handled separately.</p><pre>Object myObject = new Object();<br><br>.............<br><br><br>myObject = null;</pre><p>If at some point of the program, another reference to an object or “null” was assigned to the “myObject” variable, the reference that existed with the already created “Object” will be removed. However, the memory allocated for this “Object” will not be freed even though the Object is not being used. In the older programs such as C or C++, the programmer needs to be concerned about these type of objects allocated in the Heap and delete when they are not in use to free up the memory. Failing to do that can end up in a memory leak. In the other hand, if we mistakenly delete an Object that has a live reference to a variable can cause null pointer exceptions in later parts of the code when we try to access the deleted object using the old reference.</p><p>However, in languages like Java and C#, this memory management is handled by a separate entity known as the Garbage Collector.</p><p>With a Garbage Collector in place, we can allocate an object in the memory, use it and when there is no longer any reference for that object, the object will be marked for the Garbage Collector to pick up freeing the allocated memory. And a Garbage Collector also guarantees that any live Object that has an active reference will not get removed from the memory.</p><h4>Reference Counted Garbage Collection</h4><p>The reference count garbage collection keeps a track of the number of references for a particular object in the memory. Let’s look at the following code segment.</p><pre><strong>Object a = new Object();</strong> // Reference Count(OB1) starts at 1<br><strong>Object b = a; </strong>        // Reference Count (OB1) incremented to 2 as a new reference is added</pre><pre><strong>Object c = new Object();</strong><br><br><strong>b.someMethod();</strong><br><strong>b = null; </strong>       // Reference Count(OB1) decremented to 1 as reference goes away<br><strong>a = c; </strong>          // Reference Count(OB1) decremented to 0</pre><p>When executing the line Object a = new Object(), a new object (let’s say OB1 ) is created in the memory and the reference count (for OB1) starts at 1.</p><p>When the reference for the OB1 in the variable “a” is copied to “b”, the reference counter increases by one as now two variables have the reference for OB1.</p><p>When “b” is assigned to null, there reference for OB1 decreases leaving only the variable “a” having a reference for OB1.</p><p>When the value of “a” is updated by the value of “c” (which is having a reference for a whole new object), there reference counter for the OB1 becomes zero leaving the OB1 available for garbage collection.</p><p><strong>Drawbacks in Reference Counted GC</strong></p><p>The main disadvantage in the reference counted garbage collection is its inability to identify circular references. To understand the circular references, let’s have a look into the below code segment.</p><p>Consider two classes A and B having each other’s references.</p><pre>class A {<br>    private B b;<br><br>    public void setB(B b) {<br>        this.b = b;<br>    }<br>}<br><br>class B {<br>    private A a;<br><br>    public void setA(A a) {<br>        this.a = a;<br>    }<br>}</pre><p>Now in the main method, we can create new objects for both of these classes and assign the references.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        A one = new A();<br>        B two = new B();<br><br>        // Make the objects refer to each other (creates a circular reference)<br>        one.setB(two);<br>        two.setA(one);<br><br>        // Throw away the references from the main method; the two objects are<br>        // still referring to each other<br>        one = null;<br>        two = null;<br>    }<br>}</pre><p>When we assign null values for the two variables one and two, the external references existed with the class objects (“A” and “B”) created at the beginning will be removed. Still, they won’t be eligible for garbage collection as the reference counters of those two objects will not become zero due to object “A” having its reference inside “B” and the object “B” having its reference inside “A”.</p><h4>Mark and Sweep Garbage Collection</h4><p>As the name suggests, Mark and Sweep garbage collectors have two phases<br>1. Mark Phase<br>2. Sweep Phase</p><p><strong>Mark Phase<br></strong>During the Mark phase, the GC identifies the objects that are still in use and set their “mark bit” to true. The search starts with a root set of references kept in local variables in the stack or global variables. Starting from the root references the GC will conduct a depth search for the objects that have reachable references from the root. Any object that keeps a reference of another object, keeps that object alive.</p><p>It is important to keep note that during the Mark phase, the application threads are stopped to avoid the changes that can happen to the object state during the marking phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xkq7jGtAKf7SP1R1a8vcA.png" /><figcaption>Source: <a href="https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description">https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description</a></figcaption></figure><p>The cyclic references are not an issue for a Mark and Sweep GC. If you observe the above diagram, a cyclic reference exists (shown by the square) but it is unreachable from the root. Hence, those types of references will not be marked as live allowing GC to collect as garbage.</p><p><strong>Sweep Phase<br></strong>In the sweep face, all the unmarked objects from the Mark phase will be removed from the memory freeing up space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZTk9FfqQVMpNWmmdgS8VA.png" /><figcaption>Source: <a href="https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description">https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description</a></figcaption></figure><p>As you can observe from the above diagram, there may exist plenty of free regions after the sweep phase. But, due to this fragmentation, the next memory allocation may fail if it is bigger than all the existing free regions.</p><p>To overcome this problem, an additional Compact phase was added.</p><h4>Mark-Sweep-Compact Garbage Collection</h4><p>After the sweep phase, all the memory locations are rearranged to provide a more compact memory allocation. The downside of this approach is an increased GC pause duration as it needs to copy all objects to a new place and to update all references to such objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8b-ANSuneRBXkO1JNtH6LQ.png" /><figcaption>Source: <a href="https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description">https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description</a></figcaption></figure><h4><strong>Mark and Copy Garbage Collector</strong></h4><p>This is similar to the Mark and Sweep collector, but the memory space is divided into two. Initially, the objects are allocated to one space (fromspace), and the live objects are marked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBJP3fl_PyBIRTekkaQWXg.png" /><figcaption>Source: <a href="https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description">https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description</a></figcaption></figure><p>During the copy phase, the marked objects are copied into the other space (tospace) and at the same time compacted. Then, the fromspace is cleared out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQD7WcGBjFCaPIocvPlDSA.png" /><figcaption>Source: <a href="https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description">https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description</a></figcaption></figure><p>After that, both spaces are swapped resulting any new memory allocation to allocate memory in the “new fromspace” (the old tospace will now become the new fromspace). Finally, when the “new fromspace” becomes full, the whole process happens again.</p><h4>Generational Garbage Collector</h4><p>In generational garbage collection, the memory space is divided into different generations (e.g. young generation and old generation). Initially, all the objects would reside on the young generation. However, when a garbage collection cycle happens, objects that survive the garbage collection will be promoted to the older generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxyn657K6Wm8-uSRsjSj-w.png" /><figcaption>Source: <a href="https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description">https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YyFP0Jp9W2W3NhWigeQ0Ig.png" /><figcaption>Source: <a href="https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description">https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/description</a></figcaption></figure><p>Now, the objects left in the young generation can be cleared as all the live objects are moved to the old generation.</p><p>Garbage collection cycles in the old generation occur less frequent than in the young generation. The key idea behind this approach is that objects that survive the first garbage collection tend to live longer. Thus the frequency of garbage collection can be reduced for objects in the older generations. The number of generations differs with the programming language. For example, in Java there are two generations and in .NET there are three.</p><p>It’s always up to the programmer to decide the optimum garbage collector to be used for the application. We can research the types of garbage collectors that have been implemented with the programming language that we use and their properties. However, choosing a garbage collector might require thorough testing as garbage collection is something that affects the performance of an application.</p><h4>References</h4><p>[1] <a href="https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/table-of-contents">https://app.pluralsight.com/library/courses/understanding-java-vm-memory-management/table-of-contents</a></p><p>[2] <a href="https://www.geeksforgeeks.org/mark-and-sweep-garbage-collection-algorithm/">https://www.geeksforgeeks.org/mark-and-sweep-garbage-collection-algorithm/</a></p><p>[3] <a href="https://blogs.msdn.microsoft.com/abhinaba/2009/01/30/back-to-basics-mark-and-sweep-garbage-collection/">https://blogs.msdn.microsoft.com/abhinaba/2009/01/30/back-to-basics-mark-and-sweep-garbage-collection/</a></p><p>[4] <a href="https://plumbr.io/handbook/garbage-collection-algorithms">https://plumbr.io/handbook/garbage-collection-algorithms</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d48135c7fe77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSL Handshake explained]]></title>
            <link>https://medium.com/@kasunpdh/ssl-handshake-explained-4dabb87cdce?source=rss-6f61588ade99------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dabb87cdce</guid>
            <category><![CDATA[handshake]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[tls]]></category>
            <category><![CDATA[mutual-ssl]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Kasun Dharmadasa]]></dc:creator>
            <pubDate>Wed, 10 Oct 2018 13:59:48 GMT</pubDate>
            <atom:updated>2020-05-02T07:33:39.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5J6ULfBAvgLF8PBM4B__Qw.jpeg" /><figcaption>Source : <a href="https://www.x-cart.com/wp-content/uploads/2017/02/http_to_https-1.jpg">https://www.x-cart.com/wp-content/uploads/2017/02/http_to_https-1.jpg</a></figcaption></figure><p>If you have ever browsed an HTTPS URL through a browser, you have experienced the SSL handshake. Even though might not notice it, the browser and the website is creating an HTTPS connection using one-way SSL handshake.</p><p>The main purpose of an SSL handshake is to provide privacy and data integrity for communication between a server and a client. During the Handshake, server and client will exchange important information required to establish a secure connection.</p><p>There are two types of SSL handshakes described as one-way SSL and two-way SSL (Mutual SSL). The difference between those two is that in one -way SSL, only the client validates the identity of the server whereas in two-way SSL, both server and client validate the identity of each other. Usually, when we browse an HTTPS website, one-way SSL is being used where only our browser (client) validates the identity of the website (server). Two-way SSL is mostly used in server to server communication where both parties need to validate the identity of each other.</p><p>During an SSL handshake, the server and the client follow the below set of steps.</p><p><strong>1. Client Hello</strong></p><p>The client will send the information that will be required by the server to start an HTTPS connection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5db1682abe388d37174c6f4e1eb6c64a/href">https://medium.com/media/5db1682abe388d37174c6f4e1eb6c64a/href</a></iframe><p>In the above log, we can see that the client hello with TLS v1.2. By this, the client notifies the server that it has the support for TLS[1] versions 1.2 and below. List of ciphers[2] that are supported by the client can also be seen from the above log. Out of this list, the server will select a cipher suite that it supports. If the list contains cipher suites that server does not recognize, support, or wish to use, the server will ignore those ciphers. If no supported cipher suites were found the server will send a failure alert and close the connection.</p><p><strong>2. Server Hello</strong></p><p>The server will respond back with the configuration it selected from the Client Hello along with its information to proceed with the handshake. Server Hello will be as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3a072ed3b2082ca76d11bd87533fddf/href">https://medium.com/media/c3a072ed3b2082ca76d11bd87533fddf/href</a></iframe><p>Sever will select the TLS version according to the lower of that suggested by the client in the Client Hello message and the highest supported by the server. The server will also send back the cipher suite it selected from the list of ciphers presented by the client.</p><p>Along with the Server Hello, the server will also send the certificate[3] of the server with the certificate chain. The certificate chain will be validated against the certificates in the client trust store[4].</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6836d76ca11cc212c1e694f78302e30/href">https://medium.com/media/b6836d76ca11cc212c1e694f78302e30/href</a></iframe><p><strong>3. Server Key Exchange Message</strong></p><p>This message will be sent by the server to the client carrying the required details for the client to generate the pre-master secret. This message will not be sent if RSA key exchange algorithm (more in this later) or any other key exchange algorithms are used that do not require the information from the server to generate a pre-master secret.</p><p>For Elliptic Curve Diffie Hellman(ECDH)[5] key exchange, the following details on the server ECDH public key are being sent to the client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c8fd7ac7c5e7f068da7f57066ab4a67/href">https://medium.com/media/1c8fd7ac7c5e7f068da7f57066ab4a67/href</a></iframe><p><strong>4. Certificate Request</strong></p><p>This is the place where one-way SSL defers from two-way SSL. In one-way SSL, the authenticity of the client is not being validated. Hence, this step is omitted in one-way SSL handshake.</p><p>During this step, the server will send a certificate request from the client with the certificate type, certificate signature algorithms and certificate authorities [6] supported by the server. There can be situations where the certificate authorities list can be empty. In such scenarios, the client may choose whether to send or avoid sending of the client certificate (depends on the client implementation)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1628fa73b7c4a7193ac6189a55a4bd2/href">https://medium.com/media/e1628fa73b7c4a7193ac6189a55a4bd2/href</a></iframe><p>Finally, the server sends the Server Hello Done message indicating the end of Server Hello. After sending this message, the server will wait for a client response.</p><p><strong>5. Client Certificate</strong></p><p>The client presents its certificate chain to the server. The certificate needs to be appropriate for the negotiated cipher suite’s key exchange algorithm, and any negotiated extensions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76cccf138ce7f0f46d7eca38dcb2f37d/href">https://medium.com/media/76cccf138ce7f0f46d7eca38dcb2f37d/href</a></iframe><p><strong>6. Client Key Exchange Message</strong></p><p>This message needs to be sent by the client following the Client Certificate message. If the client certificate is not being presented (in one-way SSL), the client key exchange message should be sent after the client receives the ServerHelloDone message.</p><p>As we all know the data transferred between the server and the client in an HTTPS connection will be encrypted. Symmetric encryption[7] is being used for this purpose as the computational cost is much lower than Asymmetric encryption. In order to use symmetric encryption, there needs to be a common key between the two ends. The purpose of this message is to generate that common key between that client and the server without exposing to an outsider.</p><p>There are two client key exchange methods described in the TLS v1.2 spec. They are RSA[8] and Diffie-Hellman.</p><p>If RSA is used as the key exchange algorithm, the client generates a 48-byte pre-master secret. The client encrypts the pre-master secret by the public key of the certificate and sends to the server. Only the server will have the corresponding private key to decrypt and get the client generated pre-master secret.</p><p>If Diffie-Hellman is used, the Diffie-Hellman parameters are transmitted to allow both client and server to generate the same pre-master secret.</p><p>After that, both sides will generate a master secret using the pre-master secret and the master secret will be used to generate the symmetric key for encrypting the session data</p><p><strong>7. Finished</strong></p><p>After successful authentication and generating the pre-master secrets/master secrets, a change cipher spec message will be sent by both client and server indicating that the rest of the communication will be encrypted.</p><p>The Finished message will immediately follow the change cipher spec message. This will be the first message encrypted with the negotiated algorithms. Application data will be transferred only after both parties send the finished message and verifying the content of the message.</p><h3><strong>References</strong></h3><p>[1] <a href="https://tools.ietf.org/html/rfc5246">https://tools.ietf.org/html/rfc5246</a></p><p>[2] <a href="https://docs.microsoft.com/en-us/windows/desktop/secauthn/cipher-suites-in-schannel">https://docs.microsoft.com/en-us/windows/desktop/secauthn/cipher-suites-in-schannel</a></p><p>[3] <a href="https://www.websecurity.symantec.com/security-topics/what-is-ssl-tls-https">https://www.websecurity.symantec.com/security-topics/what-is-ssl-tls-https</a></p><p>[4] <a href="https://docs.apigee.com/api-platform/system-administration/keystores-and-truststores">https://docs.apigee.com/api-platform/system-administration/keystores-and-truststores</a></p><p>[5] <a href="https://wiki.openssl.org/index.php/Elliptic_Curve_Diffie_Hellman">https://wiki.openssl.org/index.php/Elliptic_Curve_Diffie_Hellman</a></p><p>[6] <a href="https://www.globalsign.com/en/ssl-information-center/what-are-certification-authorities-trust-hierarchies/">https://www.globalsign.com/en/ssl-information-center/what-are-certification-authorities-trust-hierarchies/</a></p><p>[7] <a href="https://www.ssl2buy.com/wiki/symmetric-vs-asymmetric-encryption-what-are-differences">https://www.ssl2buy.com/wiki/symmetric-vs-asymmetric-encryption-what-are-differences</a></p><p>[8] <a href="https://www.geeksforgeeks.org/rsa-algorithm-cryptography/">https://www.geeksforgeeks.org/rsa-algorithm-cryptography/</a></p><p>[9] <a href="https://www.acunetix.com/blog/articles/establishing-tls-ssl-connection-part-5/">https://www.acunetix.com/blog/articles/establishing-tls-ssl-connection-part-5/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dabb87cdce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Maven Assembly Plugin to build a ZIP distribution]]></title>
            <link>https://medium.com/@kasunpdh/using-the-maven-assembly-plugin-to-build-a-zip-distribution-5cbca2a3b052?source=rss-6f61588ade99------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cbca2a3b052</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[responses]]></category>
            <category><![CDATA[servlet]]></category>
            <dc:creator><![CDATA[Kasun Dharmadasa]]></dc:creator>
            <pubDate>Sat, 30 Jun 2018 18:08:39 GMT</pubDate>
            <atom:updated>2018-10-07T15:36:53.855Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been creating Java programs you are surely familiar with Maven. Maven [1] is a project build and management tool that can be used to build your Java code into a running application. A Maven project has a pom.xml [2] file which contains all the configurations details that will be used by Maven to build the project. Inside this pom.xml we can define plugins that we can use during the building process.</p><p>One such plugin is the Maven Assembly Plugin [3]. This plugin can be used to aggregate all the project output along with its dependencies, configurations and other required files into a single distribution archive.</p><p><strong>A Sample Program</strong></p><p>Let’s create a sample Maven project including a configuration file and a dependency. (source code can be found from <a href="https://github.com/kasundharmadasa/AssemblyPluginSample">here</a> )</p><p>Create a Maven project and add the following Main.java under src/main/java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ada15b1593eabd93887c627fed78957/href">https://medium.com/media/4ada15b1593eabd93887c627fed78957/href</a></iframe><p>The program will read the config.properties and display the output if it is not empty.</p><p>Create a “conf” directory under the project root directory and create a config.properties file with the following content</p><pre>name = Kasun</pre><p>This program uses the org.apache.commons.lang3.StringUtils [4] library to check whether a string is empty. As this is an external dependancy, I have added it into the pom.xml of the project.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;<br>    &lt;artifactId&gt;commons-lang3&lt;/artifactId&gt;<br>    &lt;version&gt;3.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Our final goal is to create a distribution with the config.properties file and the dependent library. This is where the Maven Assembly Plugin comes into play.</p><p>As we are planning to create a zip archive with all the required files, we need to create an assembly descriptor [5] mentioning the required files that we need for the final zip distribution.</p><p><strong>Creating an assembly descriptor</strong></p><p>Create zip.xml file under src/main/assembly and add the following configurations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a40465a869016a0d18009794c19bf28b/href">https://medium.com/media/a40465a869016a0d18009794c19bf28b/href</a></iframe><p><strong>&lt;format&gt; — </strong>specifies the format of the assembly. We can have multiple formats and the assembly plugin will create archives for each format. The supported formats are as follows.</p><ul><li><strong>“zip”</strong> — Creates a ZIP file format</li><li><strong>“tar”</strong> — Creates a TAR format</li><li><strong>“tar.gz”</strong> or <strong>“tgz”</strong> — Creates a gzip’d TAR format</li><li><strong>“tar.bz2”</strong> or <strong>“tbz2”</strong> — Creates a bzip’d TAR format</li><li><strong>“tar.snappy”</strong> — Creates a snappy’d TAR format</li><li><strong>“tar.xz”</strong> or <strong>“txz”</strong> — Creates a xz’d TAR format</li><li><strong>“jar”</strong> — Creates a JAR format</li><li><strong>“dir”</strong> — Creates an exploded directory format</li><li><strong>“war”</strong> — Creates a WAR format</li></ul><p>Since we are creating a zip archive, I have added the format as zip.</p><p><strong>&lt;fileSet&gt;</strong> — defines the directories that need to be included in the assembly. I have added the conf directory which contains the config.properties file.</p><p><strong>&lt;file&gt;</strong> — As &lt;fileSet&gt; can be used to add directories, &lt;file&gt; can be used to add individual files. I have added this project’s jar file that gets built to be included in the final archive. (the path ${project.build.directory}/${project.artifactId}-${project.version}.jar file gets resolved into target/assemblyPluginTutorial-1.0-SNAPSHOT.jar). Since I would want the project jar to be in the root of the zip archive, &lt;outputDirectory&gt; value has been added as “/”.</p><p><strong>&lt;dependencySet&gt;</strong> — Defines the location for the all the dependency libraries. Note that I have excluded my project jar being copied into the dependency directory as I have already included it in the archive root directory.</p><p><strong>Adding the plugins into POM</strong></p><p>Finally, we can edit the pom.xml file to include the Maven Assembly Plugin as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03cf1cbfa751d15e3ea1372078aefd59/href">https://medium.com/media/03cf1cbfa751d15e3ea1372078aefd59/href</a></iframe><p>Here, I have also added the Maven Jar Plugin [6] that will be used to create the MANIFEST.MF. The MANIFEST.MF file will be used to specify the project main class and the classpath of the libraries.</p><p><strong>Build the program</strong></p><p>Building the program (mvn clean install) will create the final <strong>assemblyPluginTutorial-1.0-SNAPSHOT.zip</strong> in the target directory. If we list the files inside this zip archive, we can seen that the config.properties file has been packed inside the conf folder and the dependent commons library is packed inside the lib directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AglNeAb8RDYZ7dt9PaaCqw.png" /></figure><p><strong>References</strong></p><p>[1] <a href="https://maven.apache.org/">https://maven.apache.org/</a><br>[2] <a href="https://maven.apache.org/guides/introduction/introduction-to-the-pom.html">https://maven.apache.org/guides/introduction/introduction-to-the-pom.html</a><br>[3] <a href="https://maven.apache.org/plugins/maven-assembly-plugin/">https://maven.apache.org/plugins/maven-assembly-plugin/</a><br>[4] <a href="https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html">https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html</a><br>[5] <a href="https://maven.apache.org/plugins/maven-assembly-plugin/assembly.html">https://maven.apache.org/plugins/maven-assembly-plugin/assembly.html</a><br>[6] <a href="https://maven.apache.org/plugins/maven-jar-plugin/">https://maven.apache.org/plugins/maven-jar-plugin/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cbca2a3b052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Session Management in Java using Servlet Filters and Cookies]]></title>
            <link>https://medium.com/@kasunpdh/session-management-in-java-using-servlet-filters-and-cookies-7c536b40448f?source=rss-6f61588ade99------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c536b40448f</guid>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kasun Dharmadasa]]></dc:creator>
            <pubDate>Sun, 17 Dec 2017 09:55:49 GMT</pubDate>
            <atom:updated>2017-12-17T09:55:49.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*e7cAGS8hGkpT1rpc.jpg" /><figcaption>Source: <a href="https://ak0.picdn.net/shutterstock/videos/9572030/thumb/11.jpg">https://ak0.picdn.net/shutterstock/videos/9572030/thumb/11.jpg</a></figcaption></figure><p>(If you are not familiar with Servlets and JSP, please refer my previous post on <a href="https://medium.com/@kasunpdh/sample-java-web-application-using-servlets-and-jsp-5621cad2f582">Sample Java Web Application using Servlets and JSP</a>)</p><p>By default HTTP protocol is stateless. This means that every request is a new request to a server. Although there are advantages of being stateless, some occasions enforce to maintain a state in order to its proper functionality. For example, consider a user logging into a website. After authentication, the website needs to maintain a logged state for the user in order to execute his actions. A web server can easily achieve this by using Cookies.</p><p><strong>What are Cookies?</strong></p><p>A Cookie is a small piece of data that is exchanged between a server and a client. Whenever a client sends a request, the server will send a cookie containing the required data and the client can send back the cookie with its next request. In session management, Tomcat creates a session id whenever client’s first request gets to the server (However, other servlet containers may behave differently). Then it inserts this session id into a cookie with a name JSESSIONID and sends along with the response. After receiving the response with the cookie, the client can send the received cookie in its next request so that the server will identify the session using session id that resides in the JSESSIONID cookie.</p><p>In this tutorial, I will explain how to create a simple login interface that will maintain a login session. I am using IntelliJ Idea as my IDE and Maven tomcat plugin to deploy the war. (Please refer <a href="https://medium.com/@kasunpdh/sample-java-web-application-using-servlets-and-jsp-5621cad2f582">this</a> if you are not familiar with them)</p><p><strong>Step 1: Create a maven project in intelliJ idea</strong></p><p><strong>Step 2: Add the required dependencies to the pom.xml</strong></p><p>Add the javax.servlet-api and tomcat7-maven-plugin into the pom.xml and make the packaging as “war”. After that, your pom.xml should be similar to this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13b1098cc0f4659b3321073446fbbc28/href">https://medium.com/media/13b1098cc0f4659b3321073446fbbc28/href</a></iframe><p><strong>Step 3: Create the login page</strong></p><p>3.1. Create a directory with the name “webapp” under src/main/ and insert the following loginPage.html file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eabd9e62a23a5c3a86b7c500346b999d/href">https://medium.com/media/eabd9e62a23a5c3a86b7c500346b999d/href</a></iframe><p>This will be the landing page for our application. When the user enters his username and password, a post request containing those parameters is send to our LoginServlet.</p><p><strong>Step 4: Create the LoginServlet class</strong></p><p>Create LoginServlet.java under src/main/java with a package name of com.servlet.session and insert the following code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*soFMNxmO5GsaCr3UXDF34A.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e01b5f074ad11065578dd81d0fb2c56b/href">https://medium.com/media/e01b5f074ad11065578dd81d0fb2c56b/href</a></iframe><p>Inside the LoginServlet, we are comparing the received credentials with a set of stored credentials in the servlet. If they both match, the user can be successfully authenticated.</p><p>Be sure to invalidate the session that existed before authenticating the user and create a new session after authenticating.</p><pre>HttpSession newSession = request.getSession(true);</pre><p>Above line creates a new session and saves it in the newSession object. This will also create the JSESSIONID cookie with the new value. Note that passing the Boolean parameter “false” to the getSession() returns the existing session and returns null if no session exists. Passing the parameter “true” will create a new session if no session exists.</p><p>If we want to expire the session after some period and prompt user to log in again, we can use setMaxInactiveInterval().</p><p>We can also add new cookies to the session. Here, we are creating a cookie with the name message and inserting the value “Welcome” into the cookie.</p><p>Set the “secure” flag in a cookie if you want to stop sending a cookie to an HTTP page. Browsers will send the “secure” cookies only through HTTPS channels. “HttpOnly” flag in a cookie makes it inaccessible to JavaScript’s Document.cookie API. This can help in preventing <a href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)">Cross Site Scripting (XSS)</a> attacks.</p><pre>cookie.setSecure(true);<br>cookie.setHttpOnly(true);</pre><p>Note that tomcat automatically sets the HTTPOnly flag in the JSESSIONID cookie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*yFrF3K0KfawLSzTM60tXqQ.png" /></figure><p>After all this, we can redirect the user to Login Success page.</p><p>If the credentials don’t match, we are redirecting the user to the login page with an error message saying “Either username or password is wrong”. In this step, we are not specifying which parameter is wrong due to security reasons. If an attacker is trying to log in by brute force, we don’t want to inform him even if he enters the correct username.</p><p>We have used @WebFilter annotation to map the URL pattern /LoginServlet into our Servlet. We can also achieve this by using a deployment descriptor (web.xml)</p><p><strong>Step 5: Create the LoginSuccess.jsp</strong></p><p>Create a LoginSuccess.jsp file under src/main/java/webapp/admin and add the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edd39ee38bebbe2dcc278e4eac3c6014/href">https://medium.com/media/edd39ee38bebbe2dcc278e4eac3c6014/href</a></iframe><p>Once the user gets redirected to this LoginSuccess.jsp, we can read the cookies set by LoginServlet. Since there are multiple cookies, we have iterated through the cookies array and extracted the required cookie values. Here we display the cookie values on the Login Success page. This page contains the logout link that will send the logout request to the LogoutServlet.</p><p><strong>Step 6: Create the Logout Servlet</strong></p><p>Create a LogoutSevlet.java under src/main/java with a package name com.servlet.session and insert the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65f03f32e2e8c9efd84f66c50cac8761/href">https://medium.com/media/65f03f32e2e8c9efd84f66c50cac8761/href</a></iframe><p>In here we are invalidating the authenticated session and redirect the user to the login page. Note that we have added the /admin/LogoutServlet as the servlet mapping.</p><p>Now, build the war file and deploy!</p><p>Since I’m using tomcat maven plugin, I can simply enter <br>mvn tomcat7:run<br>in the terminal and go to <a href="http://localhost:8080/Login/loginPage.html">http://localhost:8080/Login/loginPage.html</a></p><p>Here /Login is my maven artifactID (see my pom.xml).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*Xpt-09ZdM93e94k4-NMv5Q.png" /></figure><p>After login, you will be redirected to LoginSuccess.jsp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*q-XlDABJq57OqiNRcAuP9A.png" /></figure><p>Once you press the logout, you will be again redirected to the login page.</p><p>However, you will notice that even after the logout, we can still browse to the LoginSuccess.jsp(<a href="http://localhost:8080/Login/loginPage.html">http://localhost:8080/Login/</a>admin/LoginSuccess.jsp). It will still show a success login. Whaaaaat????</p><p>So, the above authentication process is useless? No. This is where Servlet Filters come in to play (If you are not familiar with servlet filters, read my blog on <a href="https://medium.com/@kasunpdh/how-to-use-servlet-filters-4fb497084eb4">How to use Servlet Filters</a>).</p><p><strong>Let’s use Servlet Filters</strong></p><p>A servlet filter can block the access to the LoginSuccess.jsp when the session is null.</p><p>Step 7: Create the Authentication Filter</p><p>Create an AuthenticationFilter.java under src/main/java with a package name com.servlet.filter and insert the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ae41f9f3bd06134dfa1eb0ddbacbc54/href">https://medium.com/media/2ae41f9f3bd06134dfa1eb0ddbacbc54/href</a></iframe><p>In order to make this filter active, we need to define the filter and the required filter mapping in the web.xml</p><p>Step 8: Create the web.xml</p><p>Create the WEB-INF directory under webapp directory and add the following web.xml file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6aa36340f54b203bdbfa48122ad30d2/href">https://medium.com/media/b6aa36340f54b203bdbfa48122ad30d2/href</a></iframe><p>If there is a request for a path that starts with /admin without an existing session, this filter will log it as an unauthorized request and redirect to loginPage.html. If the session exists, the request is passed to the next filter in the filter chain. This will prevent unauthorized users accessing LoginSuccess page while allowing logged users to access. Any additional Servlets or JSPs that needs to be accessed by authorized users, can be exposed under the URL pattern /admin</p><p>Here <a href="https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html">ServletContext</a> logs are used to log filter initialization and user actions. These logs can be viewed from %TOMCAT_HOME/logs/localhost.$(date).log file.</p><p>Now you can try to browse to the LoginSuccess.jsp before login. You will see that it gets automatically redirected to the loginPage.html. If you examine the logs, you will see the “Unauthorized access request” log message.</p><h3>References</h3><ul><li><a href="https://docs.oracle.com/javaee/6/tutorial/doc/bnagb.html">Filtering Requests and Responses - The Java EE 6 Tutorial</a></li><li><a href="https://www.journaldev.com/1933/java-servlet-filter-example-tutorial">Java Servlet Filter Example Tutorial - JournalDev</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c536b40448f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Servlet Filters]]></title>
            <link>https://medium.com/@kasunpdh/how-to-use-servlet-filters-4fb497084eb4?source=rss-6f61588ade99------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fb497084eb4</guid>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[servlet]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kasun Dharmadasa]]></dc:creator>
            <pubDate>Sun, 17 Dec 2017 08:21:15 GMT</pubDate>
            <atom:updated>2017-12-17T15:16:37.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R4ygmo7F_4F0sQ_O.jpg" /><figcaption>Source: <a href="http://blog.inkjetwholesale.com.au/wp-content/uploads/2016/07/instagram-for-your-business-filters.jpg">http://blog.inkjetwholesale.com.au/wp-content/uploads/2016/07/instagram-for-your-business-filters.jpg</a></figcaption></figure><p>Servlet Filters are used to intercept a request and conduct pre-processing or post-processing on that request. It is useful in implementing features such as</p><ol><li>Logging of requests</li><li>Authentication and Authorization</li><li>Encryption or Decryption</li><li>Formatting the request header or body before sending to the servlet.</li></ol><p>Filters can also be implemented in chains. The order of the filter chain can be defined using the deployment descriptor (web.xml).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*ktkLi286lvygzGBT.JPG" /><figcaption>Source : <a href="https://www.javatpoint.com/servlet-filter">https://www.javatpoint.com/servlet-filter</a></figcaption></figure><p>In order to use filters, we have to implement the javax.servlet.Filter interface provided by java. This interface provides the following set of methods.</p><ol><li><strong>init</strong>( FilterConfig config ) <br> This is a one-time method that gets invoked when the filter is initialized.</li><li><strong>doFilter</strong>(HttpServletRequest request,HttpServletResponse response, FilterChain chain)<br>This method gets invoked every time when the filter has to filter a request. All the filter actions on the request can be implemented here. The FilterChain parameter can be used to implement the next filter in the filter chain.</li><li><strong>destroy</strong>()<br>This is a one-time method that gets invoked when the filter is taken out of service.</li></ol><p>Before implementing servlet filters, let’s create a sample webpage that accepts a request and display the content.</p><p><strong>MovieHut.com</strong></p><p>MovieHut is an online movie store. We’ll use a servlet to display the MovieHut webpage.</p><p>I’m using IntelliJ IDEA as my IDE and maven tomcat plugin to deploy the web app. (If you are not familiar with servlets or the tomcat maven plugin, refer my previous post on <a href="https://medium.com/@kasunpdh/sample-java-web-application-using-servlets-and-jsp-5621cad2f582">Sample Java Web Application using Servlets and JSP</a>)</p><p><strong>Step 1: Create a maven project.</strong></p><p><strong>Step 2: Add the servlet dependency and tomcat maven plugin to the pom.xml</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65345623c03f3c0d655bac9ce1626733/href">https://medium.com/media/65345623c03f3c0d655bac9ce1626733/href</a></iframe><p><strong>Step 3: Create the MovieServlet class</strong></p><p>Create a class named MovieServlet.java in src/main/java under the package name com.servlet and insert the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8a4570c7c98e090ecdea8519da36133/href">https://medium.com/media/a8a4570c7c98e090ecdea8519da36133/href</a></iframe><p>The MovieServlet class accepts the GET request sent by the browser and load the Welcome page.In my previous tutorials, I have used Annotations to define the servlets. However, we’ll use a deployment descriptor (web.xml) to define this servlet.</p><p><strong>Step 5: Create the web.xml</strong></p><p>Create the WEB-INF directory under webapp directory and add the following web.xml file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a3c25cbed47963e730156296471470f/href">https://medium.com/media/5a3c25cbed47963e730156296471470f/href</a></iframe><p>In this web.xml file, we define our MovieServlet class and map the URL pattern “/Servlets/MovieServlet”. All the other relevant servlets can be mapped under /Servlets.</p><p><strong>Step 6: Build the war and deploy.</strong></p><p>If you are using tomcat maven plugin, you can simply enter the following command in the terminal.</p><p>mvn tomcat7:run</p><p>This will automatically build the war file and deploy in tomcat.</p><p>If you browse to the <a href="http://localhost:8080/FilterSample/user.html">http://localhost:8080/FilterSample</a>/Servlets/MovieServlet</p><p>you will see the MovieHut.com welcome page.</p><p>Here “FilterSample” is the artifactID I have given for my maven project. maven tomcat plugin automatically gets the artifactID as the application path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*yDgOXAn27NbMed39JQ9YyA.png" /></figure><p><strong>Let’s use Filters<br></strong>The MovieHut team decided to log IP address and the timestamp of the requests coming to the servlets. There are several ways to achieve this. Since we are here to learn about servlet filters, we’ll use a servlet filter to fulfill the above requirement.</p><p><strong>Step 8: Create the RequestLoggingFilter class</strong></p><p>Create the class RequestLoggingFilter.java in src/main/java under the package name com.servlet.filters and add the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3daf01940a20e3582b86f2404ade62b/href">https://medium.com/media/a3daf01940a20e3582b86f2404ade62b/href</a></iframe><p>In order to use this filter, we need to add the filter and its mapping to web.xml. To do that add the following code to the web.xml</p><pre>&lt;filter&gt;<br>    &lt;filter-name&gt;RequestLoggingFilter&lt;/filter-name&gt;<br>    &lt;filter-class&gt;com.servlet.filters.RequestLoggingFilter&lt;/filter-class&gt;<br>&lt;/filter&gt;<br><br>&lt;filter-mapping&gt;<br>    &lt;filter-name&gt;RequestLoggingFilter&lt;/filter-name&gt;<br>    &lt;url-pattern&gt;/Servlets/*&lt;/url-pattern&gt;<br>&lt;/filter-mapping&gt;</pre><p>Here we have mapped this filter to the URL pattern /Servlets/* so that the requests start with /Servlets will be intercepted by this filter.</p><p>As explained in the beginning of this tutorial, RequestLoggingFilter has implemented the doFilter() method to intercept the request. This filter will log the IP address and the Timestamp of requests into ServletContext logs. These logs can be viewed from %TOMCAT_HOME/logs/localhost.$(date).log file.</p><p>If you deploy the war and press Enter in the index.html, you’ll see the request log in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*WRj9fm7O_x7It0Bxb3rx7Q.png" /></figure><p><strong>Adding multiple Filters</strong></p><p>After all this, the MovieHut team needed to make MovieHut.com visible only for mobile users. They wanted to allow only mobile browsers to access the site. No need to panic. This requirement can also be achieved using Servlet filters.</p><p>You might have noticed that each HTTP request carries a User-Agent header consisting information of the browser and OS that originated the request. We can use this header to identify mobile browsers.</p><p>However, this approach is not recommended as the user has the ability to change the request headers by intercepting the requests (We’ll talk more about that in future articles).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*lErpF7N1rN6wyy_O0-2E_A.png" /><figcaption>A sample User-Agent header</figcaption></figure><p>We’ll use a library called<strong> </strong><a href="https://github.com/HaraldWalker/user-agent-utils">UserAgentUtils</a> to extract the required information from the User-Agent header. To import this library, add the following dependency into pom.xml.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;eu.bitwalker&lt;/groupId&gt;<br>    &lt;artifactId&gt;UserAgentUtils&lt;/artifactId&gt;<br>    &lt;version&gt;1.20&lt;/version&gt;<br>&lt;/dependency&gt;<strong> </strong></pre><p><strong>Step 9: Create the RequestBlockingFilter class</strong></p><p>Create the RequestBlockingFilter.java class in src/main/java/ under the package name com.servlet.filters and add the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f36b259b1ef9fc4322d7327293a375c7/href">https://medium.com/media/f36b259b1ef9fc4322d7327293a375c7/href</a></iframe><p>Remember to add the RequestBlockingFilter to the web.xml</p><pre>&lt;filter&gt;<br>    &lt;filter-name&gt;RequestBlockingFilter&lt;/filter-name&gt;<br>    &lt;filter-class&gt;com.servlet.filters.RequestBlockingFilter&lt;/filter-class&gt;<br>&lt;/filter&gt;<br><br>&lt;filter-mapping&gt;<br>    &lt;filter-name&gt;RequestBlockingFilter&lt;/filter-name&gt;<br>    &lt;url-pattern&gt;/Servlets/*&lt;/url-pattern&gt;<br>&lt;/filter-mapping&gt;</pre><p>The RequestBlockingFilter will intercept all the requests to /Servlets and check the browser name that comes with the User-Agent header. For simplicity, I have blocked the Firefox browser (Let’s assume that all the desktop computers use Firefox browser). If the user agent is Firefox, the RequestBlockingFilter will redirect the user to the landing page with an error message.</p><p>If you deploy this sample and test it using the Firefox browser, you’ll get the following error message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*ZMbpE1oMIxerQQJ2H8UBng.png" /></figure><p>Note that the order of a filter is decided on the order they are defined in the web.xml. If you have defined the RequestBlockingFilter before RequestLoggingFilter (as shown below), you will notice that the requests from Firefox browsers will not be logged by the RequestLoggingFilter as they are not getting passed to the filter chain by RequestBlockingFilter.</p><pre>&lt;filter&gt;<br>    &lt;filter-name&gt;RequestBlockingFilter&lt;/filter-name&gt;<br>    &lt;filter-class&gt;com.servlet.filters.RequestBlockingFilter&lt;/filter-class&gt;<br>&lt;/filter&gt;<br><br>&lt;filter-mapping&gt;<br>    &lt;filter-name&gt;RequestBlockingFilter&lt;/filter-name&gt;<br>    &lt;url-pattern&gt;/Servlets/*&lt;/url-pattern&gt;<br>&lt;/filter-mapping&gt;<br><br>&lt;filter&gt;<br>    &lt;filter-name&gt;RequestLoggingFilter&lt;/filter-name&gt;<br>    &lt;filter-class&gt;com.servlet.filters.RequestLoggingFilter&lt;/filter-class&gt;<br>&lt;/filter&gt;<br><br>&lt;filter-mapping&gt;<br>    &lt;filter-name&gt;RequestLoggingFilter&lt;/filter-name&gt;<br>    &lt;url-pattern&gt;/Servlets/*&lt;/url-pattern&gt;<br>&lt;/filter-mapping&gt;</pre><p>Servlet Filters are pluggable. We can easily remove any of the above filters by removing the filter mapping in the web.xml and redeploying the war.</p><h3>References</h3><ul><li><a href="https://www.journaldev.com/1933/java-servlet-filter-example-tutorial">Java Servlet Filter Example Tutorial - JournalDev</a></li><li><a href="http://tutorials.jenkov.com/java-servlets/servlet-filters.html">Servlet Filters</a></li><li><a href="https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/Filter.html">Filter (Servlet API Documentation)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fb497084eb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing and Testing HTTP Public Key Pinning (HPKP)]]></title>
            <link>https://medium.com/@kasunpdh/implementing-and-testing-http-public-key-pinning-hpkp-574f2497152c?source=rss-6f61588ade99------2</link>
            <guid isPermaLink="false">https://medium.com/p/574f2497152c</guid>
            <category><![CDATA[mitm]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[https]]></category>
            <dc:creator><![CDATA[Kasun Dharmadasa]]></dc:creator>
            <pubDate>Sun, 24 Sep 2017 19:00:56 GMT</pubDate>
            <atom:updated>2017-12-08T06:30:24.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*FaRc0u5Df0B6H_W7.jpg" /><figcaption>Source: <a href="https://cdn-images-1.medium.com/max/2000/0*FaRc0u5Df0B6H_W7.jpg">https://cdn-images-1.medium.com/max/2000/0*FaRc0u5Df0B6H_W7.jpg</a></figcaption></figure><p>With HTTPS we use encryption to secure the communication with a server and a client. This encryption consists of two types known as asymmetric and symmetric encryption. Asymmetric encryption uses a public and a private key pair. If the data is encrypted with a private key, only the corresponding public key can be used to decrypt (and vise versa). In order to reach the public key of the server to the client, SSL certificates are used. An SSL certificate is a data file that binds a public key in to an organization’s details. Here SSL stands for Secure Socket Layer. Since these certificates include organization details of the relevant web server, they can be used to ensure the legitimacy of the web server that we are visiting. An SSL certificate is issued by a Certificate Authority(CA). When ever a web server needs to get a certificate, they should generate a public key and send their organization details along with this key to a CA. This process is known as a Certificate Signing Request. The CA will investigate the details and after confirming the legitimacy of the server, it will sign the certificate.</p><p>There are two types of Certificate Authorities called root CAs and intermediate CAs. Root CAs are trusted by all the browsers. They do not need to sign their certificate by someone else. Root CAs will sign the certificates of intermediate CAs and they will sign the certificates of other intermediate CAs. This chain will end after an intermediate CA signs an end user certificate. During the initial response, server sends its certificate chain to the browser (client). After that, the browser examines the certificate chain until it finds a CA that includes in the trusted list of CAs of the browser. After successful identification, a green padlock is displayed in front of the address bar.</p><p>All of this process is dependent on the trust of the CA. So, what will happen if one CA is compromised?. All the certificates signed by the compromised CA will be accepted by all the browsers in the world. As a solution for this Public Key Pinning was introduced.</p><p><strong>What is Public Key Pinning?</strong></p><p>HTTP Public Key Pinning(HPKP) is a trust on first use technique. When a user requests a web server for the first time, the server tells to pin its own or an intermediate CA’s public key to the browser via a special HTTP header. After that browser stores this key for a given period of time. Upon user’s subsequent requests for that web server, the browser expects to contain the pinned key inside one of certificates in the certificate chain of the web server. If not, the user is blocked by giving a warning.</p><p><strong>How to implement HPKP?</strong></p><p>To implement this, following Public key Pins header should be included in the response to the client.</p><pre>Public-Key-Pins: pin-sha256=&quot;base64==&quot;; max-age=expireTime; includeSubDomains; report-uri=&quot;reportURI&quot;</pre><p><strong>pin-sha256 <br></strong>The value of this parameter should contain the base 64 encoded value of Subject Public Key Information (SPKI).</p><p>To generate the SPKI from the certificate we can use OpenSSL</p><pre>openssl x509 -pubkey &lt; tls.crt | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | base64</pre><p>Here tls.crt is the location of the certificate file. This command will print the SPKI in to the terminal. If we want to create the SPKI from the Certificate Signing Request(CSR), following command can be used.</p><pre>openssl req -pubkey &lt; tls.csr | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | base64</pre><p>Instead of pinning the public key, we can also pin the certificate. But it is recommended to use public keys (See [<a href="https://www.imperialviolet.org/2011/05/04/pinning.html">2</a>]).</p><p><strong>max-age <br></strong>The value of this parameter should contain how many seconds does the browser needs to keep the keys pinned.</p><p><strong>includeSubdomains</strong> <br>An optional parameters for enforcing public key pinning to every sub domain of the site.</p><p><strong>report-uri <br></strong>An optional parameter to specify the URL endpoint to report if a validation failure occurs.</p><p>A sample HPKP header will look like this.</p><pre>Public-Key-Pins: <br>  pin-sha256=&quot;MHJYVThihUrJcxW6wcqyOISTXIsInsdj3xK8QrZbHec=&quot;; <br>  pin-sha256=&quot;M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=&quot;; <br>  max-age=31536000; includeSubDomains; <br>  report-uri=&quot;https://www.example.com/report&quot;</pre><p>As shown in the sample, it is recommended to add backup keys. This is because if we change the certificate of the server, users will get blocked for a considerable amount of time (until the max-age time expires). Better approach would be to have a backup CSR and generate the SPKI from that because that eradicates the need to purchase a backup certificate until needed. If the CSR is same the generated certificate will be the same.</p><p>Public-Key-Pins-Report-Only header can be used instead of Public-Key-Pins header if we want only to report a validation failure, not to block the user.</p><p>Now let’s come to the most important part.</p><p><strong>How to test HPKP?</strong></p><p>Most of the time adding the HPKP header is an easy task. But how can we ensure that this works and our users are secured?. A key point to remember is that browser will not accept the HPKP header if the certificate of the server is self signed. Most of the time for testing purposes we create self signed certificates. But the browser will accept only if the certificate is signed by a CA that is trusted by the browser.</p><p>However to avoid this for the testing purposes we can generate a CA certificate locally and add it into browser’s trusted list of CAs (See [<a href="https://datacenteroverlords.com/2012/03/01/creating-your-own-ssl-certificate-authority/">4</a>]). Then sign the certificate of the web server that we want to test using this generated CA certificate. Since now the certificate is signed by a CA trusted by the browser, HPKP header is accepted.</p><h3>References</h3><p>[1] <a href="https://tools.ietf.org/html/rfc7469">https://tools.ietf.org/html/rfc7469</a></p><p>[2] <a href="https://www.imperialviolet.org/2011/05/04/pinning.html">https://www.imperialviolet.org/2011/05/04/pinning.html</a></p><p>[3] <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning">https://developer.mozilla.org/enUS/docs/Web/HTTP/Public_Key_Pinning</a></p><p>[4] <a href="https://datacenteroverlords.com/2012/03/01/creating-your-own-ssl-certificate-authority/">https://datacenteroverlords.com/2012/03/01/creating-your-own-ssl-certificate-authority/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=574f2497152c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to store passwords securely with PBKDF2]]></title>
            <link>https://medium.com/@kasunpdh/how-to-store-passwords-securely-with-pbkdf2-204487f14e84?source=rss-6f61588ade99------2</link>
            <guid isPermaLink="false">https://medium.com/p/204487f14e84</guid>
            <category><![CDATA[salt]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kasun Dharmadasa]]></dc:creator>
            <pubDate>Mon, 03 Jul 2017 17:47:55 GMT</pubDate>
            <atom:updated>2017-09-23T16:09:49.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2-gODOezUMpalY6Z.jpg" /><figcaption>Source : <a href="http://cdn.ttgtmedia.com/visuals/ComputerWeekly/Hero%20Images/password-security-fotolia.jpg">http://cdn.ttgtmedia.com/visuals/ComputerWeekly/Hero%20Images/password-security-fotolia.jpg</a></figcaption></figure><p>Passwords can be the most valuable data to an attacker because stolen passwords can provide attackers the ability to bypass most of the security perimeters that exists in the system. Since lot of people use the same password in several other systems, one system compromise can affect the security of other systems too.</p><h4>Hashing</h4><p>Hashing is a successful way that can be used to store the passwords securely. With hashing, we can convert any size of data into a fixed set of characters. Main difference between hashing and encryption is that the hashing process cannot be reversed. Once we hash a data, we cannot retrieve its value again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*S-AklkzjLATErkpX.gif" /><figcaption>Source : Cryptography : A Basic Introduction of Hashing and HashAlgo class for beginners — Part 1 by RaviRanjanKr,</figcaption></figure><h4>So how we can use hashing to store passwords securely?</h4><p>First of all whenever a new user is registered, we have to pass that user’s password through a hashing function before storing it in a database. During the user’s next login, we can simply pass the user entered password through the same hashing function and compare the output hash with the hashing value stored in the database to validate the user. By doing this we can ensure that even in a database breach the user passwords will be safe because the passwords are hashed and the attacker cannot extract the actual passwords from them.</p><h4>Salting</h4><p>If two users use the same password, there will be duplicate hashes in the password database. If an attacker sees this duplication, he will know that both users are using the same password. This gives the attacker the ability to compromise both accounts by compromising one. The solution is to append a system generated random value (salt) to the user entered password before hashing. This is known as salting. It is recommended to use a random value with at least 32 characters long. Remember that we need to store the salt value along with the hash in order to validate the user upon his next login.</p><h4>Why PBKDF2?</h4><p>Naturally in programming developers search for the fastest algorithm. But when it comes to hashing, the algorithms have been made slow intentionally to withstand brute force attacks. The super computing resources available today can attempt billions of hashes per second. If the algorithm is slow, the frequency of those attempts can be made slower. The trick is to make the algorithm slower such that it can withstand brute force attacks and still be fast enough not to harm the user experience.</p><p>MD5 was once a popular hashing algorithm that were used by many applications. But later many weaknesses were found in MD5. There were collisions where same hash was generated by different inputs. Due to these weaknesses the author himself declared that MD5 is unsuitable for hashing in 2005. Secure Hashing Algorithm (SHA) is another popular hashing algorithm. There are several versions such as SHA-0, SHA-1, SHA-2 and SHA-3. Among them SHA-0 and SHA-1 are no longer considered as secure. When Linkedin got compromised in 2012 most of their passwords were stolen because, at that time they were still using SHA-1 to hash their passwords. Even though SHA-0 and SHA-1 were unsuccessful, SHA-2 still has some strength left with it’s different variations of hash lengths. SHA family has also released SHA-3 improving its predecessors.</p><p>If you are a java developer, PBKDF2 is an excellent algorithm to use. In PBKDF2 we can force the algorithm to behave slowly by increasing its iteration count. Following is a simple tutorial explaining how to use PBKDF2 algorithm to hash the passwords.</p><p>Step 1: Create a maven project</p><p>Step 2: Create a Main class inside src/main/java as Main.java</p><p>Step 3: Add the following dependency into your pom.xml within dependencies tag.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;commons-codec&lt;/groupId&gt;<br>    &lt;artifactId&gt;commons-codec&lt;/artifactId&gt;<br>    &lt;version&gt;1.9&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>This dependency is needed to convert the byte array returned by hashPassword() into a String.</p><p>Step 4: Insert the following code into Main.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aea8cdd9290465798fda1eefb063278/href">https://medium.com/media/8aea8cdd9290465798fda1eefb063278/href</a></iframe><p>Finally your pom.xml should look similar to this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6ba2d2e7c619f431f871e1bac800917/href">https://medium.com/media/c6ba2d2e7c619f431f871e1bac800917/href</a></iframe><p>After you run the main() method you will see an output similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbZ06v4nC7xgb2poc9u0_w.png" /></figure><p>This is the final hashed string that can safely store in the database.</p><p>In the Main .java I have created a method called hashPassword() that contains the functionality of PBKDF2. This function has four input variables.</p><p><strong>password </strong>- the password that needs to be hashed. This should be converted<br>into a char array before passing.</p><p><strong>salt</strong>- salt value that should append to the password.</p><p><strong>iterations</strong>- no. of iterations to be done. This value can be used to adjust the speed of the algorithm.</p><p><strong>keyLength</strong>- This is the required output length of the hashed function.</p><p>This function returns a byte array that needs to be converted into a string using a suitable hex encoder. In my project I have used Apache Commons Codec library(See the pom.xml).</p><p>After executing this program with 100000 iterations in a laptop with a 2.6 GHz Core i-7 processor with 16GB RAM, the execution time takes approximately about 500ms and when it is increased up to 200000, the execution takes about 1000ms. Therefore in my opinion, the optimum number of iterations is somewhere between those two values. Anyway it is up to the developer to decide the optimum number of iterations according to the context.</p><h4>References</h4><ol><li>Iron-Clad Java_ Building Secure Web Applications_ Best Practices for Secure Java Web Application Development [Manico &amp; Detlefsen 2014–09–12]</li></ol><p>2. <a href="http://security.blogoverflow.com/2013/09/about-secure-password-hashing/">http://security.blogoverflow.com/2013/09/about-secure-password- hashing/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=204487f14e84" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>