<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[/dev/]]></title><description><![CDATA[by Paul Thompson]]></description><link>https://devslash.net/</link><image><url>https://devslash.net/favicon.png</url><title>/dev/</title><link>https://devslash.net/</link></image><generator>Ghost 2.22</generator><lastBuildDate>Fri, 24 Apr 2026 01:59:46 GMT</lastBuildDate><atom:link href="https://devslash.net/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[You don't have to know a lot about tmux]]></title><description><![CDATA[<p>I certainly don't, yet for the past 3 years it's been one of my favourite productivity tools. </p><p>Put simply, it's like a window manager for your terminal. No longer will you be burdened by 10 iterm tabs as you start up your local project, ssh to your server, keep webpack</p>]]></description><link>https://devslash.net/you-dont-have-to-know-a-lot-about-tmux/</link><guid isPermaLink="false">61e52adcc029c704408a60af</guid><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Mon, 17 Jan 2022 08:48:58 GMT</pubDate><content:encoded><![CDATA[<p>I certainly don't, yet for the past 3 years it's been one of my favourite productivity tools. </p><p>Put simply, it's like a window manager for your terminal. No longer will you be burdened by 10 iterm tabs as you start up your local project, ssh to your server, keep webpack running, and download in the background. </p><p>Suddenly, as you <code>ssh</code> into your remote machine you have all the window management capabilities you have locally. Much like <a href="https://devslash.net/you-dont-have-to-know-a-lot-about-vim/">my opinions on vim</a>, it doesn't take a lot for tmux to be really useful. </p><h2 id="get-started">Get started?</h2><p>Install, then run <code>tmux</code>. Well done, most of the way there. To run comamnds in tmux you use a pair of keyboard shortcuts. The default is <code>Ctrl + B</code>. This is often called the <code>Leader</code>. So you'll see things like "Do this thing by <code>Leader + %</code>". That means press <code>Ctrl + B</code> and then press <code>%</code>.</p><h3 id="window-pane-management">Window Pane Management</h3><p>To rekindle your love of tabs use <code>Leader + c</code> (C for create). Congrats, on the bottom bar you'll see a new "Window". To close this window, you can simply exit your terminal. There is a keystroke for it, but i've never used it. Want to switch between windows? Just use <code>Leader + &lt;number&gt;</code> where number is the window index.</p><p>Splitting the window is great, to do this you want <code>Leader + %</code> or <code>Leader + "</code>. Want to know how to remember them? Me too. I've found this easier to learn by attrition. <code>"</code> creates a horizontal switch. <code>%</code> makes a vertical one.</p><h3 id="tmux-is-now-useful">Tmux is now useful</h3><p>At this point in tmux we haven't covered plugins, tmuxconf, getting bloody copy and paste to work nicely on a mac. But you don't have to know a lot about tmux for it to be useful. With the above you're already able to jump onto your remote AWS machine and spin up a series of terminals like a pro. No longer creating 5 different ssh sessions, but just one and multiplexing the terminal instead.</p><p>Much like as mentioned in the vim post, the consistency that can be delivered to a developer by the use of tools like tmux and vim can mean that there's no discernable difference between you working on your local machine and when you're running something remotely.</p>]]></content:encoded></item><item><title><![CDATA[You don't have to know a lot about Vim]]></title><description><![CDATA[<p>If you go on any corner of the progrmaming internet, it shouldn't take long because you're rudely interrupted as you round the corner by a joke about <em>quitting vim</em>. A new user might reasonably think if quitting is so hard, imagine the rest of it.</p><p><strong>Well, you don't have to</strong></p>]]></description><link>https://devslash.net/you-dont-have-to-know-a-lot-about-vim/</link><guid isPermaLink="false">61e4ae69c029c704408a5ff8</guid><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Mon, 17 Jan 2022 06:57:37 GMT</pubDate><content:encoded><![CDATA[<p>If you go on any corner of the progrmaming internet, it shouldn't take long because you're rudely interrupted as you round the corner by a joke about <em>quitting vim</em>. A new user might reasonably think if quitting is so hard, imagine the rest of it.</p><p><strong>Well, you don't have to know a lot about vim</strong> for it to be a really useful tool. It's a great way to have a consistent editing experience across servers, IDEs, or even <a href="https://chrome.google.com/webstore/detail/vimium/dbepggeogbaibhgnhhndojpepiihcmeb?hl=en">Chrome</a>. With very basic knowledge it also begins to become something that'll make a lot of your work faster, and easier. </p><p>So, this aims to provide the precise minumum that you can know about vim and still find it useful. This means, i'll leave out things like visual mode, macros, and plugins - because fundamentally, you don't have to know a lot about them for vim to be useful.</p><h3 id="step-1-you-edit-or-give-actions">Step 1 - You edit, or give actions</h3><p>When programming, you'll almost definitely spend less time typing in characters compared to time doing <em>literally anything else</em>. So thus, when you are attempting to type in letters ensure you're in <code>INSERT</code> mode. You get into insert mode by typing <code>i</code>. If <code>i</code> just appeared in your document, congrats, you were already in INSERT mode.</p><!--kg-card-begin: image--><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://devslash.net/content/images/2022/01/image.png" class="kg-image"><figcaption>Vim doesn't make it subtle if you're in INSERT mode. It's down the bottom</figcaption></figure><!--kg-card-end: image--><p>While here, do all the typing of characters that you need. <em>When you're done. Exit INSERT mode with the escape key</em>. </p><p>In essence, to make Vim useful, get in the habit of being in insert mode when you actually want to add characters to your screen. The moment you're no longer doing that. Press escape.</p><h3 id="step-2-move-around">Step 2 - Move around</h3><p>When you're not in insert mode, you can give commands. You might want to use them to move. The most basic forms of movement is up, down, left right. Everything else is optional. It's just HJKL = Left, Up, Down, Right. </p><h3 id="step-3-save-and-exit">Step 3 - Save and exit</h3><p>Because you're not inserting text, you're of course in COMMAND mode. In this mode press Shift + ; to begin your command. All you have to know to be useful is <code>w</code>, <code>q</code>, and <code>!</code>. </p><p><code>:w&lt;Enter&gt;</code> is <em>write</em></p><p><code>:wq&lt;Enter&gt;</code> is <em>write</em> and <em>quit</em> </p><p><code>:q&lt;Enter&gt;</code> is <em>quit</em></p><p><code>:q!&lt;Enter&gt;</code> is <em>quit!!! I really mean it, don't ask about unsaved changes</em></p><h2 id="at-this-point-vim-is-already-useful">At this point, Vim is already useful</h2><p>Congrats. You now know enough to have a consistent editor no matter what platform you're on.</p><p>From here, every addition is a choice and thus it's worth avoiding beating youself up about the fact that you don't know every keystroke on that vim cheatsheet you saw. Instead celebrate the utility you already have.</p><h1 id="choices-i-made">Choices I made</h1><p>In the 10 years i've used vim, here's a list of things i've never really gotten into</p><ul><li>A super customised <code>~/.vimrc</code> file. The vast majority of the time, i don't even use a custom one though <a href="https://vim.fandom.com/wiki/Example_vimrc">if you want one, just Google</a>.</li><li>Plugins</li><li>Having multiple buffers open at the same time</li><li>Trying to make Vim an IDE</li><li>Macros</li><li>File management within Vim itself</li></ul><p>Still, any time that I install an IDE the first thing i do is install vim, i use it daily at least on my local media server, raspberry pi, or work laptop.</p><p>Here's the things i decided to learn about on top of it</p><h4 id="fast-movement">Fast Movement</h4><ul><li><code>gg</code> top of File</li><li><code>G</code> bottom of file</li><li><code>:12</code> go to line 12</li><li><code>23j</code> go down 23 times. (Can do this sort of things with tonnes of commands) </li><li><code>/searchString</code> find "searchString" in your doc</li><li><code>*</code> find the next time the word under the cursor is mentioned</li><li><code>n</code> give me the next one</li><li><code>p</code> previous one thanks</li><li><code>0</code> start of line</li></ul><h4 id="fast-edits">Fast edits</h4><ul><li><code>dd</code> delete line</li><li><code>C</code> change from my cursor to the end of line</li><li><code>ciw</code> Change in word (delete the word and start INSERT mode)</li><li><code>di{</code> delete all text within braces</li><li><code>ci)</code> delete all text within parens and start INSERT mode</li><li><code>A</code> append to the end of the line</li></ul><p>This works for me. It only scratches the surface of what it can do. But that's ok. Instead of trying to be a master, try lean in to the fact that you don't have to know a lot about something for it to be useful.</p>]]></content:encoded></item><item><title><![CDATA[Practicing Pair Code Review]]></title><description><![CDATA[<p><em>Sometimes in the following I sound like i’m stating facts. Please infer an ‘in my opinion’ in front of everything you read here. If you disagree, awesome, let me know because I’m interested. I’m definitely not trying to prescribe truths here but just speaking from my experience.</em></p>]]></description><link>https://devslash.net/how-to-pair-code-review/</link><guid isPermaLink="false">5b7376908ad0be5272489537</guid><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Wed, 15 Aug 2018 03:43:48 GMT</pubDate><content:encoded><![CDATA[<p><em>Sometimes in the following I sound like i’m stating facts. Please infer an ‘in my opinion’ in front of everything you read here. If you disagree, awesome, let me know because I’m interested. I’m definitely not trying to prescribe truths here but just speaking from my experience.</em></p><p>In the grand scheme of things, I’m still quite new to my career in software engineering. I’ve been working in the field since 2013, at four separate places during that time. Three of those places had some form of code-review as part of standard process. One, a bank that performed code review as part of the process after code was on SVN mainline. Two, where code-review was a strict process where discussions could go on for hours before your code ever hit the master branch.</p>
<p>When you join these places, part of the engineering onboarding is usually talking about how one goes through the process of PRs (Pull Requests). In particular it is mentioned that PRs really should be merged in 1-2 days. Each time though, the actual time to merge a PR is higher. Sometimes lots higher.</p>
<p>What follows is a personal opinion on what you, and I can do to help lower this. This method is something that I’ve used in the past to great success, and you’re able to pick up as just an individual, this doesn’t require the whole company to try it all at once.</p>
<p>Lets start with a bit of <em>why</em> I think these issues arise.</p>
<h2 id="whatshardaboutapr">What’s hard about a PR</h2>
<p>For a normally sized PR, there are a few things that are difficult when reviewing</p>
<ul>
<li>Context</li>
<li>Time</li>
<li>Latency</li>
</ul>
<p><strong>Context</strong>: When work across teams, or even in large teams you're often assigning review to someone who knows the code well, but might not be fully aware of all the work you're doing. To get around this, as a good PR owner, you of course wax lyrical in the PR description about what your PR is, and why it’s doing it. As a reviewer though, it’s a bit of a lottery if that’s enough to go on, or whether it answers the kind of questions that you need answered.</p>
<p><strong>Time</strong>: As a reviewer, often you’ll just get hit with a PR in your inbox without much warning. Maybe you knew it was coming, but there’s often cases where you just suddenly have a fresh piece of work on your plate that’s just arrived without so much as a ping on Slack. Now your week just got effectively shorter for you to actually perform any work that you wanted to do.</p>
<p><strong>Latency</strong>: This affects both sides of the review. It’s hard to ask questions, and get responses fast. If you ask a question one day, it’s very possible that by the next day the other person on the review has forgotten about them, and will need to nudge them for an answer. Maybe you’re answering any questions asked on your PR in seconds, but your reviewers never seem to get back to you as fast. Perhaps because they’ve expected it to take a while to receive a response, and thus have moved on to the next review. For every question that goes back and forth in a PR you can lose somewhere between minutes, and days of time.</p>
<h2 id="howcanyoufixthat">How can you fix that?</h2>
<p>With <em>Pair code review</em>.</p>
<p>In my opinion it’s as simple as that for a vast amount of cases. In a perfect world here’s my steps for a quality, and fast code review:</p>
<p>Before you start work on code, you should have an understanding about who you’ll be needing as a reviewer, notify then that you’ll be interested in performing a pair code review. Just to be polite about what you’re expecting from the reviewer.</p>
<p>Now, complete the code (the easy part).</p>
<p>Put up the review. The review quality should be just as good as always. This technique does not allow you to have a lower quality description, or lower quality clarifying comments throughout the PR.</p>
<p>Here's where things take a small turn.</p>
<p>Send a calendar invite to your reviewer(s). When doing so, I follow these rules</p>
<ol>
<li>Your PR should be sized that this should take 30m - 1h max. If it’s a larger PR, break it down. No excuses. This is <em>especially</em> important for this technique.</li>
<li>Your calendar invite should respect the reviewers time, make sure you’ve not just turned their day into a crap meeting-fest.</li>
<li>You should aggressively give back time. Indicate this on the invite. If the pair-review only takes 15m of the 30m, end the meeting straight away and relish. Nothing is worse than someone stretching a meeting just because it finishes 10 minutes from now.</li>
<li>When it's time for the start of the meeting, make sure you’ve got a good place to go to. If you’ve invited more than one person, grab a room with a TV, otherwise go to the reviewers desk.</li>
</ol>
<h4 id="runningthereviewasareviewee">Running the review as a reviewee</h4>
<p>Your job is to sit near/next to your reviewer and attempt to help with any and all context. You’re there to answer the &quot;why did you do this&quot; kind of questions. You should be taking notes, for all the changes that are desired.</p>
<p>Often i’ll have the review open on my own laptop, and write down what the reviewer tells me to change as comments on the PR like they’d done it.</p>
<p>Make sure to ask any clarifying questions straight away. Get that latency down to seconds rather that hours or days.</p>
<p>Come prepared with justifications for what you’re doing. It should be rare that you answer a question with ‘i don’t know'. Remember that you’re asking for the gift of your reviewers time, respect that by being prepared.</p>
<p>If a large change is required and/or its clear the review is going to be rejected, clarify how the solution should be rearchitected. Then, stop the meeting, and give back the reviewers their time. Alternatively, if you’d like this time can be used for some short pair programming to make the next session more likely to succeed.</p>
<h4 id="asareviewer">As a reviewer</h4>
<p>If possible, it’s good to have spent the 5-10 minutes before the calendar invite familiarising yourself with what’s there. This doesn’t have to be time reviewing, but should help you know if you’re the right person for the job, and have your brain running in the background about things you should check. Often the best time to do this is as close to when you received the invite as possible. This will allow you to respond fast if you're not the right person for the job.</p>
<p>When in the meeting, you don’t have to constantly talk, being silent is expected and totally ok. The reviewee is there to benefit your ability to review, but will be getting a lot of of this. You don't need to feel pressured to make conversation, or constantly update what you're thinking. You should feel free to review as you usually would. The only change is to verbalise your actionable comments, and ask questions straight away rather than on the PR.</p>
<p>Be clear at the end of the meeting what actions you’re expecting from the reviewer, and if they need to either book more time for a second review or, if you’re happy for them to merge once the changes you’ve asked for are applied.</p>
<p>For subsequent reviews, sometimes this whole process isn’t needed. Chances are your views have become so aligned that the number of questions, and thus latency is going to go down quite a lot.</p>
<p>Now all together, Merge, then celebrate.</p>
<h4 id="whatyouget">What you get</h4>
<p>This seems like a complex series of steps but overall boils down to</p>
<ul>
<li>Prepare your PR</li>
<li>Review together</li>
</ul>
<p>In my experience i’ve seen this consistently bring down PRs from up to 1-2 weeks to 2-3 days.</p>
<p>One thing to note is that this may feel like you’re losing time as a reviewer, as now you’ve suddenly got 10 calendar invites this week. My argument against that is that this approach should cut way down on your <em>actual</em> time spent per PR. There’s next to no context switching as questions are fielded back and forth without delay, thereby saving time. Your time spent writing questions and understanding answers is reduced to how quickly you can have a conversation.</p>
<p>As a reviewee, if you’re expecting to start a project that is going to require a lot of reviews from a particular person, do the courteous thing, and check in with them at the start. Make sure they have the bandwidth for this kind of thing. Perhaps you’ll need to help let their team know that you’re going to have to ‘steal’ them for a few hours a week as your project goes on.</p>
<p>Overall, feel free to do this, feel free to not. This is just a personal thing that I’ve found successful in the past, and would be happy to do in the future. This approach doesn’t need buy in from any more than you and your reviewer(s), so feel free to just give it a go one day if you feel that your PRs are taking a little longer than you’d like.</p>
<p></p>]]></content:encoded></item><item><title><![CDATA[Sleep can sometimes be the hardest thing]]></title><description><![CDATA[<p>For the last four or five years I've had a varying amount of insomnia. This culminated in different ways, sometimes I'd wake up 10-15 times per night, other times it would mean I'd go full nights without sleeping, most commonly it would mean that I'd take between 2 and 6</p>]]></description><link>https://devslash.net/sleep-can-sometimes-be-the-hardest-thing/</link><guid isPermaLink="false">5add38fe71941103b50eed8e</guid><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Sat, 21 Jul 2018 22:01:12 GMT</pubDate><content:encoded><![CDATA[<p>For the last four or five years I've had a varying amount of insomnia. This culminated in different ways, sometimes I'd wake up 10-15 times per night, other times it would mean I'd go full nights without sleeping, most commonly it would mean that I'd take between 2 and 6 hours to get to sleep for days in a row leaving me exhausted.</p>
<p>The worst part about that? It was all me. It was my fault. It was in my head. I knew that much years ago, but had zero ideas how to fix it. Dr Google only gets you so far.</p>
<p>To spoil a paragraph below, I kept doing something that's known as hyper-monitoring. I've only recently discovered the name for it, but it's basically something that occurs when you get stressed about sleeping. It's one of those annoying repetitive loops.</p>
<p>I would be concerned about my sleep before I went to bed<br>
I'd try make everything perfect to sleep. Dark room, comfy mattress, sheets, silent<br>
I'd not be able to sleep for an hour.<br>
I'd constantly question why! Was I too hot? Too cold? Should I roll over? Lets try it, what i'm currently doing obviously isn't working?!</p>
<p>The questioning meant that my brain was constantly active, getting more and more frustrated as I was so tired yet everything I was doing wasn't letting me sleep<br>
Thus, I'd not sleep, therefore making my concern higher the next night as I desperately needed to catch up<br>
Therefore the next night i'd question faster, and be monitoring more things (temp, airflow, sound, etc)<br>
It's a massive pain to have something that is so 'simple' be stuffed up and not know why. Kids can do it, some people can do it without even trying, it feels really lame to be shit at sleep. It affected me pretty consistently though, sometimes having to take days off work just based on ridiculous levels of tiredness.</p>
<p>Over the years I went to doctors, I'd heard everything you can hear about sleep hygiene. If you know about that, it is a list of 'good things' that you should do to have better sleep. Things such as not using your phone in bed, avoiding blue light, etc. One of the worst parts about moving to Sydney was that I was unable to actually have that any more. In a studio apartment, there's no avoiding lights from things in your house, no ability to separate your 'work space' and your 'sleep space'.</p>
<p>In the past, i'd been prescribed medication that helped for short times, but never underestimate the ability for your mind to defeat that, and I was soon back to bad sleep.</p>
<p>Finally, late last year I finally decided to specifically ask for a referral to a sleep psychologist. As of last week, i've finished my sessions and just wanted to provide details as I feel like sleep is something so many people have problems with but not many fix.</p>
<h3 id="whatdoyoudo">What do you do?</h3>
<p>So, I went to see an absolutely fantastic sleep physiologist. Quickly it was reassuring to find out that what I was dealing with wasn't much when it comes to grand scale of sleep issues. At the start though, I was skeptical, I really didn't believe that I could think my way out of a problem. I was worried that a psychologist would provide wishy-washy techniques that were based on feelings rather than fact.</p>
<p>Oh damn I was wrong.</p>
<p>Over the next 6 sessions were some of the most evidence based hours I'd had the pleasure to experience.</p>
<p>First, we identified what I was doing. Even that was a relief. I remember calling my wife after the first session excited &quot;She knows exactly what I do! That's so exciting! I'll be boring!&quot;. Boring is good. Boring is easy to fix. In general, what I had was a flight-or-fight response to going to bed. It sounds ludicrous, but when you spend hours just laying awake, bed becomes negatively connotated.</p>
<p>Second, and most exciting in some ways, was we started being very evidence driven. This was kind of weird, as I expected a lot of laying back on a couch with &quot;how did that make you feel&quot; kind of questions. Instead I had 2 worksheets I constantly filled out.</p>
<p>What time did you go to sleep?<br>
What time did you wake up?<br>
How did you feel your sleep was?<br>
How awake did you feel during the day?<br>
One of the first &quot;facts&quot; that surprised me was how low the correlation is between length of sleep and you actually feeling awake that day. Day tiredness and sleep quality are semi-unrelated, something Dr. Clancy would stress. This was great to find out weirdly enough. It reduced the stress of sleeping on an individual night as you're less worried about the next day definitely being terrible (still might be though).</p>
<p>Other things we did were techniques around CBT (Cognitive behaviour therapy), all of this with a large backing in research. I was able to collect evidence based responses for concerns that my brain would blow out of scale. eg &quot;I didn't sleep at all night, my next day will be zero fun&quot; → counter that with my birthday last year where I didn't sleep a single minute, but still had a freaking awesome time! Just reminding myself of this evidence made a bad sleep less powerful to affect my next day, and in turn became less scary, therefore letting me sleep easier.</p>
<p>It was also exceptionally useful to just have a really solid understanding of what's going on in your body around sleep. As someone who values evidence based stuff, everything was framed from the science of what's behind sleep (if you're interested, there's a great book by Matt Walker called &quot;Why we sleep&quot;).</p>
<h3 id="overall">Overall</h3>
<p>After close to 6 months, I'm way better than I was at the start. I still have nights where I don't sleep, or sleep very little, but they don't stress me any more. I accept them and don't get terribly stressed, it ends at one bad night rather than two or three weeks of awful times. This is incredibly freeing. Bed isn't inherently difficult any more. On top of that I now feel like I  have the evidence based tools that will help me in the future when I kick back into a bad sleep funk for a little while.</p>
<p>Finally, I really would encourage everyone treat sleep like any other ailment. If you broke your leg you'd go to the doctor. If you've broken your sleep, it's one and the same. If it's your head that's stuffing you up, then I hope that knowing that it can be such a successful treatment will help justify going to get the help needed as well. I just wish I'd done it years ago.</p>
]]></content:encoded></item><item><title><![CDATA[Private isn't always so private in Java]]></title><description><![CDATA[<p>There's a few things I take for granted as a backend Java developer. IntelliJ &gt; eclipse, by the time I get back to frontend JS - it's all changed again, and finally in Java, private is pretty private.</p>
<p>A <code>private</code> method generally means that only the class that defined the</p>]]></description><link>https://devslash.net/private-isn-t-always-so-private/</link><guid isPermaLink="false">5a76dcb2af8c8c196db50e17</guid><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Mon, 19 Feb 2018 11:19:11 GMT</pubDate><content:encoded><![CDATA[<p>There's a few things I take for granted as a backend Java developer. IntelliJ &gt; eclipse, by the time I get back to frontend JS - it's all changed again, and finally in Java, private is pretty private.</p>
<p>A <code>private</code> method generally means that only the class that defined the method may call it. That said, Java does give you tools to poke holes in it from the start. Let's take the following as a starting point.</p>
<pre><code class="language-java">class Privacy {
   
    private Privacy() {
        System.out.println(&quot;Hi there&quot;);
    }
}
</code></pre>
<p>Ths post aims to answer &quot;how can we get the JVM to call the private constructor?&quot;</p>
<h3 id="methodonereflection">Method One: Reflection</h3>
<p>Using the reflection APIs this is simple.</p>
<pre><code class="language-java">public class Reflect {
    public static void main(String... args) throws Exception {
        Constructor&lt;Privacy&gt; constructor = (Constructor&lt;Privacy&gt;) Privacy.class.getDeclaredConstructors()[0];
        constructor.setAccessible(true);
        constructor.newInstance();
    }
}

