Monday, 16 December 2019

Pithy Saying

At some future period, not very distant as measured by centuries, the civilized races of man will almost certainly exterminate and replace the savage races throughout the world.

Charles Darwin

Friday, 13 December 2019

Secularism and Citizenship

It is a sad state to see that we are quickly going the way of losing our secular identity. Fundamentalists and extremists seem to be rampant on either religious denominations. I pray to the Almighty the Omniscient the Munificent that may peace and harmony prevail forever in the land that gave birth to Netaji Subhash Chandra Bose, the Mahatma, our national pride and the Late President Abul Pakir Jainalubdin Abdul Kalam, Mohammed Rafi Ahmed Kidwai, and many more who shall forever remain etched in the fabric of our nation's great history and proud heritage.

My heart grows sad for no one should feel alienated or segregated. Ghettoisation is neither wanted nor should be tolerated. Jingoism and playing to the crowd are what our nation does not ever require. What our country needs is to eradicate corruption, sectarian violence, ensure that its citizens are protected at night and in remote corners of the country at all times. Our country needs our children to grow strong, healthy and prosperous. Religion is what we turn to to keep our society from plunging into depravity and moral turpitude. Religion is not and should never be a rod to stir up issues for the sake of political mileage and economic benefit for a select few.

It is said that quotes by the Mahatma are the most frequently quoted ones on the Internet. What, therefore, could be better than using one made famous by his views on Truth and Nonviolence - "It is easy enough to be friendly to one's friends. But to befriend the one who regards himself as your enemy is the quintessence of true religion. The other is mere business."


Tuesday, 29 October 2019

Java String Encryption




Think of password encryption in Java programming and the word “BCrypt” springs to mind. There are such several excellent articles and tutorials written on the subject, that one need only examine those at leisure to incorporate the techniques illustrated with ease. I find that the resources available here and here ought to be worth the time for anyone keen on understanding how password encryption can be used and programmed in Java language.

However, it was not until when I came upon this did I really began to appreciate the value of digging deeper into the world of password encryption algorithms and techniques in Java. Interestingly, a comment that appears here set me off on a search to Argon2 password hashing. 

I came upon this excellent resource which uses Jargon2 - an API to assist in implementation of Argon2 password hashing in Java. 

To test whether I was on the right track to use this library, I followed the instructions. The salient features were the inclusion of the following in pom.xml of Java project that I created anew in Eclipse IDE. Before adding the following section to the pom.xml, I converted the Java Project to a Maven Project.


<dependency>
    <groupId>com.kosprov.jargon2</groupId>
    <artifactId>jargon2-api</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>com.kosprov.jargon2</groupId>
    <artifactId>jargon2-native-ri-backend</artifactId>
    <version>1.1.1</version>
    <scope>runtime</scope>
</dependency>

The actual code was straightforward copy of the simple example provided and is reproduced below:


import static com.kosprov.jargon2.api.Jargon2.*;

public class Jargon2EncodedHashExample {
    public static void main(String[] args) {
        byte[] password = "this is a password".getBytes();

        // Configure the hasher
        Hasher hasher = jargon2Hasher()
                .type(Type.ARGON2d) // Data-dependent hashing
                .memoryCost(65536)  // 64MB memory cost
                .timeCost(3)        // 3 passes through memory
                .parallelism(4)     // use 4 lanes and 4 threads
                .saltLength(16)     // 16 random bytes salt
                .hashLength(16);    // 16 bytes output hash

        // Set the password and calculate the encoded hash
        String encodedHash = hasher.password(password).encodedHash();

        System.out.printf("Hash: %s%n", encodedHash);

        // Just get a hold on the verifier. No special configuration needed
        Verifier verifier = jargon2Verifier();

        // Set the encoded hash, the password and verify
        boolean matches = verifier.hash(encodedHash).password(password).verifyEncoded();

        System.out.printf("Matches: %s%n", matches);
    }
}


To make this program run on a standalone basis with all dependencies bundled into it, all I did was to add the following fragment to the pom.xml:



<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.test.argon2.Jargon2EncodedHashExample</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>



Again, the above was copy from an excellent resource to be found here.


