<?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 Prateek Nischal on Medium]]></title>
        <description><![CDATA[Stories by Prateek Nischal on Medium]]></description>
        <link>https://medium.com/@prateeknischal25?source=rss-b4cc533c93a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RfM06Z_eR4jlI_I9.</url>
            <title>Stories by Prateek Nischal on Medium</title>
            <link>https://medium.com/@prateeknischal25?source=rss-b4cc533c93a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 00:23:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prateeknischal25/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[Drunk president and the nuclear launch — Shamir and the duel guy, Galois — III]]></title>
            <link>https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-shamir-and-the-duel-guy-galois-iii-f0fe9d6e0548?source=rss-b4cc533c93a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0fe9d6e0548</guid>
            <category><![CDATA[galois-fields]]></category>
            <category><![CDATA[shamir-secret-sharing]]></category>
            <category><![CDATA[inverse-modulo]]></category>
            <category><![CDATA[finite-field]]></category>
            <category><![CDATA[modular-arithmetic]]></category>
            <dc:creator><![CDATA[Prateek Nischal]]></dc:creator>
            <pubDate>Sun, 09 Dec 2018 18:54:41 GMT</pubDate>
            <atom:updated>2018-12-10T09:46:47.923Z</atom:updated>
            <content:encoded><![CDATA[<h3>Drunk president and the nuclear launch — Shamir and the duel guy, Galois — III</h3><p>Part 1 — <a href="https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-shamir-secret-sharing-i-fdd7f812445a">Drunk president and the Nuclear launch — Shamir Secret Sharing — I</a></p><p>Part 2 — <a href="https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-lagrange-decomposition-of-a-function-ii-20149766e74a">Drunk president and the nuclear launch — Lagrange Decomposition of a function</a></p><p>In school, we were taught Natural numbers, Integers, and Real numbers, everyone was stoked by the concept of infinity and infinite numbers being in between any 2 real numbers, there was <em>just no end</em> to the amazement !! Too many numbers to handle. The last one came after a very long time. C , the <a href="https://en.wikipedia.org/wiki/Complex_number">Complex Numbers</a>. I could never have <em>imagined</em> something like that. I like it though, it’s so unbiased, it won’t even compare 2 numbers.</p><p>Let’s take a step back, and discover a Number system that does not have a whole lot of numbers but are devilishly complex, not like our friend C but in its own ways. Let’s look at the simplest ones.</p><h3>Finite field or Galois Field</h3><p>Consider a Set of numbers that has q elements (field’s order). It’s a Finite field iff q is a positive power of a prime number. All the elements need to follow the basic rules of addition, subtraction, multiplication and division called the <a href="https://en.wikipedia.org/wiki/Field_(mathematics)">Field Axioms</a>. The result of all operations must lie within the Finite field, which is it should be present in the set of q elements.</p><p>Let’s consider the simplest case for our use: GF(p) read as Galois Field of order p and this contains {0, 1, 2,..., p — 1} . To keep all the results within the set we loop back the numbers, like a ring, say p=5 and you add 3 and 4. In a normal world you would see the answer as 7 but in GF(5), since nothing beyond 4 exists, 3 + 4 = 2, why 2? We looped 7 back so our counting is, if you will, 0, 1, 2, 3, 4, 0, 1, 2, … That is how you would map your real world numbers from Integers to GF(5). This operation of mapping is a result of <strong>modulo </strong>operation, the 5th fundamental arithmetic operation. It’s very similar to taking remainder.</p><p>So, now that we are sufficiently pleased, Let’s try out some basic modulo</p><p>This defines a modulo operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*CLWvPdYSemGLDXbW" /><figcaption>representing in modulo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*4lnbcG2U7dp03i4S" /><figcaption>I think you get the point</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WKgZroIxF-e6-MKZ" /><figcaption>Similarly for multiplication</figcaption></figure><h4>Just for fun</h4><p>An interesting outcome of this is operation in GF(p) is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*0tGp_NI8yZLMDazdksYizA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*TH3Kde4lfr0Ytbl15mrTHw.jpeg" /><figcaption>No one understood this guy, He LIKES Galois field !!! (source: <a href="https://i.imgflip.com/2g98ar.jpg">Imgflip</a>)</figcaption></figure><p>Another gold coming through your way: The proof is left as an exercise for the reader</p><p>Just kidding !!</p><p>Expand the expression using <a href="https://en.wikipedia.org/wiki/Binomial_theorem">binomial expansion</a>, and you’ll see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*drkSxpINIEx2o1YwxZg3Vw.png" /></figure><p>Since all numbers x, y, p are integers, all terms in the expression too should be integers. Let’s analyse one.</p><p>You can expand the binomial coefficient and write it as a product of p and the remaining part. There is no term in the denominator that divides p as it’s a prime number and r &lt;= p in this case. We know that whole term is an integer. So the remaining part too should be an integer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*ADIEWVHgkpLI9ZxK" /></figure><p>This means that all the terms except the first and the last in the binomial expansion are integral multiples of p and will vanish when evaluated modulo p</p><p>Addition, and by extension, subtraction are trivial and so is multiplication. But in case of division, this get’s a little tricky. We are talking about getting remainders for potential floating point number say 2/3 mod 5 which does not make sense as, Finite fields are defined as a subset of positive <strong>Integers.</strong></p><p>Fret not, let’s analyse the above case as the basic definition of modulo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/0*FbgGzgaNuVlNCnta" /></figure><p>Nothing wrong in this right, we can write a in whatever representation as it currently belongs to Real numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/0*9v6hmm46lG_3f7vC" /></figure><p>Suppose we multiple both sides with the denominator. We get good integers both sides and since we did not change the meaning of the equation, it still holds valid and behaves the same as the first one. Now we can safely restrict the number space to Integers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*UElbDdV0nETdp6Gs" /></figure><p>2/3 is the remainder of a when divided with p which is equivalent to 2 being the remainder of 3a being divided by p .So if we figure out what is a we would know the value of the modulo of 2/3. All we need to solve is 3a = 2 mod 5</p><p>Let’s try by hand. 3a = {3, 6, 9, 12, 15, … } , I think we have our solution, for a = 4, 3a = 12 = 2 mod 5 , So 2/3 mod 5 behaves same as 4 in GF(5)</p><p>So, we know how to get a multiplicative inverse. But how feasible is this calculation for larger fields say GF(1000000007), how long would you keep multiplying a check if things coincide.</p><h4>Fermat’s little theorem</h4><p>The guys is infamous for <a href="https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem">writing proofs on margins</a>, but thank god we are not dealing with his <a href="https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem">last theorem</a>, but the little one. It states that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*12PvH6NZWV5MbPOy" /></figure><p>When a is raised to the power of a prime p, has a remainder of a when divided by p . There is a simple <a href="https://primes.utm.edu/notes/proofs/FermatsLittleTheorem.html">proof</a> to it which is not necessary here.</p><p>Assume that a and p do not have any factor in common, which is gcd(a, p) = 1 , we can safely assume</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*fcsfivGUUuxxjR4x" /></figure><p>Since, p and a do not have anything in common, p has to divide a^(p-1)-1</p><p>We have already seen that we can divide by a number on both sides of modulo, as they would behave in the same way. So, let’s divide both sides by a in the above equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/0*sJtFdRu__zA94THj" /><figcaption>compute multiplicative inverse in GF(p)</figcaption></figure><p>So, all we need to do is compute a^(p-2) mod p and that will be the inverse or multiply the above term to simulate division in GF(p).</p><p>In our computation of our p(0) to find our secret, we saw that we had some division computations too that caused the results to be in floating point. Let’s rectify that by making computations in a prime field.</p><p>Code: <a href="https://github.com/prateeknischal/SecretShamir/blob/master/shamir_finite.py">Shamir in Finite fields</a></p><pre>$ python shamir_finite.py gen<br>850, 619<br>996, 130<br>419, 37<br>345, 69<br>950, 860<br>349, 486<br>310, 938<br>$ python shamir_finite.py solve<br>Usage: Enter space separated values for mentioned<br>type, X or Y. eg:<br>X: x1 x2 x3 ...<br>Y: y1 y2 y3 ...</pre><pre>X: 850 996 419 345 950<br>Y: 619 130 37 69 860<br>29</pre><p>Now, we see that we get a concrete integral answer, which is what we expect. So are we done with this. Yes, we have a working solution in finite fields which is perfectly fine and can be used for studying.</p><h4>What more do we observe</h4><p>If we start nitpicking and see in the perspective of implementation, 2 things show up.</p><ol><li>Any prime will work, but we would prefer a power of 2 because, calculations on Extended Galois Fields (of the type GF(p^k), k &gt; 0)are still feasible and it’s easier for a machine with 2 states to work on powers of 2.</li><li>The Inverse calculation is done as by raising the number to a huge power and then taking modulo which requires O(log P) steps and each step comprises of 1 multiplication, 1 addition and 2 modulo operations.</li></ol><pre>def pow_mod(a, n, p):<br>  # calculates a^n (mod p)<br>  d, s = a, 1<br>  while n &gt; 0:<br>    if n &amp; 1: s = (s * d) % p<br>    d = (d * d) % p<br>    n &gt;&gt;= 1<br>  return s</pre><p>and be advised, all of these numbers are meant to be huge, like for context, the Wikipedia implementation uses the 12th <a href="https://en.wikipedia.org/wiki/Mersenne_prime">Mersenne prime</a> which is 2^127–1 = 170141183460469231731687303715884105727 to make the search space huge to make brute force infeasible.</p><p>Non-Native multiplications (whose word size is greater than CPU word size, i.e. 64-bit processors) take much more time that simple additions and Fermat’s little theorem only works on prime numbers.</p><p>Both the problems can be solved by using Extended Galois fields which aren’t primes anymore and using another method to calculate the multiplicative inverse called <a href="https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm">Extended Euclidean Algorithm</a>.</p><p>This brings us to the apparent end (there is always more to everything). Now we can use this cool scheme to share secret keys and not let the drunk president destroy mankind.</p><p>A small closing note — the above implementation still requires use of big integer libraries, it is just reducing the number of multiplications. Another way of doing this is, Generate multiple polynomials, say 16 polynomials, and then calculate a distinct key in GF(2⁸), so you get an 8 bit keys. Now combine all the 8-bit keys from all 16 polynomials and there you have a larger key with the 128-bit strength and same purpose, just that each person will have 16 8-bit keys, which makes no difference and is purely on implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0fe9d6e0548" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drunk president and the nuclear launch — Lagrange Decomposition of a function — II]]></title>
            <link>https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-lagrange-decomposition-of-a-function-ii-20149766e74a?source=rss-b4cc533c93a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/20149766e74a</guid>
            <category><![CDATA[math]]></category>
            <category><![CDATA[lagrange-decomposition]]></category>
            <category><![CDATA[decomposition-proof]]></category>
            <category><![CDATA[shamir-secret-sharing]]></category>
            <category><![CDATA[hashicorp-vault]]></category>
            <dc:creator><![CDATA[Prateek Nischal]]></dc:creator>
            <pubDate>Sun, 09 Dec 2018 18:53:06 GMT</pubDate>
            <atom:updated>2018-12-09T19:20:27.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>Drunk president and the nuclear launch — Lagrange Decomposition of a function — II</h3><p>Part 1 — <a href="https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-shamir-secret-sharing-i-fdd7f812445a">Drunk president and the Nuclear launch — Shamir Secret Sharing</a></p><p>You might have landed here because of the above-linked article to go deeper into the rabbit hole. If not, I am impressed by your perseverance, either you are stuck with math homework and looking desperately for help or just have too much time on your hands to have landed here.</p><p>Oh wait, medium.com tags are good too, and search engines these days are running tags on steroids with the ML hype. Crunch everything you can and raise prices for Nvidia <a href="https://www.nvidia.com/en-us/geforce/graphics-cards/rtx-2080-ti/">RTX 2080 Ti</a> and <a href="https://www.nvidia.com/en-us/geforce/products/10series/titan-x-pascal/">Titan X</a>. No, I am not a sales rep from Nvidia.</p><p>So, coming back to our problem, given N+1 points (x,y) where for a Nth degree function, how do I determine a particular co-efficient without wasting the precious compute power of my <a href="https://www.raspberrypi.org/products/raspberry-pi-zero/">Raspberry pi zero</a>.</p><p>By now, you would have realized that you can’t calculate a single coefficient ai individually. You get all or none, just like my jokes. We will consider the secret at the first constant a0 because it provides computational feasibility without losing any information.</p><h3><strong>How to construct the polynomial</strong></h3><p>We want to find a polynomial such that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/0*GimxhQh0u0S2wuj_" /></figure><p>Assume that you have a polynomial such that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/0*Mha-ps5rdwh_tvZC" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/0*NasTdhMCrEHEEUbP" /></figure><p>Now what good does this do. We can construct p(x) from those polynomials given xi, yi . How ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*DvnKbIAM8NTQRBIN-Pt7lA.png" /></figure><p>If you substitute x = x0 all polynomials except y0 will vanish. That’s the case will all values of x and y. This means, with whatever information we have, we simulated the original polynomial used to derive the shared keys. All we need to find out now are those smaller polynomials.</p><p>Let’s try to fulfil the first condition of each pi(x) .</p><ol><li>Function must return 0 on all values except one</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*m1fHyqOAQ-Ynt2PX8KyiRA.png" /></figure><p>This is the simplest polynomial that fulfills the first condition, <a href="https://en.wikipedia.org/wiki/Triviality_(mathematics)">It’s trivial</a>, as they say.</p><p>2. It must return 1 for the one missed value xi . If we solve the above equation with x=xi and pi(xi) = 1 we can see that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*Y42NuLzC2SWDC4QC" /></figure><p>making the smaller polynomial</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*jmAonNgIl-_YFxg0" /></figure><p>Now let’s look what do we need to find actually. That was a Lagrange decomposition of the function by the way.</p><p>Since we modeled our function p(x) as the key generating function, the same polynomial that we discarded after generating the key, and we agreed to making the Secret as a0 which is conveniently equal to f(0) thus equal to p(0) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*DycGrI-7DGrfmVTg5hOL7g.png" /></figure><p>So all we need to find is p(0)</p><p>Let’s construct the condensed form of the equation, trust me, that will help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/0*0m3faYjT2UdD_yPb" /></figure><p>Again, replace the smaller polynomials pi(x) with the condensed product form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*-mrn2v8S2wSnKtJo" /></figure><p>Now putting this all together, we come with the below form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*08Om8rLXwNSSvUOp" /></figure><p>Now, we are ready to get the value of p(0)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/0*QD0mlAAO4wfbbXxM" /></figure><p>Now this, we can calculate easily and in O(N²) time complexity.</p><p>A simple implementation: <a href="https://github.com/prateeknischal/SecretShamir/blob/master/shamir_simple.py">Basic Shamir</a></p><pre>$ python shamir_simple.py gen<br>86, 5004526649<br>55, 839710439<br>4, 26141<br>42, 286285385<br>76, 3054424829<br>7, 233255<br>89, 5739193331</pre><pre>$ python shamir_simple.py get<br>X: 86 4 89 76 42<br>Y: 5004526649 26141 5739193331 3054424829 286285385<br>28.9999959767</pre><p>If you check the implementation, you’ll see that the secret is 29 but we get a value close to 29. This happens because there is a division aka floating point operation in the solution.</p><p>There is an element of information leak here. Let’s go back to the original straight line equation that we had seeing how a line can’t be fixed with just 1 point. Assume m is 1 to make things simpler. Also, we are trying to leak some info, so it is ok to assume that we have a subset of required keys. In this case assume we own the key (2, 4)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*Tx0gIP_aJT9SvNGq" /></figure><p>We have assumed that all coefficients are integers, so with the below equation after substituting the keys known to us,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*LKPNfm6hnHIjoZgm" /></figure><p>we can derive that a0 needs to be an even number to make a1 an integer which reduces the search space.</p><h4>A small comment on the explanation on Wiki</h4><p>Wiki assumes that all coefficients are Natural numbers that leak even more information, in our case that assumption will lead to a solution with only one point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/0*MXMuJnulCAJl00rX" /></figure><p>In our case, we have assumed that the numbers belong to Integers except 0, so we only have one information leak (still not desired), that the number is even.</p><p>To solve this issue (check the next part for this) and the above precision issue we move all the calculations to a <a href="https://en.wikipedia.org/wiki/Finite_field">Finite Field</a>.</p><p>Ok, that’s something which is generally not taught in schools. Certainly, asking the drunk president to deal with Finite field math, he would prefer launching the missile.</p><p>Oh, by the way, did you notice, the above method has a fail safe as well, that relies on traditional key management. Just let one person have the Secret, like the head of an Org. In case of his losing the key, or some mercenaries overthrowing the head, the secret is lost, it can always be regenerated using the keys and passed on to the new head. I would refrain to let the drunk president have it though, just sayin’.</p><p>There is still more to it, check out the <a href="https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-shamir-and-the-duel-guy-galois-iii-f0fe9d6e0548">third part</a> for getting over the precision problem.</p><p>Part 3 — <a href="https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-shamir-and-the-duel-guy-galois-iii-f0fe9d6e0548">Drunk president and the nuclear launch — Shamir and the duel guy, Galois — III</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20149766e74a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drunk president and the Nuclear launch — Shamir Secret Sharing — I]]></title>
            <link>https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-shamir-secret-sharing-i-fdd7f812445a?source=rss-b4cc533c93a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdd7f812445a</guid>
            <category><![CDATA[hashicorp-vault-key-share]]></category>
            <category><![CDATA[shamir-secret-sharing]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[secret-sharing]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Prateek Nischal]]></dc:creator>
            <pubDate>Sun, 09 Dec 2018 18:50:44 GMT</pubDate>
            <atom:updated>2018-12-09T19:27:16.597Z</atom:updated>
            <content:encoded><![CDATA[<h3>Drunk president and the Nuclear launch — Shamir Secret Sharing — I</h3><p>Suppose you work for a president who likes to flaunt their nuclear strength, but you understand the responsibility of owning a nuclear weapon. So you need to save the world from the drunk president. One thing you could do is break up the key into multiple pieces and let the drunk fella have only 1 of the pieces.</p><p><strong>The formal problem statement</strong></p><p>Given a secret S, divide it into k pieces such that any combination of N+1 pieces can recover the secret. It must be computationally easy to compute and If you have the number of pieces less than k it should be computationally infeasible to calculate the secret.</p><p>So, now you know it’s a terribly simple (spoiler alert) method called <a href="https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing">Shamir’s Secret Sharing</a>. Given that wiki has a complete explanation to it, you have 2 choices left, abandon reading this and jump to the provided link or continue having fun over my discreet way of writing.</p><p>So, you are still here, guess you’ll get a tickle or two.</p><p>Let’s go back to grade school and re-visit straight lines. Given a point in 2D space, how many straight lines can you draw passing through the point?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*Ge5rb8e5NmsfaEqHIxUqCw.png" /><figcaption>multiple lines through 1 point</figcaption></figure><p>There can be infinitely many lines that pass through a single point which in this case is (2, 4) .The general equation of lines passing through this is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/0*l8sFD62BhsyUJR2b" /></figure><p>Suppose we fix another point, then we can draw a fixed line. The above line is rotating around the point (2,4), probably high on some spiral, let’s leave it at that. Fix another point, say (0, 2) and we can solve for m in the above equation.</p><p>Let’s generalize this now, as every math text says,…</p><p>Given a function f of degree N such that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/0*0LaPPmrwvvOgj4IR" /></figure><p>To uniquely identify the above curve, you need N+1 parameters, which are all the constant terms in the equation. If you know same number of relations between unknowns as there are number of unknowns, all of them can be solved for. Which implies,</p><blockquote>You would need at least N+1 points (x, y) to fix the curve where all values of x are distinct.</blockquote><p>Substitute all the points in the above equation and you’ll get a set of N+1 equations with N+1 variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*yG_2YGyTcLl4jyOf" /></figure><p>If you have any less than N+1 equations, you won’t be able to solve for all variables and you’ll get a family of curves, which will do no good. (If you are not careful, it might hurt you)</p><p><strong>Note: </strong>The degree N is also an important aspect, when defining a function, because you can plot a fixed line through 2 points although you cannot define a fixed parabola using just 2 points. Our requirement is to get a fixed curve. So if we want to derive a fixed curve of degree N we would need N+1 points exactly.</p><p>So, you would now ask, where is the safeguard I promised, sharing a key between multiple people. So let’s begin with deriving the shared keys.</p><p><strong>Note</strong>: Generating exactly N + 1 keys would not be fault tolerant one of the applications of Shamir secret sharing is that you can lose a certain number of keys before making it irrecoverable.</p><ul><li>Choose k such that k &gt; N + 1</li><li>Generate k unique random numbers x0, x1, .. x(k-1) and corresponding values of y using the curve f(x)</li><li>We have derived k keys now, and each key is represented as</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/0*G-uO2AI6srxh1Dbl" /><figcaption>ith key</figcaption></figure><ul><li>Distribute the keys to k people and throw away the constants in the original equation, purge it, have no trace of it, and I don’t mean <a href="https://en.wikipedia.org/wiki/Trace_%28linear_algebra%29">trace</a> but <a href="https://www.merriam-webster.com/dictionary/trace">trace</a></li></ul><p>Wait, is that it…</p><p>Yes, that’s it. All you need is any N + 1 points from the set of keys and would be able to solve the curve. In this process, you can use any of the values a0, a1, a2, ..., an as your secret that you want to share. Unless you have atleast N + 1 points you can not solve for all values of a.</p><p>To get the feel of it, try solving this (the above equation for m=1 ) with the substitution of the point (2, 4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/0*6qP79WcUupKOnnha" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*uLZBD-gazq4DVEvA" /><figcaption>destroying all coefficients</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*LKPNfm6hnHIjoZgm" /></figure><p>Not possible right, to pin-point the curve, you get a family of curves with the variable m.</p><p>Either you can believe me, it’s true for the above-generalized equation too, anything less than N+1 equations, and you are in for a ride, or I am going to use the strongest weapon, Proof is left as an exercise to the reader .</p><p>Let’s go through an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*dJosPNAmxiOzbrxw" /><figcaption>Let 7 be the secret we need to share</figcaption></figure><p>and we derive keys from it which are (1, 6), (2, 7), (3, 10), (4, 15)</p><p>Let’s forget the equation and only remember that we need 3 keys to unlock whatever is locked by the shared keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/0*bfaB7cvJoMRdvXBR" /></figure><p>by solving this, we get a2=1, a1=-2, a0=7 which tells us the exact curve and we get our value 7 to unlock. Okay, but how did we solve this and how can we make it easier, as solving a set of linear equations is not easy at all. Some ways that you can solve are <a href="https://en.wikipedia.org/wiki/Cramer%27s_rule">Cramer’s Rule</a> and <a href="https://en.wikipedia.org/wiki/Gaussian_elimination">Gauss Jordan Elimination</a> (When the <a href="https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss">prince</a> has a way, you oblige)</p><p>But the thing is that we don’t need all the constants, we only need one of them, so why find all of them.</p><p>Enter <a href="https://en.wikipedia.org/wiki/Joseph_Louis_Lagrange">Joseph-Louis Lagrange</a> and his weird enough intuition. But sad enough, we are exiting now. I don’t intend to make this too long because</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*M7EP13EYQlwVXpnHaFBsOA.jpeg" /><figcaption>source: <a href="https://i.pinimg.com/originals/56/ef/19/56ef195bd3d1ae34c9c9c08abe921cc4.jpg">Pinterest</a></figcaption></figure><p>Need more, look up the <a href="https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-lagrange-decomposition-of-a-function-ii-20149766e74a">second part</a>, deeper down the rabbit hole, more towards the real world.</p><p>Part 2 — <a href="https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-lagrange-decomposition-of-a-function-ii-20149766e74a">Drunk president and the nuclear launch — Lagrange Decomposition of a function — II</a></p><p>Part 3 — <a href="https://medium.com/@prateeknischal25/drunk-president-and-the-nuclear-launch-shamir-and-the-duel-guy-galois-iii-f0fe9d6e0548">Drunk president and the nuclear launch — Shamir and the duel guy, Galois — III</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdd7f812445a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using encrypted private keys with Golang HTTPS server]]></title>
            <link>https://medium.com/@prateeknischal25/using-encrypted-private-keys-with-golang-server-379919955854?source=rss-b4cc533c93a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/379919955854</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[encrypted]]></category>
            <category><![CDATA[private-key]]></category>
            <category><![CDATA[tls-server]]></category>
            <category><![CDATA[x509]]></category>
            <dc:creator><![CDATA[Prateek Nischal]]></dc:creator>
            <pubDate>Tue, 02 Oct 2018 03:17:36 GMT</pubDate>
            <atom:updated>2018-10-02T08:59:30.819Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-f7pypAmnusienQJh720Eg.jpeg" /><figcaption>Yes, this is an Owl, protecting my traffic</figcaption></figure><p>Coming from a Java world (I am embarrassed enough), this hit me like a wall. Default golang <a href="https://golang.org/pkg/net/http/?#Server">http.Server</a> does not have a way to accept private keys that are protected by a passphrase. If you look up the documentation for <a href="https://golang.org/pkg/net/http/?#Server.ListenAndServeTLS">server.ListenAndServerTLS</a>, it needs 2 parameters, the certFile and keyFile strings, that represent the location of PEM encoded format for certificate and private key. There is no option to supply the password !!</p><p>Another weird thing I saw is there is field in the <a href="https://golang.org/pkg/net/http/?#Server">http.Server</a> struct, it has a <a href="https://golang.org/pkg/crypto/tls/#Config">tls.Config</a> parameter that too has a field to configure the <a href="https://golang.org/pkg/crypto/tls/#Certificate">tls.Certificate</a> object and that is not just for Certificates but for PrivateKey as well. I thought, why does it need the parameters in server.ListenAndServerTLS when it already has it. I got into the messy part because I can’t read documentation.</p><pre>func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {<br> // Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig<br> // before we clone it and create the TLS Listener.<br> if err := srv.setupHTTP2_ServeTLS(); err != nil {<br>  return err<br> }</pre><pre>config := cloneTLSConfig(srv.TLSConfig)<br> if !strSliceContains(config.NextProtos, &quot;http/1.1&quot;) {<br>  config.NextProtos = append(config.NextProtos, &quot;http/1.1&quot;)<br> }</pre><pre>configHasCert := len(config.Certificates) &gt; 0 || config.GetCertificate != nil<br> if !configHasCert || certFile != &quot;&quot; || keyFile != &quot;&quot; {<br>  var err error<br>  config.Certificates = make([]tls.Certificate, 1)<br>  config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)<br>  if err != nil {<br>   return err<br>  }<br> }</pre><pre> tlsListener := tls.NewListener(l, config)<br> return srv.Serve(tlsListener)<br>}</pre><p>It is first checking the TLSConfig that we might have supplied, if not then it would use the supplied cert and key file names.</p><p>It occurred to me, why not we try to build the <a href="https://golang.org/pkg/crypto/tls/#Certificate">tls.Config.Certificate</a> with the encrypted key file that we have.</p><h3>Let’s get to some action</h3><p>How do you load a plain cert and key files to build a Certificate Object</p><p><a href="https://golang.org/pkg/crypto/tls/#LoadX509KeyPair">tls.LoadX509KeyPair(certFile, keyFile string)</a> or <a href="https://golang.org/pkg/crypto/tls/#X509KeyPair">tls.X509KeyPair(certPEMBlock, keyPEMBlock []byte)</a></p><p>The first one takes file names and second one takes PEM encoded blocks. First is no use, as it is the same as the Server interface. The second one looks interesting. Let’s try to get the private key as a PEM block.</p><p>But first, What is PEM encoding. There is a very interesting and intimidating thing called <a href="https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One">ASN.1</a> that can be used to serialise structures and cryptographic implementation uses the DER encoding rules to store the ASN.1 structures.</p><p>A basic guide for layman can be found here: <a href="http://luca.ntop.org/Teaching/Appunti/asn1.html">ASN.1</a> and surprisingly here: <a href="https://docs.microsoft.com/en-us/windows/desktop/seccertenroll/about-der-encoding-of-asn-1-types">DER encoding for ASN.1</a></p><p>For now just think of those as serialization techniques and know that DER is a binary encoding scheme or it produces binary output. Which is ok to store on disk. But when you have to transfer it over emails, for which PEM (Privacy enhanced mails) was originally built, which is plain text, you need to make it a little simpler.</p><p>Here comes the <a href="https://en.wikipedia.org/wiki/Base64">base64</a> cannon. Another encoding scheme on top of an encoding scheme (I know, right !!). It can represent any binary data as printable characters. eg:</p><pre>$ echo hello | xxd<br>00000000: 6865 6c6c 6f0a                           hello.</pre><pre>$ echo -ne &quot;\x68\x65\x6c\x6c\x6f\x0a&quot; | base64<br>aGVsbG8K</pre><pre>$ echo &quot;aGVsbG8K&quot; | base64 -D<br>hello</pre><p>Yay ! So now you can transmit binary data in a printable format.</p><p>PEM is the fancy name for this base64 encoding of DER format. Try this for fun, it’s pure pleasure :D</p><pre>$ wget <a href="https://secure.globalsign.net/cacert/Root-R1.crt">https://secure.globalsign.net/cacert/Root-R1.crt</a><br>$ cat Root-R1.crt | base64<br>MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==</pre><pre>$ openssl x509 -in Root-R1.crt -inform DER -outform PEM<br>-----BEGIN CERTIFICATE-----<br>MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG<br>A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv<br>b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw<br>MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i<br>YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT<br>aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ<br>jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp<br>xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp<br>1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG<br>snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ<br>U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8<br>9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E<br>BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B<br>AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz<br>yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE<br>38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP<br>AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad<br>DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME<br>HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==<br>-----END CERTIFICATE-----</pre><p>Look at both of the outputs, They are the same, with a better formatting though. And the</p><pre>-----BEGIN CERTIFICATE-----<br>...<br>-----END CERTIFICATE-----</pre><p>part is according to the RFC which tells about the type of the PEM block.</p><p>Coming back to our problem,</p><p>If we can get golang a PEM block that has the private key unencrypted, bingo. First let us get the PEM block in golang Native structs.</p><p><a href="https://golang.org/pkg/encoding/pem/">encoding/pem</a> has a useful function: <a href="https://golang.org/pkg/encoding/pem/#Decode">Decrypt(data []bytes)(p *pem.Block, rest []byte)</a>. This function goes through the bytes and tries to find the marker of the PEM block and returns the first block as a pointer to <a href="https://golang.org/pkg/encoding/pem/#Block">pem.Block</a></p><pre>-----BEGIN Type-----<br>Headers<br>base64-encoded Bytes<br>-----END Type-----</pre><p>Let’s try to see how to write this thing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9775089e9948d829a5703ab22ac9ec7/href">https://medium.com/media/e9775089e9948d829a5703ab22ac9ec7/href</a></iframe><p>Not bad, but we still haven’t reached the magic yet.</p><p>Another amazing function, a pair actually, that golang’s crypto library provides is</p><ul><li><a href="https://golang.org/pkg/crypto/x509/#IsEncryptedPEMBlock">IsEncryptedPEMBlock(b *pem.Block) bool</a></li><li><a href="https://golang.org/pkg/crypto/x509/#DecryptPEMBlock">DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)</a></li></ul><p>Check if a PEM block is encrypted, if yes, decrypt it. Yes, it’s that awesome.</p><p>All you need now is check if the detected Private key block is encrypted, If yes, decrypt it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e78dd47978eeb18e4a3a4af82413fddd/href">https://medium.com/media/e78dd47978eeb18e4a3a4af82413fddd/href</a></iframe><p>And, that was it.</p><p>If you would have seen the signature of the <a href="https://golang.org/pkg/crypto/tls/#X509KeyPair">tls.X509KeyPair</a>(certPEMBlock, keyPEMBlock []byte) all they need is a PEM block as bytes. And <a href="https://golang.org/pkg/encoding/pem/#Block">pem.Bloc</a>k already has a Block.Byte Value. What’s this for ?</p><p>This is the DER encoding of the ASN.1 structure and we just don’t need bytes in the function, but a well formed PEM block with all the markers and headers (yes, that took me a couple of hours and some facepalms to find out, as I read documentation as carefully as people think about their passwords.)</p><p>Now, how do you protect the password to the encrypted private key, is another problem altogether and my face already has enough finger marks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=379919955854" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modding JJWT]]></title>
            <link>https://medium.com/walmartglobaltech/modding-jjwt-562ae8b444e2?source=rss-b4cc533c93a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/562ae8b444e2</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Prateek Nischal]]></dc:creator>
            <pubDate>Fri, 28 Apr 2017 00:35:26 GMT</pubDate>
            <atom:updated>2018-02-23T15:40:28.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*_vuJZVJReJb03fslQIaIJg.jpeg" /><figcaption>Credit : <a href="https://pixabay.com/en/computer-security-padlock-hacker-1591018/">Pixabay</a></figcaption></figure><p><strong>JSON Web Tokens:</strong></p><p>According to <em>RFC#7519</em> JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.</p><p>JWT contains 3 parts appended in a particular order.</p><p>1. Header — containing metadata about the token itself, example : type of token, signing algorithm used (<em>‘NONE’ </em>when not signed)</p><p>2. Claims set / payload — The JWT Claims Set represents a JSON object whose members are the claims conveyed by the JWT.</p><p>3. Signature — Contains the signature of header and claims set using the algorithm mentioned in Header.</p><p>Construction :</p><p><em>H</em> : urlBase64(header)</p><p><em>P</em> : urlBase64 (payload)</p><p><em>S</em> : urlBase64 (signature(H || . || P)) (|| implies concatenation)</p><p>Token : <em>H || . || P || . || S</em></p><p>Signature part of the token is optional but it needs to have 3 sections connected by a “period”.</p><p><strong>Token Based Authentication</strong></p><p>For stateless services, authentication is done by using tokens. These tokens must contain sufficient information to authenticate the sender of the request. Since these are tokens, we also need to verify the authenticity of the issuer. The tokens must be such that no one should be able to forge them and only intended parties can verify it.</p><p>Tokens may contain a field of authority to determine access to a resource on a web page or application. It may be ‘user’ or ‘admin’. These tokens are not meant to store any sensitive information as they are just base64 encoded JSONs. (Although they can optionally be encrypted using JWE standard). So it is easy to create a payload. But, one must not be able forge a payload. This is taken care by the signature part of the token.</p><p>To obtain a token, the user first needs to supply its user credentials. When validated, the service returns a token with corresponding authentication and authorization information in the payload signed using its asymmetric key. These tokens generally contain the identification of the issuer and identification of the audience to which it was intended. These tokens are recommended to be short lived.</p><p><strong>Use Case:</strong></p><p>A RESTful service is developed to store sensitive information in the form of encrypted entities. It supports persistence of the entity which can be retrieved/modified by an authorized user. To handle the authorization, JWT tokens signed by an asymmetric key either supplied by the client or generated by the service at the time of registration needs to be presented in the request. This token is verified as a means to authenticate the request.</p><p><strong>The Problem:</strong></p><p>To build the JWT tokens, we use a java implementation of the specification — JJWT. We construct a token as follows :</p><pre>String compactJws = Jwts.builder()</pre><pre>    .setSubject(“Joe”)</pre><pre>    .signWith(SignatureAlgorithm.HS512, key)</pre><pre>    .compact();</pre><p>And to verify a token compactJws as follows:</p><pre>try {</pre><pre>    Claims claims = Jwts.parser()</pre><pre>        .setSigningKey(key)</pre><pre>        .parseClaimsJws(compactJws)</pre><pre>        .getBody();</pre><pre>        //OK, we can trust this JWT</pre><pre>} catch (SignatureException e) {</pre><pre>    //don&#39;t trust the JWT!</pre><pre>}</pre><p>This builder interface provides a signWith(Algorithm, key) function that accepts an algorithm from a set of pre-defined and supported algorithms defined in the library and a <strong>clear</strong> key for signing. PCI DSS 3.0 Guidelines states:</p><blockquote>3.5.1: “Restrict access to cryptographic keys to the fewest number of custodians necessary”</blockquote><blockquote>3.5.4: “<strong>Store cryptographic keys in the fewest possible locations</strong>”</blockquote><p>Also, the application is designed to segregate roles into layers. So all we should have is a handle to the actual key in the business logic that provides the token. The cryptographic tasks should be segregated into a crypto layer i.e. the business logic must not be concerned with the keys itself.</p><p>Similarly, for verification it provides with setSigningKey(Key) that picks up the algorithm from the header and does the verification. Again, this key too needs to be in clear.</p><p>The current concern is, how do we sign with mere handles to actual keys using JJWT as JJWT library has its own provider that uses JCE interface for cryptographic tasks and have specific interfaces to accept input.</p><p>At the time of development, the library did not support having custom implementations for Algorithms and providers for delegating encryption to a different service and with no timeline for it, the library had to be modified.</p><h4>The solution:</h4><p>The Builder and Parser interfaces need to be modified. 2 new methods are introduced in both the interfaces.</p><pre>JwtBuilder setCryptoProvider(CryptoProvider cryptoProvider);</pre><pre>JwtBuilder setConfigParams(Map&lt;String, Object&gt; config);</pre><p>The first method allows the library to accept a custom crypto provider that is user specific and can contain whatever logic until it implements the CryptoProvider interface added in the library.</p><p>The cryptoProvider Interface –</p><p>It contains two basic methods that is used for token building and verification.</p><pre>/**</pre><pre>*</pre><pre>* <strong>@param</strong> plain the string that needs to be signed</pre><pre>* <strong>@param</strong> config configuration hashmap that requires exclusive information required for sign</pre><pre>* This config map can be implementation specific as the user will have to implement the CryptoProvider and provide</pre><pre>* an instance for using jjwt.</pre><pre>* <strong>@return</strong> String the signed value as a String</pre><pre>*</pre><pre>* Parsing of the config map is left for the implementation</pre><pre>*/</pre><pre><strong>public</strong> String sign(String plain, Map&lt;String, Object&gt; config)</pre><pre><strong>throws</strong> SignatureException;</pre><pre>/**</pre><pre>*</pre><pre>* <strong>@param</strong> plain the string that has been signed</pre><pre>* <strong>@param</strong> sign the sign that is to be verified for the given plain text</pre><pre>* <strong>@param</strong> config configuration hashmap that requires exclusive information required for verify</pre><pre>* This config map can be implementation specific as the user will have to implement the CryptoProvider and provide</pre><pre>* an instance for using jjwt.</pre><pre>* <strong>@return</strong> Boolean value identifying if the sign is valid or not</pre><pre>*/</pre><pre><strong>public</strong> Boolean verify(String plain, String sign,</pre><pre>Map&lt;String, Object&gt; config) <strong>throws</strong> SignatureException;</pre><p>The config params that are passed in the second method added to the interfaces contains users-specific information. This is intended to support a user-specific implementation for cryptographic functions. Hence it is opaque to the library. These config map can be blindly passed to the implementation of the cryptoProvider. It is on the implementing class how to use it. It can implement its own protocols for token signing, delegating this to another service or to an HSM. All of the metadata required can be stored in the config map.</p><p>To actually use these added functions, the code had to be changed in the library so as to override library’s sign/verify call when both cryptoProvider and configure are explicitly set.</p><p>So by supplying a CryptoProvider implementation and relevant config, the default behaviour can be delegated to the application’s own implementation overriding JJWT’s JCE Implementation.</p><pre>String token = Jwts.<em>builder</em>().setId(ID)</pre><pre>    .setIssuedAt(now)</pre><pre>    .setExpiration(exipration)</pre><pre>    .setCryptoProvider(cryptoProvider)</pre><pre>    .setConfigParams(config).compact();</pre><p>config is a Map&lt;String, Object&gt;() and cryptoProvider is an instance of a class implementing CryptoProvider interface from the library.</p><p>Similary verification works as follows :</p><pre>claims = Jwts.<em>parser</em>()</pre><pre>    .setCryptoProvider(cryptoProvider)</pre><pre>    .setConfigParams(config)</pre><pre>    .parseClaimsJws(token).getBody();</pre><p>With this design change, the cryptographic responsibility can be abstracted out without affecting backwards compatibility.</p><p>links : <a href="https://github.com/jwtk/jjwt">https://github.com/jwtk/jjwt</a></p><p>modded version : <a href="https://github.com/prateeknischal/jjwt">https://github.com/prateeknischal/jjwt</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=562ae8b444e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/modding-jjwt-562ae8b444e2">Modding JJWT</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>