</code></pre>
<p>Lo and behold, the class is available and the instance is ready.</p>
<p>This is a feature of language, and can be guarded against if you don't want code to be using the reflection APIs. The following bans all reflection.</p>
<pre><code class="language-java">System.setSecurityManager(new SecurityManager() {
            @Override
            public void checkPermission(Permission perm) {
                if (perm instanceof ReflectPermission) {
                    throw new SecurityException();
                }
            }
        });
</code></pre>
<h3 id="method2usinginnerclasses">Method 2: Using inner classes</h3>
<p><em>How else can we do it</em>? Well, if you have access to the source code (and assuming we can't change private to public) then you can add an inner class.</p>
<pre><code class="language-java">class Outer {
    
    private Outer() {
        System.out.println(&quot;Hi there&quot;);
    }

    public static class Inner {
        public void goForIt() {
            new Outer();
        }
    }
}
</code></pre>
<p>In this case, we're very much able to run <code>new Outer.Inner()</code> and cause the JVM to output the message. This structure may be familiar to you if you utilise a builder pattern. Often, a builder's <code>build()</code> method will call straight back to the private constructor of the enclosing class.</p>
<h2 id="whataboutathirdway">What about a third way?</h2>
<p>Let's assume for a moment that</p>
<ul>
<li>You're unable to use reflection</li>
<li>You can't change <em>any</em> of the original source code.</li>
<li>The class containing our private method we want to access has the following
<ul>
<li>An inner class</li>
<li>That inner class accesses the private member we desire (constructor/member)</li>
</ul>
</li>
</ul>
<p>Given that, let's start by taking a look at our example. This is the code that we want to try call the private constructor on. You can surely imagine that we very much would like to create a bank account with more than $100 starting balance.</p>
<pre><code class="language-java">class BankAccount {
    
    private BankAccount(int amount) {
        System.out.println(&quot;Bank balance: &quot; + amount);
    }

    public static class BankAccountBuilder {
        public void balance(int i) {
            if (i &gt; 100) throw new IllegalArgumentException(&quot;$100, yeah right&quot;);
            new BankAccount(i);
        }
    }
}
</code></pre>
<p>That is the same structure as we've just had. There's an inner class that calls the private constructor. This time though, we're not going to go through the <code>BankAccountBuilder</code>, we instead want to create our own instance without using the validation that's performed in the Builder.</p>
<p>These examples take places on the following machine. The overall method has been tested on the Oracle JDK, eclipse compiler, and the Open JDK. Though what you see in the rest of these sections are specific to Oracle, and will require slight adjustments for the other compilers.</p>
<pre><code>Macbook pro 2015 - High Sierra
Oracle java version &quot;1.8.0_144&quot;
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)
</code></pre>
<h3 id="howdoestheinnerclasswork">How does the inner class work?</h3>
<p>To get started with this investigation, we can look at what's actually going on in the inner class. In the simplest case, let's take a quick peek at the bytecode of the following MVP.</p>
<pre><code class="language-java">class Outer {
    private Outer() {
    }

    public static class Inner {
        new Outer();
    }
}
</code></pre>
<p>Let's compile.</p>
<pre><code>javac Outer.java
</code></pre>
<p>When compiling an inner class, Java will actually create a separate class file for the inner class. The name of this class is <code>&lt;Name of outer class&gt;$&lt;Name of inner class&gt;</code>. We can see this in the output</p>
<pre><code># ls | grep class
Outer.class
Outer$1.class
Outer$Inner.class
</code></pre>
<p>There's the expected outer class, the inner class. There is also an extra classfile here called <code>Outer$1.class</code>.</p>
<p>As a note, if you change the constructor to <code>protected</code> and compile again you'll notice something's missing. The <code>Outer$1.class</code> file <em>only</em> exists when the private constructor is accessed. This is a clue as to how <code>javac</code> resolves the fact that we need to access a private member.</p>
<p>So, that <code>$1</code> class is getting generated all because of Java. Let's take a peek at it. To do this, we use the tool <code>javap</code> that comes with each JDK installation.</p>
<pre><code>javap -p -s -v &lt;class&gt;
</code></pre>
<ul>
<li><strong>-p</strong> asks the tool to show private, protected, and public methods.</li>
<li><strong>-s</strong> includes the internal type signatures</li>
<li><strong>-v</strong> asks it to be verbose. This is good when you want to really dig in. You'll get the constant pool &amp; the bytecode of the methods.</li>
</ul>
<pre><code class="language-java"># javap -p -s -v Outer$1
class Outer$1
  minor version: 0
  major version: 52
  flags: ACC_SUPER, ACC_SYNTHETIC