The author presents lucid examples on how to use the Jargon2 library. For anyone keen on extending password encryption to another level, this should be an interesting find.



Thursday, 3 October 2019

Dabbling in Plain Text

I am a writer; or at least I pretend to be one. But for all my efforts at writing, the most that I do is reading. Some say, that you need to be an avid reader to come even remotely close to being a writer. That said, writing is not a 9 to 5 business routine that needs to be respected and bowed to at every turn. Far from it. Writing is a feeling that overwhelms you and begs you to take to your smartphone, laptop, PC, tablets, or even to few blank sheets and pencil at odd hours.

Being a person with interest in history and computers, I thought of shoehorning those sources of stimuli into earning my livelihood. Thus far, that task has been onerous at best; and a source of frustration and of many arguments with friends and family at worst. Notwithstanding my struggles, a fate that many aspiring writers probably share as well, writing is a channel that acts as an opiod analgesic. 

Writing, if you like, can be both a release and a profession. It demands interest and a soul to begin with. It also requires a distraction-free environment for the most part.

Think of a normal daily routine. You could be in a public transport riding choc-a-bloc with fellow travellers steaming inside a packed compartment with little room for your own elbow. Or you could be in your own personal transport immersed in your thoughts trying to negotiate rush hour traffic. Whatever be the environment you may find yourself in, it does not take much for any interesting thought to kick in. 

At this point, the urge is to jot down one's thoughts as quickly and as effortlessly as possible. And the tools to do so? Certainly not a piece of pen and paper, for you would be hard-pressed to hold those implements rock steady while on the move. Your best bet would then be the smartphone residing in your pocket. Or an iPad if you are seated, with the steering of the vehicle you are in controlled by someone not hit with the same impulse as yours at that precise moment.

It is at this juncture when you begin to tap in the words you begin to realize the value of screen space. Word processors do not offer distraction-free writing space. On the contrary, menu icons and title bars hog a noticeable portion of the space. Formatting woes fill in your senses while you write. All very acutely distracting.

What you need is simple plain interface with minimalistic approach in terms of visibility, but at the same time loaded on features. Enter the Markdown syntax and iA Writer for Android and iOS.

The iA Writer is offered for Android, iPad, iPhone, Mac and Windows platforms as on date. Thoughtfully crafted, the simplicity of the software makes it attractive for writers who are light-fingered and need thoughts to be inscribed in black and white as quickly as humanly possible. 

And yet with its Markdown syntax support, it is as feature-rich as most writers would like without the often unused options that are offered by word processing apps.

Priced at ₹ 699.00, the iPad version is competitively priced compared to competing cloud models offered by similar apps. The Android version is free. 

While the iA Writer (Android) allows opening and saving of files on Dropbox and on Google Gloud, the iPad version considerably extends the range to include iCloud and OneDrive.  

What all this means is that you and I no longer have to fret over maintaining more than one cloud account if we can help it. Many rely on either Dropbox or OneDrive for storing their documents online. And indeed this does make sense in an age where devices are swapped and can be exchanged or sold within a couple of years or less. 

With the feature that the iA Writer for iPad now offers, connecting to OneDrive can be a lot easier than ever before.

For writers who are on the move, or who need less of distraction at every possible turn, the combination of iA Writer’s text support with cloud storage accessibility and support for prominent brands does look promising.

In case you would like to leave comments or feedback, please feel free to do so by sending an email. I am almost always constantly available and do respond as quickly as possible.

Let me know your questions, if any, that you would like me to help you out with.







Friday, 11 November 2016

Using JNA to call a Windows function without parameters

The applications for Java Native Access are limited only by the functions and parameters that the external DLL files allow. In this post, we discuss how JNA can be used to obtain the process identifying number of the calling process. 

The Kernel32.dll file supports a GetCurrentProcessId function that performs the terribly important function of returning the unique identifying number of the calling process. The return value is an integer. Following is the C++ syntax straight from the msdn page:


DWORD WINAPI GetCurrentProcessId(void);

As can be seen from the function signature, this takes in no parameters at all. 