Constant pool:
&lt;&lt;&lt;snipped&gt;&gt;&gt;
{
}
SourceFile: &quot;Outer.java&quot;
EnclosingMethod: #6.#0                  // Outer
InnerClasses:
     static #1; //class Outer$1
</code></pre>
<p>See those opening, and closing braces? That's <code>javap</code>'s idea of the body of the class. In this case, there are no methods defined at all.</p>
<p>Do note the <code>ACC_SYNTHETIC</code>, that means this class does not exist in the source code. Keep that in mind for later. Any time you see this flag, it means the Java compiler created something for us that we didn't directly write.</p>
<p>So this class seems to do absolutely nothing, yet is always created when accessing a private member from an inner class. This indicates that this is at least quite important to this functionality.</p>
<p>To find out, let's check out those other classes, starting with the <code>Outer</code> class.</p>
<pre><code class="language-java"># java -p -s -v Outer
public class t.Outer
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
&lt;snipped&gt;
{
  private t.Outer();                          // First constructor
    descriptor: ()V
    flags: ACC_PRIVATE
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #2                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V
         4: return
      LineNumberTable:
        line 4: 0
        line 6: 4

  t.Outer(t.Outer$1);                         // Second Constructor
    descriptor: (LOuter$1;)V
    flags: ACC_SYNTHETIC
    Code:
      stack=1, locals=2, args_size=2
         0: aload_0
         1: invokespecial #1                  // Method &quot;&lt;init&gt;&quot;:()V
         4: return
      LineNumberTable:
        line 3: 0
}
</code></pre>
<p>And there we go, there's <code>ACC_SYNTHETIC</code> on the second constructor. Let's break down interesting things about this:</p>
<ul>
<li>The flags do not include privacy. That means we're <em>package private</em>.</li>
<li>The flags include <code>ACC_SYNTHETIC</code> so we definitely didn't write this constructor.</li>
<li>The descriptor attribute references the <code>$1</code> class in the following way:
<ul>
<li>L means an Object parameter, what comes next is the class. <code>Outer$1</code>;</li>
<li>V is a void return. This is expected.</li>
</ul>
</li>
</ul>
<p>The body of the method is relatively simple as it;</p>
<ul>
<li>Loads the <code>self</code> reference</li>
<li>Calls the private constructor</li>
<li>Finally returns</li>
</ul>
<p>What this shows, is that <code>javac</code> generated us a constructor that allows for classes in the same package to call the private constructor via this synthetic constructor. The descriptor (method params + return) change is clever as it ensures that there isn't a collision between the regular functions and the ones that  <code>javac</code> generated. We know this for sure because <code>Outer$1</code> is a synthetic class and thus can't have been referenced in any prior source.</p>
<p>One more class to go. Let's check out the call site in the inner class.</p>
<pre><code class="language-java"># javap -p -s -v Outer\$Inner
public class t.Outer$Inner
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
&lt;snipped&gt;
{
  public Outer$Inner();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=3, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V
         4: new           #2                  // class Outer
         7: dup
         8: aconst_null
         9: invokespecial #3                  // Method Outer.&quot;&lt;init&gt;&quot;:(LOuter$1;)V
        12: pop
        13: return
}
</code></pre>
<p>Alright, so let's beak down the constructor.</p>
<ul>
<li>0: Load <code>this</code></li>
<li>1: Invoke the constructor for the superclass <code>Object</code></li>
<li>4: Create a new instance of the <code>Outer</code> class</li>
<li>7: Duplicate the new instance on the stack. This is <a href="https://blog.nishtahir.com/2015/09/12/exploring-java-byte-code/">required for the <code>invokespecial</code> step.</a></li>
<li>8: Load null into the stack</li>
<li>9: Call the synthetically created constructor</li>
<li>12: Pop the stack</li>
<li>13: Return</li>
</ul>
<p>If you're wondering why there are breaks between the numbers, the labels at the start are byte offsets since the start of the method. An instruction can take more than 1 byte (eg, <code>new</code> takes 2). So the jumps in the numbers are due to the fact that the instruction prior has taken more than a single byte.</p>
<p>So, when you have a</p>
<ul>
<li>public</li>
<li>protected</li>
<li>package private</li>
</ul>
<p>method, javac has do to bugger all. It's when it's private that we have to jump through these hoops.</p>
<h2 id="whocancallthat">Who can call that?</h2>
<p>So what gives <code>Inner</code> the right to call that synthetic method? Is there a way that you can write code that'll allow a non-inner class to call it?</p>
<p>On the surface it seems the only requirements are to be able to call the constructor that takes the <code>Outer$1</code> as a parameter and to be in the same package.</p>
<p>A difficulty arises though, as javac will not allow you to compile a java source file that references the $1 class. Or at least, I've been unable to.</p>
<p>There's nothing from stopping us from creating our own bytecode though. Perhaps we can create a class that'll allow us to open up this private constructor to the world.</p>
<p>To do this, we can use the <a href="http://asm.ow2.org/">java-asm</a> library. This library is a bytecode manipulation framework. You can use it to manipulate existing class files, or even just create your own classes. Let's take our knowledge of how the inner class calls the synthetic method and utilise that.</p>
<p>Looping back for a moment, the core part of the bytecode of the synthetic call was</p>
<pre><code>1: new Inner
2: dup
3: aconst_null
4: invokedynamic Inner.&lt;init&gt;(LOuter$1;)V
5: pop
6: return
</code></pre>
<p>What we want to do is insert that bytecode into a method of another class. In java-asm, that looks as follows. Here we're creating a class called <code>Example</code>.</p>
<pre><code class="language-java">        ClassWriter cw = new ClassWriter(0);
        cw.visit(V1_1, ACC_PUBLIC, &quot;Example&quot;, null, &quot;java/lang/Object&quot;, null);

        MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, &quot;&lt;init&gt;&quot;, &quot;()V&quot;, null,
                null);
        mw.visitVarInsn(ALOAD, 0);
        mw.visitMethodInsn(INVOKESPECIAL, &quot;java/lang/Object&quot;, &quot;&lt;init&gt;&quot;, &quot;()V&quot;, false);
        mw.visitInsn(RETURN);
        mw.visitMaxs(1, 1);
        mw.visitEnd();
</code></pre>
<p>Firstly, we must create our constructor. Javac will create a constructor when compiling a source file, however when writing bytecode we must create a constructor explicitly.</p>
<p>Now, let's create another method that does contain the bytecode in the same way the inner class has.</p>
<pre><code class="language-java">        mw = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, &quot;createBankAccount&quot;,
                &quot;(I)V&quot;, null, null);

        mw.visitTypeInsn(NEW, &quot;BankAccount&quot;);
        mw.visitInsn(DUP);
        mw.visitVarInsn(ILOAD, 0);
        mw.visitInsn(ACONST_NULL);
        mw.visitMethodInsn(INVOKESPECIAL, &quot;BankAccount&quot;, &quot;&lt;init&gt;&quot;, &quot;(LBankAccount$1;)V&quot;, false);
        mw.visitInsn(RETURN);
        mw.visitMaxs(3, 2);
        mw.visitEnd();

        byte[] code = cw.toByteArray();

        FileOutputStream fos = new FileOutputStream(&quot;Example.class&quot;);
        fos.write(code);
        fos.close();
</code></pre>
<p>We then write out the class by running the above snippets together.</p>
<p>We should be able to verify this class is valid by using <code>javap</code>. If for some reason the class file was generated unsuccessfully, <code>javap</code> will complain that there's some issues. Here's the output, not including the method bodies</p>
<pre><code class="language-java"># javap -v -s -p Example
...
public static void createBankAccount(int);
  descriptor: (I)V
  flags: ACC_PUBLIC, ACC_STATIC
  Code:
    stack=3, locals=2, args_size=1
       0: new              #13        // class BankAccount
       3: dup
       4: iload_0
       5: aconst_null
       6: invokespecial    #15        // Method BankAccount.&quot;&lt;init&gt;&quot;:(ILBankAccount$1;)V
       9: return
...
</code></pre>
<p>We should now be able to use our class file.</p>
<pre><code class="language-java">class Runner {
    public static void main(String... args) {
        Example.createBankAccount(100_000);
    }
}
</code></pre>
<p>We then run <code>javac Runner .java</code>. This should compile successfully! Doing so shows we've been able to create code that has compiled against our generated bytecode.</p>
<p>From here, run it with <code>java Runner</code>.</p>
<pre><code class="language-java"># java Runner 
Your bank balance is $100000
</code></pre>
<p>Your console should now print the amount that you've asked for, even though it the constructor is private. To the jvm, you've only called a package-private method, and that's considered perfectly fine.</p>
<p>The implications of this is that if you're able to insert your own class into a package containing a outer/inner pair, then you're also able to call any private parts of the outer class that the inner class references.</p>
<p>This also holds for private methods. In my instance, calling a private method will create an <code>access$xxx</code> synthetic method, where x are digits. These are created somewhat deterministically, so a rogue user would have little difficulty figuring out what to call when generating their own class file.</p>
<p>Finally, there's no requirement for any part of the inner class to be public for this technique to be utilised. An entirely private inner class still opens up the holes in the exact same way. This can lead to a false sense of security if steps aren't taken to mitigate this approach.</p>
<h3 id="overall">Overall</h3>
<p>When utilising the outer/inner class pattern, you have to be prepared for the fact that <code>javac</code> is creating holes in the privacy of certain parts of your code. This is by design, when querying Oracle they said it is a known and expected behaviour. So this isn't a crazy security problem in the JDK, it's just an interesting side effect of how Java manages to create a pattern that we all very much enjoy when using patterns such as the <code>Builder</code>.</p>
<p>If you're running an application, this could only be a problem if you run user-code, and allow classes to be defined in pre-existing packages.</p>
<p>To mitigate this, when running untrusted code, you should ensure that the code does not define itself in a pre-existing package. Of course, if you're running untrusted code, this is probably number 100,000 on the priority listing of possible actual issues and this is mostly an exercise into the possibilities.</p>
<p>For now though, celebrate the fact that you've managed to call a private method/constructor (in another one of the <em>many</em> ways). That's pretty cool, and hopefully you've learnt a little bit about how Java abstracts these language features.</p>
]]></content:encoded></item><item><title><![CDATA[Pizza: Yummo Fetta Pizza]]></title><description><![CDATA[<h2 id="dough">Dough</h2>
<ul>
<li>1.5 cups flour - high gluten</li>
<li>teaspoon salt</li>
<li>pinch of sugar</li>
<li>5/8 cup water (warm) + 1 tsp yeast</li>
</ul>
<p>knead, mix, etc. Frozen, then thawed for later.</p>
<h2 id="pizza">Pizza</h2>
<ul>
<li>half red onion (raw)</li>
<li>tomato paste</li>
<li>1 chicken breast (cooked)</li>
<li>1/2 capsicum (small cuts)</li>
<li>Chilli Olive Oil</li>
<li>80g fetta</li></ul>]]></description><link>https://devslash.net/pizza-yummo-fetta-pizza/</link><guid isPermaLink="false">5a76dcb2af8c8c196db50e13</guid><category><![CDATA[cooking]]></category><category><![CDATA[pizza]]></category><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Mon, 12 Jun 2017 01:42:41 GMT</pubDate><content:encoded><![CDATA[<h2 id="dough">Dough</h2>
<ul>
<li>1.5 cups flour - high gluten</li>
<li>teaspoon salt</li>
<li>pinch of sugar</li>
<li>5/8 cup water (warm) + 1 tsp yeast</li>
</ul>
<p>knead, mix, etc. Frozen, then thawed for later.</p>
<h2 id="pizza">Pizza</h2>
<ul>
<li>half red onion (raw)</li>
<li>tomato paste</li>
<li>1 chicken breast (cooked)</li>
<li>1/2 capsicum (small cuts)</li>
<li>Chilli Olive Oil</li>
<li>80g fetta</li>
<li>Mozzarella</li>
<li>Bush tomato sauce (chilli)</li>
</ul>
<h6 id="method">Method</h6>
<ol>
<li>Ensure the BBQ is on High, try have it at 200<sup>o</sup>C</li>
<li>Put down a flour surface, put dough on top</li>
<li>Punch dough, pushing out onto the bench</li>
<li>Flip the dough a couple of times, pushing out even more</li>
<li>Once dough is around half the size of the final pizza, pick up</li>
<li>Start with stretching the dough, try to make sure there exists a nice round crust. Use knuckles to stretch.</li>
</ol>
<p>Now for the pizza toppings</p>
<ol>
<li>Put on tomato sauce first, followed by a small amount of mozzarella. Less than normal</li>
<li>This is followed in order by:</li>
</ol>
<ul>
<li>Capsicum</li>
<li>Red onion</li>
<li>Chicken</li>
</ul>
<ol>
<li>Crumb the fetta over the pizza using your fingers to make small chunks</li>
<li>Drizzle olive oil over the top, add tomato sauce as desired</li>
<li>Cook on pizza stone in the BBQ until crust is firm on top.</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Why you don't store passwords in Strings in Java]]></title><description><![CDATA[<p>If you're interviewing for a junior Java developer position you might be asked.</p>
<blockquote>
<p>Why should you never store secrets or passwords in a String in Java?</p>
</blockquote>
<p>This can be answered based on a few facts of Java. First of all, <code>java.lang.String</code> is immutable. Therefore, once allocated, there is</p>]]></description><link>https://devslash.net/why-you-dont-store-secrets-in-strings-in-java/</link><guid isPermaLink="false">5a76dcb2af8c8c196db50e12</guid><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Wed, 29 Mar 2017 08:04:42 GMT</pubDate><content:encoded><![CDATA[<p>If you're interviewing for a junior Java developer position you might be asked.</p>
<blockquote>
<p>Why should you never store secrets or passwords in a String in Java?</p>
</blockquote>
<p>This can be answered based on a few facts of Java. First of all, <code>java.lang.String</code> is immutable. Therefore, once allocated, there is no way to change the value of a String. So this means if you ever update the value, simply an entire new String is created. The old string merely sits in memory with no JVM reference to it.</p>
<p>Lets start a look at this problem by investigating the class <code>DumpMemory</code> (no points for what we'll do later). It stores a password that's meant to be entered and matched.</p>
<pre><code class="language-java">class DumpMemory {
    private String line = &quot;hi there&quot;;

    public void setPassword(String value) {
        managerPassword = value;
    }

    public boolean matches(String password) {
        return managerPassword.equals(password);
    }
}
</code></pre>
<p>Enter our bad actor. Somehow, they got access to the machine that it runs on. Lets just pretend that's not impressive already and instead highlight another security concern.</p>
<p>Our bad actor can now core dump out our running Java process</p>
<pre><code># gcore &lt;pid&gt; 
</code></pre>
<p>From here it's trivial to get the Strings referenced by each class.</p>
<p>First, lets create a hprof file. This will transform the dump file created earlier into a filetype that Java specific tools are happy to read.</p>
<pre><code>&gt; jmap -dump:format=b,file=dump.hprof $JAVA_HOME/bin/java &lt;core file&gt;
</code></pre>
<p>We can take a look at this using the <code>jhat</code> tool.</p>
<pre><code>&gt; jhat dump.hprof
Reading from dump.hprof...
Dump file created Wed Mar 29 11:32:54 AEDT 2017
Snapshot read, resolving...
Resolving 10814 objects...
Chasing references, expect 2 dots..
Eliminating duplicate references..
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.
</code></pre>
<p>If we navigate to <a href="http://localhost:7000">http://localhost:7000</a> we can see the package we're interested in.</p>
<p><img src="https://devslash.net/content/images/2017/03/Screen-Shot-2017-03-29-at-11-40-10-am.png" alt=""></p>
<p>After selecting <code>DumpMemory</code> we then select the a list of references to our object.</p>
<p><img src="https://devslash.net/content/images/2017/03/Screen-Shot-2017-03-29-at-11-41-45-am.png" alt=""></p>
<p>then we can select the <code>DumpMemory</code> reference.</p>
<p><img src="https://devslash.net/content/images/2017/03/Screen-Shot-2017-03-29-at-11-42-05-am.png" alt=""></p>
<p>Suddenly, plain as day, we can see our String just sitting there. This is entirely expected and understandable.  The String exists as a field on an instance of a class, and thus has to stay around while the instance is in scope. Given the JRE isn't going to encrypt Strings at rest, we have to expect it to be in our heap dump.</p>
<p>Though couldn't we just lower the scope of the String as much as possible and wait for GC to come along and clean up our secret?</p>
<p>Lets do so in the following example:</p>
<pre><code class="language-java">public class DumpMemory {

    String line = &quot;&quot;;

    public void run() {
        line = new Scanner(System.in).nextLine();

        System.out.println(&quot;You entered: &quot; + line);
    }

    public static void doSomething() {
        new DumpMemory().run();
    }

    public static void main(String[] args) {
        doSomething();
        new Scanner(System.in).next();
    }
}
</code></pre>
<p>Again, a somewhat contrived example. We get a String from the user. Lets pretend this is a secret String. We proceed to <em>securely</em> print it, and then <code>doSomething()</code> completes. This means that the instance that was created in that method is now up for garbage collection, as it is no longer in scope.</p>
<p>In the example, once <code>doSomething()</code> has completed we wait for user input so we can get a chance to dump the process.</p>
<p>Once <code>gcore</code> has completed, we can't use the standard Java core analysers. That's because they'll ignore parts of the dump that aren't part of a valid stack/heap. Instead, we can take a look at the core file in a hex viewer.</p>
<p>When running this, I entered the String <code>beagle3</code> as the input. Now analysing the core dump, you might expect that since the object has gone out of scope you wouldn't see it any more.</p>
<p><img src="https://devslash.net/content/images/2017/03/Screen-Shot-2017-03-29-at-7-54-15-am.png" alt=""></p>
<p>Hmm. Even though the String is firmly out of scope at the point that we took the dump,  look what we actually see. The reasoning behind this is the fact that going out of scope is not enough for the JVM to get <em>rid</em> of the underlying data.</p>
<h3 id="whataboutafteragc">What about after a GC?</h3>
<p>Sometimes you'll read an answer about the fact that if you use a <code>String</code> rather than a <code>byte[]</code> then you'll have to wait for garbage collection to come along before that String will no longer exist in memory.</p>
<p>Lets investigate that claim to find if that's always true.</p>
<p>This time we'll start Java with a slightly custom flag. <code>java -verbose:gc dva.DumpMemory</code>. This will allow us to see when gc has taken place so that we can know when to take our dump.</p>
<p>Here's the output of a run of the same program</p>
<pre><code class="language-bash"># java -verbose:gc dva.DumpMemory                                                                
beagle3
You entered: beagle3
[GC (JvmtiEnv ForceGarbageCollection)  13107K-&gt;1544K(251392K), 0.0033103 secs]
[Full GC (JvmtiEnv ForceGarbageCollection)  1544K-&gt;1399K(143360K), 0.0099899 secs]
</code></pre>
<p>What I did was first enter the <em>hyper-secure</em> password, and then using JProfiler, I forced a full GC of the program. You can see the effects in the JProfiler memory view.</p>
<p><img src="https://devslash.net/content/images/2017/03/Screen-Shot-2017-03-29-at-9-01-57-am.png" alt=""></p>
<p>Taking the dump once again. I opened it in a hex editor.</p>
<p><img src="https://devslash.net/content/images/2017/03/Screen-Shot-2017-03-29-at-9-05-38-am.png" alt=""></p>
<p>This dump was performed <em>after</em> the GC, but the String is still sitting in memory. The reason this is happening is due to the fact that, when garbage collecting, the JVM does not bother to zero out memory (for good reason). Instead it simply discards GC'able objects from its internal memory model and marks the memory as available for future object storage.</p>
<h3 id="willitevergoaway">Will it ever go away?</h3>
<p>Yes!</p>
<p>Lets make an example that does just that. In the previous example we had a single GC, lets change it so we're having lots of GC.</p>
<pre><code class="language-java">public class DumpMemory {
    String line = &quot;&quot;;

    public void run() {
        line = new Scanner(System.in).nextLine();

        System.out.println(&quot;You entered: &quot; + line);
    }

    public static void doSomething() {
        new DumpMemory().run();
    }

    public static void main(String[] args) {
        doSomething();
        
        while(true) {
            new Date().toString();
        }
    }
}
</code></pre>
<p>As we run this one we're going to see GC occurring consistently without any JProfiler help</p>
<pre><code># java -verbose:gc dva.DumpMemory                                                                
beagle3
You entered: beagle3
[GC (Allocation Failure)  65536K-&gt;840K(251392K), 0.0010497 secs]
[GC (Allocation Failure)  66376K-&gt;848K(251392K), 0.0010727 secs]
[GC (Allocation Failure)  66384K-&gt;896K(251392K), 0.0006899 secs]
[GC (Allocation Failure)  66432K-&gt;872K(316928K), 0.0008372 secs]
[GC (Allocation Failure)  131944K-&gt;880K(316928K), 0.0010596 secs]
[GC (Allocation Failure)  131952K-&gt;856K(438272K), 0.0009543 secs]
[GC (Allocation Failure)  263000K-&gt;840K(438272K), 0.0014307 secs]
[GC (Allocation Failure)  262984K-&gt;816K(427520K), 0.0004112 secs]
[GC (Allocation Failure)  252720K-&gt;816K(418816K), 0.0003833 secs]
[GC (Allocation Failure)  242992K-&gt;816K(408576K), 0.0003985 secs]
[GC (Allocation Failure)  233776K-&gt;816K(400896K), 0.0004971 secs]
[GC (Allocation Failure)  225072K-&gt;816K(391680K), 0.0004864 secs]
[GC (Allocation Failure)  216880K-&gt;816K(384512K), 0.0004790 secs]
[GC (Allocation Failure)  208688K-&gt;816K(375808K), 0.0004398 secs]
[GC (Allocation Failure)  201008K-&gt;816K(369664K), 0.0004333 secs]
[GC (Allocation Failure)  193840K-&gt;816K(361472K), 0.0003493 secs]
[GC (Allocation Failure)  186672K-&gt;816K(355840K), 0.0004877 secs]
</code></pre>
<p>Now if we take a dump here, we're going to (almost definitely) be unable to find the string <code>beagle3</code>. This is because as the String containing <code>beagle3</code> went out of scope, the memory it existed in was available to be used at some point in the future. As we continually allocate objects, eventually the place where <code>beagle3</code> sat in memory is overwritten with a new object that was allocated when creating a <code>Date</code>.</p>
<p>This means that eventually our mistake of having a secret as a String is occluded, but if your application only performs GC every now and then, you are liable for having that secret around for much longer than you wanted in your lexical scope.</p>
<h3 id="whatshouldidoinstead">What should I do instead?</h3>
<p>Use <code>byte[]</code>. Byte arrays are the underlying way that Strings are stored in Java anyway. You should be able to perform the same kind of changes on a byte array that you would otherwise perform on a String. You'd simply change</p>
<pre><code class="language-java">public boolean checkSecret(String otherText) {
    // assuming 'secret' is a String
    return secret.equals(otherText);
}
</code></pre>
<p>to</p>
<pre><code class="language-java">public boolean checkSecret(byte[] otherText) {
    return Arrays.equal(secret, otherText);
}
</code></pre>
<p>The great thing that a byte array gives you is the chance to zero out your array as soon as you've finished using the secret. This means you have explicit controls over the lifetime of your secret.</p>
<pre><code class="language-java">// Secret starts existing in memory
byte[] superSecret = passwordManager.loadPassword();

boolean eq = Arrays.equal(superSecret, userInput);

// Secret is purged from memory
Arrays.fill(superSecret, (byte) 0);
return eq
</code></pre>
<p>Unlike altering a String, when you alter a byte array you are actively changing the underlying data in the heap. Therefore you don't run into the same issue where your data will stay long after the secret has gone out of scope. Even if the memory representing <code>superSecret</code> does stay around for a while, it is only filled with zeros in our example and thus has hidden our secret from prying eyes (unless your secret was actually all zeros).</p>
<p>So, if you ever are dealing with Strings that should be very private you should follow these rules</p>
<ul>
<li>use <code>byte[]</code> in every place that you wanted to use a <code>String</code></li>
<li>Only load the <code>byte[]</code> data right before you need it</li>
<li>As soon as the critical work is done, zero out your byte array</li>
</ul>
<p>Using this will give you the smallest window of time that your secret is sitting in memory, waiting for someone to discover it.</p>
<h3 id="letsprovethis">Lets prove this</h3>
<p>Taking the following program</p>
<pre><code class="language-java">package dva;

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class DumpByteMemory {

    // This is an unrealistic random, but it allows us to
    // look for what could be considered a random value
    Random rand = new Random(1);

    byte[] line = new byte[10];

    public void run() throws Exception {
        System.out.println(&quot;We're about to generate our *secure key*&quot;);
        rand.nextBytes(line);

        System.out.println(&quot;Secret is stored, look for it&quot;);

        new Scanner(System.in).next();
        Arrays.fill(line, (byte)0);
    }

    public static void doSomething() throws Exception {
        DumpByteMemory f = new DumpByteMemory();
        f.run();
    }

    public static void main(String[] args) throws Exception {
        doSomething();
        System.out.println(&quot;Out of scope&quot;);
        new Scanner(System.in).next();
    }
}
</code></pre>
<p>Here we're pretending a password is being generated, though we're setting a seed so that we know what to look for in the dump. When setting the seed to 1, the example (on my JRE) will produce <code>73 D5 1A BB D8 9C B8 19 6F 0E</code> for the 10 byte array.</p>
<p>So lets take two dumps:</p>
<ul>
<li>One after the message <code>Secret is stored, look for it</code> appears</li>
<li>One once the message <code>Out of scope</code> appears</li>
</ul>
<p><img src="https://devslash.net/content/images/2017/03/java-thing.png" alt=""></p>
<p>Here we see the results of that. At first we see this stream of data in our dump. Then at the second point we see that same memory has been completely zeroed out.</p>
<p>This shows the security that you can get by simply changing the way that you handle your keys. Instead of hoping that GC comes along and eventually overwrites your object you can make sure that you keep your secret around for as short a time as possible.</p>
]]></content:encoded></item><item><title><![CDATA[Covariant & Contravariant]]></title><description><![CDATA[<p>Before we get into the Co/Contra-variants we should quikcly go thorugh sub and super types.</p>
<pre><code>public class Bird {}

public class Duck extends Bird {}
</code></pre>
<p>In this case, <code>Bird</code> is a <em>superclass</em> of <code>Duck</code>. While <code>Duck</code> is a <em>subclass</em> of <code>Bird</code>. In UML this is designated by an arrow pointing from</p>]]></description><link>https://devslash.net/covariant-contravariant/</link><guid isPermaLink="false">5a76dcb2af8c8c196db50e11</guid><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Mon, 02 May 2016 11:42:22 GMT</pubDate><content:encoded><![CDATA[<p>Before we get into the Co/Contra-variants we should quikcly go thorugh sub and super types.</p>
<pre><code>public class Bird {}