We begin, next, by creating a new Java application project (I prefer Netbeans IDE). We then, link the necessary jna-4.2.2.jar to the project, and create a new package. Though the creation of the latter is not necessary, it is nonetheless an excellent practice.


The first way to go about There are two ways to go about the project. In the first case, we create a single Java file thus:


package jna01;

import com.sun.jna.Library;
import com.sun.jna.Native;

/**
 *
 * @author satadru
 */
public class jna_pid_01 {
    public interface Kenl32 extends Library {
        Kenl32 INNE = (Kenl32) Native.loadLibrary("kernel32", Kenl32.class);

        public int GetCurrentProcessId();
    }

    public int GetCurrentProcessId(){
        int pid = Kenl32.INNE.GetCurrentProcessId();
        return pid;
    }

    public static void main(String[] a){
        jna_pid_01 jpid = new jna_pid_01();
        
        System.out.println("Own process ID is "+jpid.GetCurrentProcessId());
    }
    
}

This when compiled and run (in Netbeans IDE) results an output that is similar to the one shown here:

run:
Own process ID is 4960
BUILD SUCCESSFUL (total time: 0 seconds)

On examining the single class file, it becomes evident that the interface name Kenl32 does not need to be identical to the primary file name of Kernel32.dll. In fact, this can be any regular valid name so long as it is uniformly addressed. Ditto in case of the instance variable INNE.

The most significant component of the whole code is the method   public int GetCurrentProcessId() which gathers the integer return value from the function call Kenl32.INNE.GetCurrentProcessId(). 



The second approach
Personally, though, I prefer the second approach. Although more complex, this approach allows to have a finer degree of control. 

We begin by creating an appropriate package in the same project. A simple interface is all that is required.

package jna02;

import com.sun.jna.Library;

/**
 *
 * @author satadru
 */
public interface KrnlInface extends Library{
    public int GetCurrentProcessId();
}

We create a suitably appropriate class to return the process ID number.

package jna02;

import com.sun.jna.Native;

/**
 *
 * @author satadru
 */
public class jna_pid01 {

    public static void main(String[] ar) {
        KrnlInface instnc = (KrnlInface) Native.loadLibrary("kernel32", KrnlInface.class);

        System.out.println("Own Process ID number is as follows: " + instnc.GetCurrentProcessId());

    }
}

The resultant output is as follows:

run:
Own Process ID number is as follows: 6068
BUILD SUCCESSFUL (total time: 0 seconds)


Many would find the second way of coding to be cleaner and perhaps slightly more structured.

Users may note that the packages, interfaces and classes have been randomly named. This has been done intentionally to show the degree of customization possible with the interface and instance names.


The author wishes to acknowledge the contributions of Mr. Rajesh Bose. Mr. Bose is a research scholar and an eminent author of papers in the field of Cloud and IoT computing. Mr. Bose has also written a book titled A Deep Vista of the fascinating world of Cloud Computing. He is currently writing another book in IoT which is soon to be published. Mr. Bose holds keen interest in Java programming in his quest to develop interesting models in Cloud and IoT computing.




Wednesday, 9 November 2016

Delving deeper with Java Native Access

The world of Java programming has always been exciting. Java won over the hearts and minds of programmers owing to its portability, ruggedness and, of course, object-oriented programming features.

However, many would argue that Java has played second fiddle to its more distinguished brethren - C and C++. That has been due to the fact that it does not offer seamless integration with dynamic linked library files (DLLs on Windows, and shared objects (SO files) on Linux). The path to integration has been through complex and often time-consuming process of Java Native Interface programming.

The Java Native Access library - which this post attempts to introduce - was developed and rolled out almost nine years ago, to mitigate the problems associated with linked library files integration. More specifically, this library allowed less of clutter and frees the developer to think and focus more on the problem, rather than get mired in complexities involving Java Native Interface. 

In the course of the years in which I have produced software using Java, I have always come across issues that required attention to certain programming aspects that went way beyond what could be achieved efficiently using Java. In most cases, I found the need to dig deeper into operating system internals in order to make certain features come alive. 