public class Duck extends Bird {}
</code></pre>
<p>In this case, <code>Bird</code> is a <em>superclass</em> of <code>Duck</code>. While <code>Duck</code> is a <em>subclass</em> of <code>Bird</code>. In UML this is designated by an arrow pointing from <code>Duck</code> to <code>Bird</code>.</p>
<h2 id="covariant">Covariant</h2>
<p>Covariant is when the ordering of types is preserved. It orders types from more specific to more generic.</p>
<blockquote>
<p><code>Enumerable&lt;Cat&gt;</code> is a subtype of <code>Enumerable&lt;Animal&gt;</code>. The sub-typing is preserved <code>Enumerable</code> is <em>covariant</em> on <code>&lt;T&gt;</code></p>
</blockquote>
<p>So you're <em>covariant</em> on something. In this case we're <em>covariant</em> on <code>&lt;T&gt;</code>.</p>
<p>An example where your <em>covariant</em> is an array in Java. This is because <code>String[]</code> is a subtype of <code>Object[]</code>.</p>
<h4 id="whatyoucando">What you can do</h4>
<p><em>Covariance</em> means that you're able to get out the object from the <em>covariant</em> structure. Lets take this in an array.</p>
<pre><code>void extract(List[] arr) {
    List list = arr[0];
    Object ob = arr[0];
}
</code></pre>
<p>So due to arrays being <em>covariant</em> you're able to extract values. This is because anything passed in must be a subtype of <code>List[] arr</code>. Therefore we at <em>least</em> have a <code>List[] arr</code>. We may have been passed in anything that is a subtype of <code>List</code> as well.</p>
<p>Therefore we can get out a <code>List</code> and any super-type of <code>List</code> with guarantees that it will not fail.</p>
<h4 id="whatyoucannotdo">What you cannot do</h4>
<p><em>Covariance</em> has its problems. Lets take a peek</p>
<pre><code>public static void main(String[] args) {
    String[] names = {&quot;Paul&quot;, &quot;Kirren&quot;, &quot;Bianca&quot;};
    Object[] casted = (Object[]) names;

	// This is NOT a syntax error
    casted[0] = 1;
}
</code></pre>
<p>In this case we've successfully down casted to an <code>Object[]</code>. This is valid because <code>Object[]</code> is the superclass of <code>String[]</code>.</p>
<p>The problem occurs when you attempt to insert into the array. Any object at all is allowed into an <code>Object[]</code> array. If the base array was of type <code>Object[]</code> that would be fine! Unfortunately in our case it's of type <code>String[]</code> and thus fails with:</p>
<pre><code>Exception in thread &quot;main&quot; java.lang.ArrayStoreException: java.lang.Integer
</code></pre>
<h2 id="contravariant">Contravariant</h2>
<p>Contravariant if the order is reversed from <em>Covariant</em>.</p>
<blockquote>
<p><code>Action&lt;Animal&gt;</code> is a subtype of <code>Action&lt;Cat&gt;</code></p>
</blockquote>
<p>The sub-typing is reversed because <code>Action&lt;T&gt;</code> is contra-variant on <code>T</code>.</p>
<pre><code>import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        take(new ArrayList&lt;Object&gt;());
        take(new ArrayList&lt;Integer&gt;());

        // This is a SYNTAX error, as it's not a superclass of Integer
        take(new ArrayList&lt;Extension&gt;());
        // So is this, it's totally unrelated to Integer
        take(new ArrayList&lt;String&gt;());
    }

    public static void take(List&lt;? super Integer&gt; list) {
        // I know that the BASE list is of type Integer, or any Super class
        // So what do we get out of this?
        // We are guaranteed to be able to Insert integers!
        list.add(new Integer(5));

         // Note that this does not allow us to insert anything in the super chain
         list.add(new Object()); // This is invalid. We could have a List&lt;Integer&gt;
    }

    private static class Extension extends Integer {
        public Extension(int num) {
            super(num);
        }
    }
}
</code></pre>
<h4 id="whatwecando">What we can do!</h4>
<p>Remember the previous example, we weren't able to insert because an <code>Object[]</code> may hide the fact the base array is <code>Integer[]</code>. In this case though, <code>take</code> will only accept Lists that will allow <code>Integer</code> to be inserted. You can easily prove this, as the only superclass of <code>Integer</code> is <code>Object</code>. Thus, this can be provided a <code>List&lt;Object&gt;</code> or a <code>List&lt;Integer&gt;</code>.</p>
<h4 id="whatwecantdo">What we can't do</h4>
<p>Now our problem lies in the opposite. With <code>covariance</code> you're always assured that you're able to extract the type in the variable. <em>Contravariance</em> does not provide us with that same guarantee, in fact, getting a variable from a <em>contravariant</em> structure provides no guarantees and can fail.</p>
<p>In this case, imagine <code>take</code> was provided with a <code>List&lt;Object&gt;</code>, you would be unable to take an <code>Integer</code> from it.</p>
<p>So <em>contravariance</em> allows for insertion, but not extraction. This because you know that the container provided knows how to store at least one type in the hierarchy, therefore, your object.</p>
<h2 id="insummary">In Summary</h2>
<p>Do you need to get able to get objects out? Make sure that your container is <em>covariant</em>.<br>
Do you need to be able be able to insert objects? Make sure it's <em>contravariant</em>.</p>
]]></content:encoded></item><item><title><![CDATA[Diffie-Hellman key exchange]]></title><description><![CDATA[<link rel="stylesheet" href="https://www.devslash.net/assets/dh.css">
The Diffie-Hellman was one of the largest changes in cryptography over the past few decades. It suddenly allowed for people to perform a key exchange over an unsecured line. This instantly had dramatic effects to furthering the cause of cryptography.
<p>One was suddenly able to create a secure connection with</p>]]></description><link>https://devslash.net/diffie-hellman-merkle-key-exchange/</link><guid isPermaLink="false">5a76dcb2af8c8c196db50e0e</guid><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Fri, 29 May 2015 05:34:08 GMT</pubDate><content:encoded><![CDATA[<link rel="stylesheet" href="https://www.devslash.net/assets/dh.css">
The Diffie-Hellman was one of the largest changes in cryptography over the past few decades. It suddenly allowed for people to perform a key exchange over an unsecured line. This instantly had dramatic effects to furthering the cause of cryptography.
<p>One was suddenly able to create a secure connection with a person that they had never met before. Previously keys had to be exchanged in some already secure manner such as an in-person exchange. Often this was done in person by exchanging books of keys for use in cyphers. This has obvious downsides, the largest of which being a captured key list will cause all others using the same key list to have their communications suddenly become completely compromised.</p>
<p>This lack of ability to exchange keys upon starting communication meant that in situations such as WWII submarines would often have large amounts of keys stored. That way on their long trips without docking they were able to keep up continuous conversation. A well known example of this is <a href="http://en.wikipedia.org/wiki/German_submarine_U-559">U-559</a>, a German submarine that was forced to surface after the Allies uncovered her location. Upon doing so the Allies instantly attempted to recover the code books. They were successful the code breakers at Bletchley Park were able to break the Naval enigma for several weeks.</p>
<p>Though this is an example which one can definitely make the point that it's a good thing that we didn't have D-H key exchange it does point out the obvious problems that cryptanalisys has been having since rather recently.</p>
<h2 id="thegeneralidea">The general idea</h2>
<p>An often used analogy of the key exchange is colours.</p>
<ul>
<li>User A selects a secret colour <span id="firstClass"></span></li>
<li>User B selects a secret colour <span id="secondClass"></span></li>
<li>User A and B agree on a shared colour <span id="shareClass"></span></li>
<li>Users A and B mix their colour and the shared colour</li>
<li>Users A and B swap their mixed colour</li>
<li>Users A and B add their own colour to the colour that the other person gave them</li>
</ul>
<p>After this they will both end up with the same colour. All we have to do is find a mathematical basis that will work the same.</p>
<h2 id="thesecurity">The Security</h2>
<p>The security of the above exchange hinges on anything that was made public. In our example it was the two mixed colours that were made public. If an eavesdropper was able to reverse the mixing process they would suddenly be able to figure out each persons' original colour. In our example one can imagine it's rather difficult to remove a colour from a mix. So we just need to make sure that in the mathematics that is used the <em>mixing</em> step will also create a result that makes it difficult to reverse.</p>
<h2 id="thealgorithm">The Algorithm</h2>
<p>We'll start off with the two traditional characters <strong>Alice</strong> and <strong>Bob</strong>. They want to decide on a key that will be used for their encryption.</p>
<p>Diffie-Hellman is <em>not</em> involved in the actual encryption of data. It is only a key exchange algorithm and as such this algorithm only needs to resolve to a shared key that <strong>Alice</strong> and <strong>Bob</strong> both can work out.</p>
<p>To start off with they will decide on the a <em>public</em> prime number. So lets say they decided on <strong>29</strong> (<code>p = 29</code>). As well as that a <a href="http://mathworld.wolfram.com/PrimitiveRoot.html">Primitive Root</a> must be decided on. This depends on the prime number, and in our case will be 18 (<code>g = 8</code>).</p>
<p>Both <strong>Alice</strong> and <strong>Bob</strong> then will choose their own secret number. This does not have to be prime.</p>
<ul>
<li>Alice chooses 8</li>
<li>Bob chooses 5</li>
</ul>
<p>They then perform the equation <code>Share = g<sup>a</sup> mod p</code> where <code>a</code> is their secret number.</p>
<ul>
<li><strong>Alice</strong> - <code>8<sup>8</sup> mod(29) = 20</code></li>
<li><strong>Bob</strong> - <code>8<sup>5</sup> mod(29) = 27</code></li>
</ul>
<p>They now share that number with each other. So <strong>Alice</strong> sends the number 20 to <strong>Bob</strong> and <strong>Bob</strong> replies with 27.</p>
<p>They will then perform the following on the number received.</p>
<p><code>S = r<sup>a</sup> mod(p)</code></p>
<p>where r is the number they received.</p>
<p><strong>Alice</strong> - <code>27<sup>8</sup> mod(29) = 24</code><br>
<strong>Bob</strong>   - <code>20<sup>5</sup> mod(29) = 24</code></p>
<p>Notice that they both arrived at the result of 24? That will now be the agreed value for their further encryption that takes place. Of course this is just an example and small values were used, in actual implementations they will instead use very large primes and integers.</p>
<h2 id="securityandvalidity">Security and Validity</h2>
<p>Generally maths people will only be keen on using something if they have a proper proof that it works. So lets start by ensuring that we didn't just happen to be lucky when creating our example above. To do this we need to start by defining general numbers.</p>
<pre>
p = prime decided
g = primitive root

A = Alice's secret number
B = Bob's secret number

A<sub>i</sub> = Alice's intemediatry result
   = g<sup>A</sup> mod(p)
   
B<sub>i</sub> = Bob's intemediatry result
   = g<sup>B</sup> mod(p)

A<sub>R</sub> = B<sub>i</sub><sup>A</sup> mod(p)
B<sub>R</sub> = A<sub>i</sub><sup>B</sup> mod(p)
</pre>
<p><em>note this is in a working state. Published for editing</em></p>
]]></content:encoded></item><item><title><![CDATA[RSA Explained using Examples]]></title><description><![CDATA[<link rel="stylesheet" href="https://www.devslash.net/assets/css/extras.css">
RSA provides a fantastic method for allowing public key cryptography. For many years it was a debated topic whether it was possible at *all* to create a scheme for public cryptography. But in the year 1977 Ron Rivest, Adi Shamir, and Leonard Adleman published a paper on RSA, so named]]></description><link>https://devslash.net/rsa-by-example/</link><guid isPermaLink="false">5a76dcb2af8c8c196db50e0d</guid><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Wed, 28 Jan 2015 09:08:04 GMT</pubDate><content:encoded><![CDATA[<link rel="stylesheet" href="https://www.devslash.net/assets/css/extras.css">
RSA provides a fantastic method for allowing public key cryptography. For many years it was a debated topic whether it was possible at *all* to create a scheme for public cryptography. But in the year 1977 Ron Rivest, Adi Shamir, and Leonard Adleman published a paper on RSA, so named for the first letter of each of their last names. 
<div class="sidenote">
<div class="exclaim">
</div>
<p>
A curious side-note comes from the fact that Rivest, Shamir and Adleman were not actually the first people to have uncovered the algorithm. English intelligence had created a similar algorithm as early as 1973. The story goes that a new hire to the agency was introduced around the office. His name was Clifford Cocks. On the tour he met James H. Ellis where he learned that James had been working on the problem of public-private key systems for a long while. Clifford Cocks must have missed the part about the difficulty of the problem as he went to his office and decided to spend the day seeing if <i>he</i> could manage to solve this difficult problem. 
</p>
<p>
Later in the day he comes back to talk to Mr Ellis mentioning that he believes he'd solved the problem. A fresh set of eyes to the problem appeared to be all that it needed as it solved the problem that Mr Ellis had been working on for years.</p>
</div>
<h2 id="letsgetdowntobusiness"><a href="https://www.youtube.com/watch?v=ZSS5dEeMX64">L</a>ets get down to business</h2>
<p>Lets have a look at an example of RSA before we get into how it works.</p>
<p>In each of these examples we have the following 'actors'.</p>
<ul>
<li><strong>Alice</strong> - Good guy, friends with Bob</li>
<li><strong>Bob</strong> - Good guy, friends with Alice</li>
<li><strong>Eve</strong> - An eavesdropper. Pretty keen to hear what Alice and Bob are up to.</li>
</ul>
<p>So to send a message between Alice and Bob we're first going to have to generate our set of public-private keys. The steps for that are below. We'll go through it in more detail in a moment.</p>
<ul>
<li><strong>Alice</strong> chooses  some <em>prime numbers</em> <br><br>
<strong>p</strong> = 17 <br><br>
<strong>q</strong> = 19</li>
<li><strong>Alice</strong> Computes n <code>n = p * q</code><br><br>
<strong>n</strong> = 17 * 19 = 323 <br><br>
<strong>Alice can share n with anyone. It's not secret.</strong></li>
<li>Compute <code>φ(n) = (p-1)(q-1) = 16 * 18 = 288</code></li>
<li>Choose an number <code>e</code> such that <code>1 &lt; e &lt; φ(n)</code></li>
<li><code>gcd(e, φ(n) = 1</code> therefore <code>e</code> and <code>φ(n)</code> are coprime</li>
<li>Our example <code>e = 11</code><br><br>
<strong>Alice can share e with anyone. It's not secret.</strong></li>
<li>Determine <code>d = e<sup>-1</sup> mod φ(n)</code></li>
<li><code>d = 11<sup>-1</sup> mod(288)</code></li>
<li>Our example makes <code>d = 131</code></li>
</ul>
<p>With these numbers we can now make our set of public/private keys.</p>
<h4 id="publickey">Public Key</h4>
<p>A public key is made up of <strong>n</strong> and <strong>e</strong>. <strong>n</strong> being the multiplication of the two large prime numbers and <strong>e</strong> being a number between 1 and 288 that had a greatest common divisor with 288 as 1. Often you're fine to just choose a random prime, but do test that <code>gcd(e, φ(n)) = 1</code> is true.</p>
<p><span class="emphasize"><strong>Alice's</strong> public key is (323, 11)</span></p>
<h4 id="privatekey">Private Key</h4>
<p>Alice's private key is first of all made up with the same <strong>n</strong> that her public key was made from. The difference is that the other number used for the key is <strong>d</strong>. This number was the multiplicative inverse of <code>e (modulo φ(n))</code>. We'll go into why this works a bit later but for now you can just solve the equation <code>d = e<sup>-1</sup> mod(288)</code>. This is done through the Extended Euclid's Algorithm (see below).</p>
<p><span class="emphasize"><strong>Alice's</strong> private key is (323, 131)</span></p>
<h4 id="howtousethem">How to use them</h4>
<p>This is where Bob comes in. Bob wants to send Alice the message: <code>you should not trust eve</code>. First Bob knows that any message that he sends must be of an integer value less than <code>n</code>. In this case any message must be less than <code>228</code>. This counts as <code>11100100</code> in binary. So therefore we can set an easy upper bound on only transmitting 7 bits at a time. So lets make our string!</p>
<pre><code>&gt;&gt;&gt; ' '.join(format(ord(x), 'b') for x in &quot;you should not trust eve&quot;)
'1111001 1101111 1110101 100000 1110011 1101000 1101111 1110101 1101100 1100100 100000 1101110 1101111 1110100 100000 1110100 1110010 1110101 1110011 1110100 100000 1100101 1110110 1100101'
</code></pre>
<h3 id="encodingusingthepublickey">Encoding using the Public Key</h3>
<p>Lets take our first message to send <code>1111001</code> and convert it to decimal. Once a decimal we will be able to encode it using the following equation.</p>
<p><span class="emphasize"><strong>Encrypt</strong> as follows: <code>CypherText of Message M = M<sup>e</sup> log(n)</code></span></p>
<p>So our binary data can be converted to decimal and will come out as the number <em>121</em>. We then need to encode this data so that only Alice will be able to read it. Once we do this Bob will not be able to decrypt it again. It's a one way step.</p>
<p>In our example we end up with</p>
<pre><code>c(M) = M<sup>e</sup> mod(n)
     = 121<sup>11</sup> mod(323)
     = 379,749,833,583,241 mod(323)
     = 144
</code></pre>
<p>Our first letter is now encoded as 144 or binary 10010000. This can then be sent across the wire to Alice.</p>
<h3 id="letsdecryptusingtheprivatekey">Lets Decrypt - Using the Private Key</h3>
<p>Alice and only Alice will be able to decrypt the data (assuming that good values were used for the primes originally). So to do that she'll need to perform the following</p>
<p><span class="emphasize"><strong>Decrypt</strong> as <code>Plain Text from Message C = C<sup>d</sup> mod(n) </code></span></p>
<pre><code>m(C) = C<sup>d</sup> mod(n)
     = 144<sup>131</sup> mod(323)
     = 121
</code></pre>
<p>We have just managed to encrypt what is the first letter of our message. We can set this as binary again and convert it back again.</p>
<pre><code>&gt;&gt;&gt; str(unichr(int('01111001', 2)))
'y'
</code></pre>
<p>Thus we've managed to send our first letter of our string to Alice. The rest can of course be completed in much the same way.</p>
<h3 id="whatmakesthisstrong">What makes this strong?</h3>
<p>It's all well and good to show that we can go encrypt and decrypt a number. But to prove that it's a good idea we've got to make sure that the public key does not leak any required information. There's a few things that we need to make sure that we can ensure.</p>
<ul>
<li>That Bob was <em>definitely</em> using Alice's public key when encrypting</li>
<li>That Alice was <em>definitely</em> receiving a message from Bob</li>
<li>That Eve was unable to infer the private key from listening to all public communication to Bob.</li>
</ul>
<p>Lets start with the last one.</p>
<h3 id="stoppingthecracker">Stopping the Cracker</h3>
<p>In our above case there wasn't much that was transmitted publicly. The only information that is available is the public key, and anyone at all can get this. The idea behind a public key is to not keep it safe, it should be able to stand by itself.</p>
<p>With that in mind lets take a look at the information provided in the public key.</p>
<ul>
<li><strong>n</strong> - The multiplication of the two original primes</li>
<li><strong>e</strong> - A number less than n that is relatively prime number to n</li>
</ul>
<p>So to get the private key Eve will need to get the factors of <strong>n</strong> and the number <strong>d</strong> where d was the multiplicative inverse of e mod n.</p>
<h4 id="nwhyitshard">N - Why it's hard</h4>
<p>So within N are two pieces of information that would unravel the whole thing. If you look at the original process the only numbers that are needed to work out the private key are <strong>p</strong>, <strong>q</strong> (the primes used in the original n equation) and <strong>e</strong>. Seeing we already have <strong>e</strong> we had better hope that finding out <strong>p</strong> and <strong>q</strong> is difficult.</p>
<p>Thankfully. It turns out that it is. It's really, <em>really</em> difficult.</p>
<p>When creating your p and q values each of them is most likely a prime number with a bit length of ~1024. So our number n is going to be incredibly large. This is of prime security concern as we need to make it as difficult as possible to factorise n. If n is ever factorised then suddenly we've lost all of our security as the private key is trivial to figure out.</p>
<p>The problem of <a href="http://en.wikipedia.org/wiki/Integer_factorization">Integer Factorisation</a> is a difficult problem. Without the use of Quantum computer (and Shor's algorithm) we are unable to currently solve this in a respectable time. Most of the methods that do work are based around trying a heap of values. For this reason we are able to be fairly sure that if we choose strong primes in p and q that the key will not be cracked (at least for a few thousand millennia).</p>
<h3 id="interactiveexample">Interactive Example!</h3>
<select id="psel">
  <option selected="selected">P - The first prime</option>
  <option>4001</option>
  <option>4003</option>
  <option>4007</option>
  <option>4013</option>
  <option>4019</option>
  <option>4021</option>
  <option>4027</option>
  <option>4049</option>
  <option>4051</option>
  <option>4057</option>
  <option>4073</option>
  <option>4079</option>
  <option>4091</option>
  <option>4093</option>
  <option>4099</option>
  <option>4111</option>
  <option>4127</option>
  <option>4129</option>
  <option>4133</option>
  <option>4139</option>
  <option>4153</option>
  <option>4157</option>
  <option>4159</option>
  <option>4177</option>
  <option>4201</option>
  <option>4211</option>
  <option>4217</option>
  <option>4219</option>
  <option>4229</option>
  <option>4231</option>
  <option>4241</option>
  <option>4243</option>
  <option>4253</option>
  <option>4259</option>
  <option>4261</option>
  <option>4271</option>
  <option>4273</option>
  <option>4283</option>
  <option>4289</option>
  <option>4297</option>
  <option>4327</option>
  <option>4337</option>
  <option>4339</option>
  <option>4349</option>
  <option>4357</option>
  <option>4363</option>
  <option>4373</option>
  <option>4391</option>
  <option>4397</option>
  <option>4409</option>
  <option>4421</option>
  <option>4423</option>
  <option>4441</option>
  <option>4447</option>
  <option>4451</option>
  <option>4457</option>
  <option>4463</option>
  <option>4481</option>
  <option>4483</option>
  <option>4493</option>
  <option>4507</option>
  <option>4513</option>
  <option>4517</option>
  <option>4519</option>
  <option>4523</option>
  <option>4547</option>
  <option>4549</option>
  <option>4561</option>
  <option>4567</option>
  <option>4583</option>
  <option>4591</option>
  <option>4597</option>
  <option>4603</option>
  <option>4621</option>
  <option>4637</option>
  <option>4639</option>
  <option>4643</option>
  <option>4649</option>
  <option>4651</option>
  <option>4657</option>
  <option>4663</option>
  <option>4673</option>
  <option>4679</option>
  <option>4691</option>
  <option>4703</option>
  <option>4721</option>
  <option>4723</option>
  <option>4729</option>
  <option>4733</option>
  <option>4751</option>
  <option>4759</option>
  <option>4783</option>
  <option>4787</option>
  <option>4789</option>
  <option>4793</option>
  <option>4799</option>
  <option>4801</option>
  <option>4813</option>
  <option>4817</option>
  <option>4831</option>
  <option>4861</option>
  <option>4871</option>
  <option>4877</option>
  <option>4889</option>
  <option>4903</option>
  <option>4909</option>
  <option>4919</option>
  <option>4931</option>
  <option>4933</option>
  <option>4937</option>
  <option>4943</option>
  <option>4951</option>
  <option>4957</option>
  <option>4967</option>
  <option>4969</option>
  <option>4973</option>
  <option>4987</option>
  <option>4993</option>
  <option>4999</option>
</select>
<select id="qsel">
<option selected="selected">Q - The first prime</option>
  <option>4001</option>
  <option>4003</option>
  <option>4007</option>
  <option>4013</option>
  <option>4019</option>
  <option>4021</option>
  <option>4027</option>
  <option>4049</option>
  <option>4051</option>
  <option>4057</option>
  <option>4073</option>
  <option>4079</option>
  <option>4091</option>
  <option>4093</option>
  <option>4099</option>
  <option>4111</option>
  <option>4127</option>
  <option>4129</option>
  <option>4133</option>
  <option>4139</option>
  <option>4153</option>
  <option>4157</option>
  <option>4159</option>
  <option>4177</option>
  <option>4201</option>
  <option>4211</option>
  <option>4217</option>
  <option>4219</option>
  <option>4229</option>
  <option>4231</option>
  <option>4241</option>
  <option>4243</option>
  <option>4253</option>
  <option>4259</option>
  <option>4261</option>
  <option>4271</option>
  <option>4273</option>
  <option>4283</option>
  <option>4289</option>
  <option>4297</option>
  <option>4327</option>
  <option>4337</option>
  <option>4339</option>
  <option>4349</option>
  <option>4357</option>
  <option>4363</option>
  <option>4373</option>
  <option>4391</option>
  <option>4397</option>
  <option>4409</option>
  <option>4421</option>
  <option>4423</option>
  <option>4441</option>
  <option>4447</option>
  <option>4451</option>
  <option>4457</option>
  <option>4463</option>
  <option>4481</option>
  <option>4483</option>
  <option>4493</option>
  <option>4507</option>
  <option>4513</option>
  <option>4517</option>
  <option>4519</option>
  <option>4523</option>
  <option>4547</option>
  <option>4549</option>
  <option>4561</option>
  <option>4567</option>
  <option>4583</option>
  <option>4591</option>
  <option>4597</option>
  <option>4603</option>
  <option>4621</option>
  <option>4637</option>
  <option>4639</option>
  <option>4643</option>
  <option>4649</option>
  <option>4651</option>
  <option>4657</option>
  <option>4663</option>
  <option>4673</option>
  <option>4679</option>
  <option>4691</option>
  <option>4703</option>
  <option>4721</option>
  <option>4723</option>
  <option>4729</option>
  <option>4733</option>
  <option>4751</option>
  <option>4759</option>
  <option>4783</option>
  <option>4787</option>
  <option>4789</option>
  <option>4793</option>
  <option>4799</option>
  <option>4801</option>
  <option>4813</option>
  <option>4817</option>
  <option>4831</option>
  <option>4861</option>
  <option>4871</option>
  <option>4877</option>
  <option>4889</option>
  <option>4903</option>
  <option>4909</option>
  <option>4919</option>
  <option>4931</option>
  <option>4933</option>
  <option>4937</option>
  <option>4943</option>
  <option>4951</option>
  <option>4957</option>
  <option>4967</option>
  <option>4969</option>
  <option>4973</option>
  <option>4987</option>
  <option>4993</option>
  <option>4999</option>
</select>
<p>n = <span id="p"></span> x <span id="q"></span> = <span id="ans"></span></p>
<p>φ(n) = (<span id="pine"></span>-1)(<span id="qine"></span>-1) = <span id="secresult"></span></p>
<p>Now we need to choose 1 &lt; <strong>e</strong> &lt; φ(n) and gcd(e, φ(n)) = 1;<br>
We'll choose a common e that's used. That being  65,537 which is 2<sup>16</sup>+1</p>
<p><b>Values</b><br><br>
<b>N:</b><span id="ansn"></span><br><br>
<b>φ(n):</b><span id="ansg"></span><br><br>
<b>E:</b>65537<br><br>
<b>D:</b><span id="ansd"></span></p>
<h4>Public Key</h4>
<p>(e,n) = (<span id="pe"></span>, <span id="pn"></span>)</p>
<h4>Private Key</h4>
<p>(d,n) = (<span id="rd"></span>, <span id="rn"></span>)</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//Populate the primes
$("#psel").change(function(){$("#p").text(this.value);checkN()})
$("#qsel").change(function(){$("#q").text(this.value);checkN()})

function checkN(){
	var p = +$("#psel").val()
	var q = +$("#qsel").val()

	if(isNaN(p) || isNaN(q))
		return;

	var n = p*q;
	var t = (p-1)*(q-1)
	$("#ans").text(n)
	$("#ansn").text(n)
	$("#pn").text(n)
	$("#rn").text(n)
	$("#ansg").text(t)

	$("#pine").text(p)
	$("#qine").text(q)
	$("#secresult").text(t)

	res = xgcd(65537, t)[0]
	if(res < 0)
		res = res + t;

	$("#ansd").text(res);
	$("#pe").text('65537')
	$("#rd").text(res)

}


function xgcd(a, b) { 

	if (b == 0) {
		return [1, 0, a];
	}

	temp = xgcd(b, a % b);
	x = temp[0];
	y = temp[1];
	d = temp[2];
	return [y, x-y*Math.floor(a/b), d];
}
</script>]]></content:encoded></item><item><title><![CDATA[Git Hooks with Python]]></title><description><![CDATA[<p><a href="http://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks">Git hooks</a> have long provided the ability for you to validate commits, perform continuous integration, continuous deployment and any number of other arbitrary actions.</p>
<p>Git hooks are often run as a bash script. For the hobby programmer or this may be a bit annoying to have to learn how to</p>]]></description><link>https://devslash.net/easy-git-hooks-with-python/</link><guid isPermaLink="false">5a76dcb2af8c8c196db50e09</guid><category><![CDATA[git]]></category><category><![CDATA[hooks]]></category><category><![CDATA[python]]></category><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Sat, 27 Dec 2014 03:14:30 GMT</pubDate><content:encoded><![CDATA[<p><a href="http://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks">Git hooks</a> have long provided the ability for you to validate commits, perform continuous integration, continuous deployment and any number of other arbitrary actions.</p>
<p>Git hooks are often run as a bash script. For the hobby programmer or this may be a bit annoying to have to learn how to use Bash just to make sure each commit will always include a meaningful commit message linked with a JIRA message, or to take a restart a server after files have been updated.</p>
<p>Thankfully it's practical and simple to make the git hook gracefully hand off the grunt work to a python script (or any other language for that matter).</p>
<h3 id="gettingstarted">Getting Started</h3>
<p>Today we're going to delve into the client side git hooks. They come in several flavours all meant for hooking into different parts of the process.</p>
<ul>
<li><code>pre-commit</code> Runs before you've even entered your commit message. Here you can take a look at the current snapshot. You're able to check for all sorts of code requirements here such as code style, tests passing, builds running, etc. A non-zero return from a script would abort the commit.</li>
<li><code>prepare-commit-msg</code> This will run before the user is asked for their commit message. It allows a hook to edit the default message to provide to the user. This would enable you to create a commit that would set the default message as something like the classes the classes that have been added. A non-zero return from a script would abort the commit. This hook is provided the following parameters:</li>
<li>Reference to file that holds the commit message so far. This can be edited to be changed to whatever you're after.</li>
<li>Type of commit (merge, fast forward, etc)</li>
<li>SHA-1 of the commit</li>
<li><code>commit-msg</code> Runs prior to a commit being completely verified but after the commit message has been created. This will run with a single parameter which is a file reference to the commit message. A non-zer exit value will abort the commit.</li>
<li><code>post-commit</code> Runs once the commit has been completely finalized. A non-zero return from this hook will not cause the commit to fail. This is mainly used for notification purposes for that reason.</li>
</ul>
<h3 id="examplecommitmsghook">Example - <code>commit-msg</code> Hook</h3>
<p>Unsurprisingly we have a small sidebar for the Windows users to get this working. As windows doesn't recognise the <a href="http://en.wikipedia.org/wiki/Shebang_%28Unix%29">shebang</a> (#!) at the start of a file we will only have the option of writing the git hook in a way that <code>cmd.exe</code> will understand. So to get started we create this small file in your base directory of your poject.</p>
<p><strong>.git/hooks/commit-msg</strong></p>
<pre><code class="language-language-bash">#!/bin/sh
python .git/hooks/commit-message.py
</code></pre>
<p>This file can still be used on Linux/Mac (as to why we've put the shebang in the start still). This will then mean that before any commit is created and placed in the git log the <code>pre-commit-hook.py</code> file will run. The return code for the python script will then be used as the overall return code for the script.</p>
<p>In all further references to <code>.git/hooks/commit-msg</code> you can assume we're talking about <code>.git/hooks/commit-msg.py</code> if you're using Windows.</p>
<h4 id="usingpython">Using Python</h4>
<p>So lets open up our python file and create a small tool that will perform some basic action for us.</p>
<p><strong>.git/hooks/commit-msg</strong></p>
<pre><code class="language-language-python">#!/usr/bin/env python

import sys

print &quot;Starting commit-msg hook&quot;

sys.exit(0)
</code></pre>
<p>This example will exit with a system code of 0. Zero indicates success, any non zero value will indicate that the commit is unsuccesful. When creating a commit now we will get the following output:</p>
<pre><code class="language-language-shell">paul@laptop ~/gitProjects/easygitwithpython $ git add *
paul@laptop ~/gitProjects/easygitwithpython $ git commit -m &quot;Hi there&quot;
Starting pre-commit hook
[master b5254f4] Starting commit-msg hook
 1 file changed, 1 insertion(+), 1 deletion(-)
paul@laptop ~/gitProjects/easygitwithpython $ 
</code></pre>
<h3 id="gettingmoreuseful">Getting more useful</h3>
<p>We can extend our previous example to make use of the commit data. An example of this is making sure that a commit message is above a certain length and matches a regular expression for a JIRA issue.</p>
<p><strong>.git/hooks/commit-msg</strong></p>
<pre><code class="language-language-python">import sys, re

#Required parts 
requiredRegex = &quot;[A-Z]{2,}-\\d+&quot;
requiredLength = 15

#Get the commit file
commitMessageFile = open(sys.argv[1]) #The first argument is the file
commitMessage = commitMessageFile.read().strip()

if len(commitMessage) &lt; requiredLength:
    print &quot;Commit message is less than the required 15 characters.&quot;
    sys.exit(1)
    
if re.search(requiredRegex, commitMessage) is not None:
    print &quot;A JIRA issue must be linked with a commit&quot;
    sys.exit(1)

print &quot;Commit message is validated&quot;
sys.exit(0)
</code></pre>
<p>The prepare-commit-msg git hook will have a single argument, that is a file reference to the commit message that has been set. This hook runs before the commit has fully been validated and as such a non-zero return code will still cause the git commit to fail.</p>
<p>You can see the following confirmation of this hook</p>
<pre><code class="language-language-base">paul@laptop ~/gitProjects/easygitwithpython $ git commit -m &quot;short&quot;
Commit message is less than the required 15 characters.
paul@laptop ~/gitProjects/easygitwithpython $ git commit -m &quot;A long message, no JIRA issue&quot;
A JIRA issue must be linked with a commit
paul@laptop ~/gitProjects/easygitwithpython $ git commit -m &quot;A long message, with JIRA-123&quot;
Commit message is validated
[master 0ecdd0d] A long message, with JIRA-123
 1 file changed, 1 insertion(+)
paul@laptop ~/gitProjects/easygitwithpython $ 
</code></pre>
<p>Another windows caveat. When using commit hooks that require passing through the argument to the Python file you'll need to have your prepare-commit-msg to pass through those arguments manually.</p>
<p><strong>.git/hooks/commit-msg</strong></p>
<pre><code class="language-langauge-bash">#!/bin/sh
python commit-msg.py $1
</code></pre>
<p>This will pass through the first argument to Python and will get you to the same level that Unix systems are up to.</p>
<h3 id="usingserversidehooks">Using Server Side Hooks</h3>
<p>One problem that comes with hooks is that you are not able to enforce them on any client who has cloned your repository. This may seem annoying but it definitely for good reason. If one was able to enforge git hooks on a repository then you'd be effectively forcing your users to run arbitrary code on their machines.</p>
<p>For this reason it's often better to rely on push hooks. This will allow you to only run the code on a trusted place. So with that in mind, we can delve into our possible <a href="http://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks#Server-Side-Hooks">server side git hooks</a>. They are as follows.</p>
<ul>
<li><strong>pre-receive</strong> - Gets a list of references that are being changed. A non-zero return will cause all to be rejected.</li>
<li><strong>update</strong> - Runs for each branch that is being pushed. A non-zero return will cause the branch individually to be rejected</li>
<li><strong>post-receive</strong> - Runs once the commits have been succesfully pushed. Usually used for notifications or for deploying to a production site.</li>
</ul>
<p><em>We'll go further into server side hooks in a further post</em></p>
]]></content:encoded></item><item><title><![CDATA[Testing With Gradle]]></title><description><![CDATA[<div id="contentsjs">
</div>
<p style="text-align: center;">I love Android.</p>
<p style="text-align: center;">I also think that testing is super duper.</p>
<p>For this reason I've always been a big fan of attempting to find ways to perform better testing. Whether this be through use of continuous integration, mocking or even <em>sweet as</em> dependency injection coupled with Gradle.</p>
<h2 id="simplegradleexample">Simple Gradle Example</h2>]]></description><link>https://devslash.net/testing-with-gradle/</link><guid isPermaLink="false">5a76dcb2af8c8c196db50e04</guid><category><![CDATA[gradle]]></category><category><![CDATA[android]]></category><category><![CDATA[java]]></category><category><![CDATA[testing]]></category><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Mon, 22 Dec 2014 08:51:00 GMT</pubDate><content:encoded><![CDATA[<div id="contentsjs">
</div>
<p style="text-align: center;">I love Android.</p>
<p style="text-align: center;">I also think that testing is super duper.</p>
<p>For this reason I've always been a big fan of attempting to find ways to perform better testing. Whether this be through use of continuous integration, mocking or even <em>sweet as</em> dependency injection coupled with Gradle.</p>
<h2 id="simplegradleexample">Simple Gradle Example</h2>
<p>Gradle allows very easily to allow for different flavours or build configurations. A very small example that shows a small change in builds is below. It is an exerpt from a larger Android <code>build.gradle</code> that will set various build configurations based on the build type.</p>
<pre><code>buildTypes {
    release {
        signingConfig signingConfigs.release
        minifyEnabled false
    }
    debug {
        minifyEnabled false
        debuggable true
}
</code></pre>
<p>A quick look at Gradle will make it fairly obvious that we're using a whole lot less boilerplate than the standard Maven POM. We are managing to leverage the Groovy DSL to be more expressive in fewer characters. Surprisingly XML isn't the best thing for all things configuration based.</p>
<p>The above buildTypes will set Android debugging flags. Based on the type of release that is being done, it will switch on debugging and sign the app correctly.</p>
<h2 id="addingsomeandroidflair">Adding some Android flair</h2>
<p>Gradle is a powerful language that means that you're able to very easily perform some simple actions that will affect the global state of your program. The following code example shows off a ways to turn on and off the high logging levels.</p>
<pre><code>release {
    buildConfigField &quot;boolean&quot;, &quot;HIGH_LOGGING&quot;, &quot;false&quot;
}
debug {
    buildConfigField &quot;boolean&quot;, &quot;HIGH_LOGGING&quot;, &quot;true&quot;
}
</code></pre>
<p>This build config field is created in the form</p>
<blockquote>
<p>buildConfigField &lt;type&gt;, &lt;name&gt;, &lt;value&gt;</p>
</blockquote>
<p>We will then be able to use this at any point as a static field in our program via <i>BuildConfig.VARIABLE_NAME</i>. This makes it suddenly incredibly easy to create a logging stub that will allow for easy debug logging. <em>Note that this part of the Android Gradle plugin and does not work out of the box for a Java build</em>.</p>
<pre><code class="language-language-java">public class Logger{

    public static void log( Level logLevel, String message ){
        if( logLevel &gt;= Level.WARN ){
            log.log( logLevel, message );
        }
        else if( BuildConfig.HIGH_LOGGING )
            log.log( logLevel, message );
        }
    }
}
</code></pre>
<p>Suddenly we will have a call to a logger that will always be able to choose how much to log based on the build type. This means whenever you release your apk you will never have a problem of creating a bucket of log files that are over the top but there is ZERO extra configuration that is required when developers are attempting to debug on their own devices.</p>
<p>But we don't have to stop there. Gradle will also let us perform more advanced actions such as those that will include or exclude whole source packages automatically. This allows for you to perform fantastically simple mocking of objects that would otherwise be a pain to switch in and out.</p>
<h2 id="controllingsourcepackageswithgradle">Controlling source packages with Gradle</h2>
<p>Android isn't always easy to perform testing on. This is generally for the same reason that UI testing in the web isn't exactly simple either. For this people generally use products such as HTMLUNIT or other selenium test runners. If you're after something similar <a href="http://robolectric.org/">Robolectric</a> allows you to perform Unit testing with the ability to test as though a UI existed.</p>
<p>Sometimes though that's not enough. When testing apps it's common that the only way that you can find exactly what you need to improve by continually attempting to use your app. This is known as dogfooding and is used extensively in software companies. We can leverage Gradle to allow us to create different APK files for the internal development team. We can combine build types and build flavours to allow us to create builds specifically for tablets, for smaller phones, for paid versions, for free versions. This without too much hair falling out. So lets demonstrate how it would be possible to create app versions that contained debug/release only code.</p>
<h3 id="gettingbuildspecificcontrol">Getting build specific control</h3>
<p>Gradle is run through Groovy. This means that we can technically do anything that we can do in Groovy. Suddenly this means our build system can have logic rather than just a lot of configuration steps. Instead of a barrage of tags all over the place we can instead create dynamic builds, even including user input. This would be fantastic if you wanted to tag a build with a special name. We'd be able to do something like:</p>
<pre><code class="language-language-groovy">android {
    defaultConfig {
        applicationVariants.all { variant -&gt;
            def file = variant.outputFile
            variant.outputFile = new File(file.parent, &quot;supercoolfilename.apk&quot;)        
        }
    }
}
</code></pre>
<p>Which you can extend this to get the user input to do the following.</p>
<pre><code class="language-language-groovy">def console = System.console()