The Java Native Access Library has been around longer than the time I ever first came into contact with it. Indeed my first search yielded several blogs in prominent online Java journals. However, most were either abstruse or esoteric for me to understand. Even now, after several projects' worth of experience, most of the programs produced in such blogs, fine though that they are, throw up errors when put in practice. 

The Java Native Access Library itself depends upon a small dynamic link library to perform its intended functions. The very excellent Getting Started with JNA page provides all necessary details to get up and running in almost no time at all. What follows next, however, is an implementation of how a Java program can be built with the help of Java Native Access library.

We shall cut through the obvious and perhaps basic steps of setting up an IDE, Java SDK, and importing the required jna library. In the following example, I use jna-4.2.2.jar file.

We begin by creating a package within a newly created Java project, of course. We create an interface and write it thus:
package jna01;

import com.sun.jna.*;
import com.sun.jna.win32.StdCallLibrary;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author satadru
 */
public interface Kernel32 extends StdCallLibrary {

    public static class SYSTEMTIME extends Structure {

        public short wYear;
        public short wMonth;
        public short wDayOfWeek;
        public short wDay;
        public short wHour;
        public short wMinute;
        public short wSecond;
        public short wMilliSecond;

        @Override
        protected List getFieldOrder() {
            return Arrays.asList(new String[]{"wYear", "wMonth", "wDayOfWeek", "wDay", "wHour", "wMinute", "wSecond", "wMilliSecond"});
        }
    }

    void GetLocalTime(SYSTEMTIME result);

}


At this point, I would like to present a frank admission. The interface, and the class file that follows hereafter, is a copy from the very excellent article written by Jeff Friesen for Java World. 

However, there is something about this interface that sets it apart from the one that Mr. Friesen had composed over eight years ago. But before, we begin discussing the difference, the accompanying class file is presented for the impatient.


package jna01;

import com.sun.jna.*;

/**
 *
 * @author satadru
 */
public class LocalTime {

    public static void main(String[] ar) {
        Kernel32 lib = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);

        Kernel32.SYSTEMTIME tine = new Kernel32.SYSTEMTIME();

        lib.GetLocalTime(tine);

        System.out.println("Year is " + tine.wYear);
        System.out.println("Month is " + tine.wMonth);
        System.out.println("Day of Week is " + tine.wDayOfWeek);
        System.out.println("Day is " + tine.wDay);
        System.out.println("Hour is " + tine.wHour);
        System.out.println("Minute is " + tine.wMinute);
        System.out.println("Second is " + tine.wSecond);
        System.out.println("Milliseconds are " + tine.wMilliSecond);
    }

}

The instance tine has been purposely spelled that way to obviate the possibility of confusing the same with java.time.

As would be evident upon compiling and running of the project (I prefer Netbeans IDE), the results are on the expected lines. A sample output is produced below:

Year is 2016
Month is 11
Day of Week is 3
Day is 9
Hour is 17
Minute is 40
Second is 18
Milliseconds are 343

It is the interface that is most interesting part in the whole program. Mr. Friesen has produced a lucid explanation on how this functions. I would not even presume to elaborate on this, simply because there could be little value added to what he has already written. What, however, is interesting is that the interface that he wrote over eight years ago, throws up errors if produced verbatim. 

It appears that the static class [SYSTEMTIME] inside the interface needs to override the getFieldMethod() which resides in the abstract class com.sun.jna.Structure that the static class extends!

In short, the solution is to insert the overriding method:

        @Override
        protected List getFieldOrder() {
            return Arrays.asList(new String[]{"wYear", "wMonth", "wDayOfWeek", "wDay", "wHour", "wMinute", "wSecond", "wMilliSecond"});
        }

The purpose of the above method is to obtain the list of field names in the order these actually appear in the SYSTEMTIME structure of Kernel32.dll.

In fine, programming with Java Native Access is interesting. It invokes host of opportunities that are not easily replicated through pure Java coding. Through this blog post, I intended to share my initial experiences unraveling the complexities associated with native codes.












Resetting password of Amazon Kindle Paperwhite (7th Generation)

What to do to in case one forgets the password of an Amazon Kindle Paperwhite (7th Generation)? The answer is to type in  111222777  and...