def newname = console.readLine(&quot;Set the APK name &gt;&quot;)

android {
    defaultConfig {
        applicationVariants.all { variant -&gt;
            def file = variant.outputFile
            variant.outputFile = new File(file.parent, newname + &quot;.apk&quot;)
        }
    }
}
</code></pre>
<p>We will now get a console output that will ask us first to confirm the apk name before it actually will get built. But this is really not something that we'll want unless we're releasing (maybe like what Google does with android for mako and other build types). So you can easily extend this to make it totally based on the build version. (<a href="http://stackoverflow.com/questions/25104323/how-to-customize-the-apk-file-name-for-product-flavors%5D">Reference</a>)</p>
<pre><code class="language-language-groovy">def console = System.console()
android {
    applicationVariants.all { variant -&gt;
        if (variant.buildType.name.equals(&quot;debug&quot;)) {
            def apk = variant.outputFile;
            variant.outputFile = new File(apk.parentFile, &quot;debugAndroidApp.apk&quot;);
        } else if(variant.buildType.name.equals(&quot;release&quot;)) {
            def apk = variant.outputFile;
            variant.outputFile = new File(apk.parentFile, &quot;AndroidApp.apk&quot;);
        }
    }
}
</code></pre>
<p>Suddenly we have a way to have build names for each of our releases all in the same number of lines that the standard Maven system would have managed to add two dependencies.</p>
<h3 id="usinggradletodeployalternativefiles">Using Gradle To Deploy Alternative Files</h3>
<p>So up to this point we've done some fairly small things with the Gradle system. It will actually allow us to override class implementations so that we may go ahead and inject different requirements based on our test system. In the following example we're going to use it to inject a sidebar into a fake android app that will allow us to change what we inject into our app. Through this we're able to add things such as a Http Service that fails requests 50% of the time.</p>
<p>To start off with, we'll have a look at the directory structure to create this example:</p>
<pre><code>src  -\
     - main
     - release
     - debug
</code></pre>
<p>All code within the <code>main</code> folder will always be compiled for use. This is code that will exist in both our release and debug builds. The <code>release</code> and <code>debug</code> folders will each be compiled when the relevant gradle build is taking place. The generic way that this is used is <strong>android.sourceSets.&lt;flavour&gt;&lt;ReleaseType&gt;</strong>, so in our case we do not have a flavour so we just use the release type. Therefore <strong>android.sourceSets.release</strong> and <strong>android.sourceSets.debug</strong> are the two that we are using. This corresponds to <code>src/release</code> and <code>src/debug</code>. Every instance of these extends the standard <strong>android.sourceSets.main</strong> which will be in <code>src/main</code>.</p>
<p>To leverage this we will create, a <code>MainActivityExtender</code> which will be implemented in both release types. This will be used to add extra functionality to the <code>MainActivity</code> in the main source set.  A comparison of the files will show the small difference that lies between them.</p>
<p><em><strong>MainActivity.class</strong></em></p>
<pre><code class="language-language-java">class MainActivity extends Activity {

    public SideBarManager(Context ctx, View parentView){
        // Inflate the new View
        setContentView(R.layout.MainActivity);
        
        runDebugPostHook();
    }
    
    public void runPostHook(){
        // Nothing exists here in the MainActivity version
    }
}

</code></pre>
<p><em><strong>/src/debug/net/devlsash/MainActivityExtender.class</strong></em></p>
<pre><code class="language-language-java">class SidebarManagerExtender extends MainActivity {
    
    @Override
    public void runPostHook() {
        // Now we should create new details based on the 
        // fact that we're running in Debug mode
        
    }
    
}
</code></pre>
<p><em><strong>/src/release/net/devlsash/MainActivityExtender.class</strong></em></p>
<pre><code class="language-language-java">class SidebarManagerExtender extends MainActivity {
    // We will not override runPostHook here
}
</code></pre>
<p><em><strong>Android Manifest</strong></em></p>
<pre><code class="language-language-xml">&lt;activity
    android:name=&quot;net.devslash.testapp.RunningMainActivity&quot;
    android:label=&quot;@string/app_name&quot;
    android:windowSoftInputMode=&quot;adjustResize|stateHidden&quot;&gt;
    &lt;intent-filter&gt;
        &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
        &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
    &lt;/intent-filter&gt;
&lt;/activity&gt;
</code></pre>
<p>This may all seem a bit over the top. Couldn't we just do as we did before? Set a flag and perform an if statment to do the same thing? That's completely correct. This is merely what I'd call cleaner and less prone to errors or possible leaking of debug features to the final application.</p>
<p>One thing not demonstrated here is the ability to override xml files. This provides extra utility due to the fact that instead of the following</p>
<pre><code class="language-language-java">Button someButton; 
if(Flag.DEBUG){
    setContentView(R.layout.debugMainActivityLayout);
    someButton = (Button) findViewById(R.id.debugButton);
} else {
    setContentView(R.id.MainActivityLayout);
}
// Then possibly later on
if(someButton != null) {
    // Do something here
}
</code></pre>
<p>With the Gradle source replacement/swapping in we're able to simplify it to</p>
<pre><code class="language-language-java">setContentView(R.layout.MainActivityLayout);
</code></pre>
<p>Then you can place different xml files in the directory <em>src/main/res/layout/MainActivity.xml</em> and <em>src/debug/res/layout/MainActivity.xml</em>. Based on the gradle build type we will override the <em>MainActivity.xml</em> with our debug version whenever it is built.</p>
<p>Then leveraging what we did before in regards to having an extended <code>MainActivity</code> we would be able to access the debug only parts of the XML in our post hook.</p>
<p>Overall Gradle gives a large amount of build configuration steps that otherwise would be a large pain or just take a really long time to do. Gradle's adoption for Android has progressed Gradle a long way as development has continued to move very quickly for a long time. For this reason it's entirely possible that what I've written will be out of date shortly. If you notice this please do leave a comment below and I'll fix up the inaccuracies.</p>
]]></content:encoded></item><item><title><![CDATA[Woops & Ghost]]></title><description><![CDATA[<h3 id="whoops">Whoops</h3>
<p>Never trust shared hosting solutions. They generally suck and mean when you have a dead installation of something (maybe even wordpress?) that you're unable to properly recover.</p>
<p>This now sits in the annals of the Microserver where hopefully it will have a little bit more luck.</p>
<h3 id="movingtoghost">Moving to Ghost</h3>]]></description><link>https://devslash.net/woops-and-ghost/</link><guid isPermaLink="false">5a76dcb1af8c8c196db50e02</guid><category><![CDATA[Getting Started]]></category><dc:creator><![CDATA[Paul Thompson]]></dc:creator><pubDate>Mon, 22 Dec 2014 08:18:51 GMT</pubDate><content:encoded><![CDATA[<h3 id="whoops">Whoops</h3>
<p>Never trust shared hosting solutions. They generally suck and mean when you have a dead installation of something (maybe even wordpress?) that you're unable to properly recover.</p>
<p>This now sits in the annals of the Microserver where hopefully it will have a little bit more luck.</p>
<h3 id="movingtoghost">Moving to Ghost</h3>
<p>After reccommendation I've moved from Wordpress to Ghost. Ghost is run on the back of node.js. It doesn't attempt to offer the same things that Wordpress does. But for that reason it's perfect for what i'm attempting to acheive here. Ghost wants to be a blogging site. Wordpress wants to be a &quot;Web Operating System&quot;</p>
<blockquote>
<p>when you think about it, we’re kind of building a web operating system.</p>
</blockquote>
<p>-Matt Mullenweg</p>
<p>This can be easily compared with the ideology of Ghost. It's plainly pronounced on their main entry to the site.</p>
<p><img src="https://devslash.net/content/images/2014/12/Screenshot-from-2014-12-24-22-13-43.png" alt="Just a blogging platform"></p>
<p>Well that's what I want.</p>
<p>And thus continues my experiment into the foray of technical blogging. I'm currently creating a writeup of the use of gradle in regards to testing with a focus on Android. I should have it finished in a couple of days.</p>
]]></content:encoded></item></channel></rss>