Wednesday 26 November 2014

Https client and server

Post the cryptograhy session (generation of asymmetric keys), I had to use my keys to communicate between a simple https client and its corresponding server. Here's how they look like:

A simple https server:

public class MyHttpsServer {
int httpsPort = 443;
String httpsPath = "/certificate";
final EventLoopGroup parentGroup = new NioEventLoopGroup();
final EventLoopGroup childGroup = new NioEventLoopGroup();
protected final LinkedBlockingQueue<ByteBuf> incomingMsgQueue = new LinkedBlockingQueue<>();
private Channel channel;

public static void main(String[] args) throws InterruptedException {
MyHttpsServer mhs = new MyHttpsServer();
mhs.createASimpleHttpsServer();
}

public void createASimpleHttpsServer(){
try {
// setup the socket address
InetSocketAddress address = new InetSocketAddress(
InetAddress.getLocalHost(), 443);

// initialise the HTTPS server
HttpServer httpsServer = HttpsServer.create(address, 0);
SSLContext sslContext = SSLContext.getInstance("SSL");

// initialise the keystore
char[] password = "dummypassword".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream("keysdir/my_keystore.jks");
ks.load(fis, password);

// setup the key manager factory
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password);

// setup the trust manager factory
TrustManagerFactory tmf = TrustManagerFactory
.getInstance("SunX509");
tmf.init(ks);

// setup the HTTPS context and parameters
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
((HttpsServer) httpsServer).setHttpsConfigurator(new HttpsConfigurator(sslContext) {
public void configure(HttpsParameters params) {
try {
// initialise the SSL context
SSLContext c = SSLContext.getDefault();
SSLEngine engine = c.createSSLEngine();
params.setNeedClientAuth(false);
params.setCipherSuites(engine.getEnabledCipherSuites());
params.setProtocols(engine.getEnabledProtocols());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});


httpsServer.start();
MyHttpsHandler myHttpsHandler = new MyHttpsHandler();
httpsServer.createContext(httpsPath, myHttpsHandler);
httpsServer.createContext("/key", myHttpsHandler);


System.out.println("https server is listening on " + httpsServer.getAddress());
} catch (Exception ex) {
ex.printStackTrace();
}
      }
}


Https handler (helper class):

public class MyHttpsHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
try {
if (exchange.getRequestMethod().equals("GET")) {
System.out.println("Processing the incoming GET request...." + exchange.getRequestURI().getPath());
byte[] response;
try {
response = getResponse();
exchange.sendResponseHeaders(200, response.length);
exchange.getResponseBody().write(response);
exchange.getResponseBody().close();

} catch (KeyStoreException | NoSuchAlgorithmException
| CertificateException e) {
e.printStackTrace();
} catch (UnrecoverableEntryException e) {
e.printStackTrace();
}
System.out.println("Sent response sucessfully");
} else {
System.out.println("Requested http method not supported");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

private byte[] getResponse() throws FileNotFoundException, IOException,
KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
File privateKeyFile = new File("keysdir/my_keystore.jks");
FileInputStream fIn = new FileInputStream(privateKeyFile);
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(fIn, "dummypassword".toCharArray());
System.out.println("Successfully loaded the keystore");

Enumeration<String> aliases;
aliases = keyStore.aliases();
String alias = aliases.nextElement();
KeyStore.PrivateKeyEntry keyEnt = (KeyStore.PrivateKeyEntry) keyStore
.getEntry(
alias,
new KeyStore.PasswordProtection("dummypassword"
.toCharArray()));
PrivateKey privateKey = keyEnt.getPrivateKey();
byte[] response = privateKey.getEncoded();
return new Base64().encode(response);
}
}

Tuesday 1 July 2014

Tech talk...Cryptography or Encryption [Using keys]

Previous post covered how to generate keys and keystores.
This post shows how to load the private key from keystore, public key from truststore and then use them for data decryption/encryption respectively:

Load keystore: (keystorePass = password of the keystore)

KeyStore keyStore= KeyStore.getInstance("JKS");
FileInputStream fin1 = new FileInputStream("D:\\MySecurityKeys\MyKeyStore.jks");
keyStore.load(fin1, keystorePass.toCharArray());

Load the truststore: (truststorePass = password of the truststore)

KeyStore trustStore= KeyStore.getInstance("JKS");
FileInputStream fin2= new FileInputStream("D:\\MySecurityKeys\MyTrustStore.jks");
trustStore.load(fin2, truststorePass.toCharArray());

Load private key from the keystore:

Enumeration<String> aliases = keyStore.aliases();
String alias = aliases.nextElement();
KeyStore.PrivateKeyEntry keyEnt = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
                    new KeyStore.PasswordProtection(keystorePass.toCharArray()));
PrivateKey privateKey = keyEnt.getPrivateKey();

Load public key from the truststore:

aliases = trustStore.aliases();
alias = aliases.nextElement();
KeyStore.TrustedCertificateEntry keyEnt = (KeyStore.TrustedCertificateEntry) trustStore.getEntry(alias, null);
PublicKey publicKey = keyEnt.getTrustedCertificate().getPublicKey();

Initializing ciphers:

//the public and private keys use encryption and decryption ciphers respectively for encrypting //and decrypting the data. So, first, the ciphers need to be initiatized:
//Initializing the encryption cipher:
Cipher encryptionCipher = Cipher.getInstance("RSA");
                        encryptionCipher.init(Cipher.ENCRYPT_MODE, publicKey);/Initializing the decryption cipher:
Cipher  decryptionCipher = Cipher.getInstance("RSA");
                        decryptionCipher.init(Cipher.ENCRYPT_MODE, privateKey);

Encryption of data:


    public byte[] encryptData(byte[] input)                throws IllegalBlockSizeException,BadPaddingException   {
        byte[] encryptedData = null;
        encryptedData = encryptionCipher.doFinal(input);
        return new Base64().encode(encryptedData);
    }

Decryption of data:


    public byte[] decryptData(byte[] inputData) throws IllegalBlockSizeException , BadPaddingException {
        byte[] decryptedData = null;
        byte[] inputBytes = new Base64().decode(inputData);
        decryptedData = decryptionCipher.doFinal(inputBytes);
        return decryptedData;
    }

Note:The Base64 encoding decoding is done to preserve the context of data when data is converted from byte to string and string to byte and encryption/decryption is done over the data. For example, if a String "Hello" were to be encrypted using the above method, the caller would say String encryptedData = new String( encryptData("Hello".getBytes()) and when decrypting back the data, he would say String decrytedData = new String(decryptData(encryptedData.getBytes()). Here, encryptedData and decryptedData are two new Strings, the final value expected on decrypting the data is "Hello". This might not be the case if proper encoding is not used. So, to preserve the value of actual data through this process, a base 64 encoding has been used here along with the encryption.

Tech talk...Cryptography or Encryption [Generating keys]

The following code snippets in java show how to generate a private and public key pair for asymmetric cryptography and how to add them to the keystore and truststore respectively:

An enum to help differentiate public and private keys:

public enum KEY_TYPE {
PUBLIC, PRIVATE
}


 Code snippet to generate the public and private keys:


  KeyPairGenerator keyPairGenerator = KeyPairGenerator
.getInstance("RSA");
  KeyPair keyPair = keyPairGenerator.generateKeyPair();
  KeyManager keyGenerator = new KeyManager();

  // generate a public-private key pair
  PublicKey publicKey = (PublicKey) keyGenerator.generateAndStoreKey(
"MyPublicKey", KEY_TYPE.PUBLIC, keyPair);
  PrivateKey privateKey = (PrivateKey) keyGenerator.generateAndStoreKey(
"MyPrivateKey", KEY_TYPE.PRIVATE, keyPair);


Storing the keys into files:

function generateAndStoreKey:
This function would store the keys into files:

private Key generateAndStoreKey(String keyName, KEY_TYPE keyType,
KeyPair keyPair) throws IOException {
Key key = null;
switch (keyType) {
case PUBLIC:
key = keyPair.getPublic();
break;
case PRIVATE:
key = keyPair.getPrivate();
break;
}
byte[] keyBytes = key.getEncoded();
File keyFile = new File("D:\\MySecurityKeys\" + keyName);
FileOutputStream fos = new FileOutputStream(keyFile);
fos.write(keyBytes);
fos.flush();
fos.close();

return key;
}


Adding private key to keystore:

A private key, once generated, can be added to the keystore. For this, first the keystore needs to be loaded into memory. Below is the code snippet for loading a keystore file, given its location:


FileInputStream fIn = new FileInputStream("D:\\MySecurityKeys\MyKeyStore.jks");
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(fIn, KEYSTORE_PASSWORD.toCharArray());

Once the keystore is loaded, the private key can be added into it as follows:


//Convert the private key to byte array, if the key is stored in the form of file, then 
//read the file and convert it to byte array (as is the case from our private key generation code //above). If it is available in any other format, like a string, then also, the string should be //converted to byte array.
File privateKeyFile = new File("D:\\MySecurityKeys\MyPrivtekey");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
privateKeyFile));
byte[] privKeyBytes = new byte[(int) privateKeyFile.length()];
bis.read(privKeyBytes);
bis.close();

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory
.generatePrivate(new PKCS8EncodedKeySpec(privKeyBytes));

                //generate a certificate chain out of the private key  
File certFile = new File("D:\\MySecurityKeys\MyCertificateFile");
FileInputStream fin = new FileInputStream(certFile);
CertificateFactory factory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
Certificate generateCertificate = factory.generateCertificate(fin);
Certificate[] chain = new Certificate[1];
chain[0] = generateCertificate;
                
                //add the entry to the keystore
keyStore.setKeyEntry("MyPrivateKey", privateKey,
PRIVATE_KEY_PASSWORD.toCharArray(), chain);
                //store the new keystore to the file system
keyStore.store(new FileOutputStream(new File("D:\\MySecurityKeys\MyKeyStore.jks")), KEYSTORE_PASSWORD.toCharArray());
System.out.println("Added private key to keystore");
}

Adding public key to truststore:

A public key can be added to the truststore as follows:
A public key needs to be embedded inside a certificate to be stored in truststore. Following code snippet shows how to do it:

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

X509Certificate[] serverChain = new X509Certificate[1];
X509V3CertificateGenerator serverCertGen = new X509V3CertificateGenerator();
X500Principal serverSubjectName = new X500Principal("CN=neha verma");
                String RANDOM = "123456789";
serverCertGen.setSerialNumber(new BigInteger(RANDOM));

serverCertGen.setIssuerDN(serverSubjectName);
serverCertGen.setNotBefore(new Date());
serverCertGen.setNotAfter(new Date());
serverCertGen.setSubjectDN(serverSubjectName);
serverCertGen.setPublicKey(publicKey);
                String CERTIFICATE_SIGNATURE_ALGO = "MD5WithRSA";
serverCertGen.setSignatureAlgorithm(CERTIFICATE_SIGNATURE_ALGO);
serverCertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
new SubjectKeyIdentifierStructure(publicKey));
serverChain[0] = serverCertGen
.generateX509Certificate(privateKey, "BC"); // note: private key
// of CA
byte[] encodedCert = serverChain[0].getEncoded();
File certFile = new File("D:\\MySecurityKeys\MyCertificate.cert");
FileOutputStream out = new FileOutputStream(certFile);
out.write(encodedCert);
out.flush();
out.close();
}

The certificate file can be added to the truststore from command line as follows:
C:\ProgramFiles\Java\jdk1.7.0_40\bin>keytool -import -file D:\\MySecurityKeys\MyCertificate.cert -alias MyCertificate
  -keystore MyTrustStore

To see how to load and use the public key and private key generated above, you can refer to next post.

Tech talk...Cryptography or Encryption [Generating & Using Keystore/Truststore]

Keystore is used to hold the private keys.
In java, keystore can be generated from the command prompt.
This is the oracle documentation for doing the same:
http://docs.oracle.com/cd/E19509-01/820-3503/ggfen/index.html

You need to go to the jre bin folder . Inside that the executable 'keytool' should be present. this is used to generate the keystore.
Here's the command to generate the keystore

keytool -keystore <keystore name> -genkey -alias <keystore-alias>

example:

keytool -keystore MyKeyStore -genkey -alias MyKeyStore

Once you enter the above command, you would be prompted for certain inputs, keep providing the inputs and finally the keystore file would be generated with a .jks extension in the bin folder.
From here, you can copy the keystore file anywhere.

An example of what all would be entered once the above command is entered:


Enter keystore password: javacaps
What is your first and last name?
[Unknown]: neha neha
What is the name of your organizational unit?
[Unknown]: Development
what is the name of your organization?
[Unknown]: self
What is the name of your City or Locality?
[Unknown]: Bangalore
What is the name of your State or Province?
[Unknown]: Karnataka
What is the two-letter country code for this unit?
[Unknown]: India
Is<CN=development.self.com, OU=Development, O=self, L=Bangalore, ST=Karnataka, 
C=India> correct?
[no]: yes

Enter key password for <MyKeyStore>
    (RETURN if same as keystore password):

Once the keystore is generated, either keys can be added to it using command prompt or using java program.To add keys using command prompt, you can further refer to the oracle documentation here: http://docs.oracle.com/cd/E19509-01/820-3503/ggfen/index.html I used java program to generate and add private keys to the keystore. Refer to the next post for seeing example of how to generate Asymmetric key pairs and add them to the keystore/truststore using java.


The key store that holds the public key is generally called a truststore. A truststore can be generated in the same way as demonstrated above. For example:

keytool -keystore MyTrustStore -genkey -alias MyTrustStore

Monday 30 June 2014

Tech Talk.....Cryptography or Encryption [Introduction]

Recently, I was working on securing the communication between different components of my product using cryptography or encryption (as it was called in the old world), I explored and learnt various concepts related to cryptography which proved to be very helpful. However, they were scattered around a lot and I had to filter out lots of stuff from here and there. I would like to summarize the learning that I gathered, over a series of small posts here, that would help someone like me in the future save time and effort and keep the learning crisp and fast.

Cryptography is a way to secure communication between two parties from any third party. In the world of computers, there are two different kind of cryptography techniques that are mostly popular : Public key cryptography (also known as Asymmetric cryptography) and Symmetric cryptography.

Public key cryptography:
This cryptography or encryption technique uses a pair of keys for encryption - decryption, one being a private key and another being a public key.Private key is used for decryption of data and public key is used for encryption of data. This mode of encryption is famous in the client - server world where the server generates a pair of keys - a public key and a private key. The private key is retained with the server , while the public key is made available to any client that wants to communicate to the server. The client encrypts its data with the public key before sending it over to the server, when the server gets the data from client, it uses the private key to decrypt the data. If any third party gets hold of the encrypted data, it can't decrypt the data because it won't have the private key with it.

In the next post, I will show how to generate a public-private key pair, how to store it and how to use it.(In java)


Friday 27 June 2014

Innocence

There are certain incidents of purity, innocence and selflessness that leave their imprints on our heart forever. Here I am narrating one such incidence that had touched me deep down and made its imprint on my heart forever.
I had these little cousins - an elder sister and a younger btrother - just an years difference between the two.  I had a piece of sweet with me which I had to offer them but unfortunately when I broke it the two pieces came out to be unequal. The two of them came rushing to me for sweet and I couldn't think of any fairer way to distribute the pieces than to spread my palm in front of them and let them make the decision of who wanted which piece. The sister reached out in a swift movement to grab the larger piece. The brother was just watching, the expression on his face clearly showing his disappointment of loosing the chance of grabbing the larger piece. When the sister was about to take the larger piece, she halted for a moment, saw her brother's face and then to my surprise she silently went ahead and grabbed the smaller piece, her eyes fixed on the disappointed face of her brother! I was so touched by the purity and selflessness of her gesture.

Thursday 27 March 2014

Wonder woman

There was this girl in college, with backlog papers in final year, obviously her career aspects didn't look very bright. On top of that she was in a relationship which both their parents disapproved. Anyways, we all graduated, joined our jobs, got busy in our lives and life moved on. Until one day when i was surprised to see her in the basement of our apartment and even more surprised to learn that she had been living here for quiet sometime. She invited me over to her place and in a few days time I arranged to visit her. Little did I know how many more surprises were there for me in store as i would come to learn more about the happenings in her life. As a starter I was impressed to learn that she had married the love of her life, and that too with the blessings of both their families in spite of all the obstacles, oppositions and tension they hadn't given up and finally got together. Then I learnt that she was working in a reputed iT firm, and I could sense the effort she would have put to reach here in her career given the weak academics. And unlike many other girls around me who had good academic records and degrees but were still not interested in pursuing a career, this woman seemed pretty serious and sincere about her job. Double imprsssed!! Next I couldn't stop gazing around her house, sorry, home. It was so nicely decorated and managed, so cute, warm, charming and inviting with the love and spirit of its owners reflecting in it. I couldn't stop wondering how many so called successful women around me would have scored more than her in this aspect - hardly any.
Needless to say, my opinion about her personality, her strength and weaknesses,  completely changed. I was impressed by the way she had pulled things up and managed to balance together all aspects of life. 
Today she is the mother of a small baby, still smartly striking the balance between her home, job and the infant with the help of her husband and just one domestic helper. I wish her success in whatever she does in life.
When I feel the work life pressure, when I feel lazy in keeping my commitments towards my home, then I think of her and it energises me.
Hats off toyou girl.

Sunday 23 March 2014

Grandmaa.....

Imagine you do a schooling only till class 2 . Then you get married at a mere age of 16 and have a child the very next year. You then become a mother every couple of years for the next 12-14 years, some of your children survive, some are still-born and a couple of others are consumed by epidemics. Your husband has hardly sufficient money to meet the monthly expenses, yet you have to manage the upbringing of  all your children to the best you can, and then you get them married one by one and have grandchildren, and you take care of each one of them, at times even better than their moms can! As if your life has just one purpose - to serve your children and grandchildren. But, things don't end here. There are these clashes and fictions of joint family that happen, the children you raised with your sweat and blood separate from one another, the grandchildren grow up and go their own ways, you grow older and older, enduring all this, taking into your lap whatever life has to offer, without complaining, without leaving the zeal to live and to make the life of people around you better through your care and love….how does it feel imagining yourself in this kind of a situation? Melodramatic? Out of the world? It does feel like that to me. If I had such a life, either I would have abandoned it or  I would have gone insane.

Sadly, its not something over-dramatic or imagined or exaggerated. It’s the life bestowed upon a Grandma, it’s the life she lead for the past 80+ years. But I am not writing it out here so that you have pity for her, I am writing It out to justify why she is one of the greatest inspirations in my life, why she deserves a salutation from all the women out there, I am writing this to bring to fore the beauty of her great personality and that of numerous other Grannies like her.

A life which me and you can't even think of, which we would loath, which would drive us mad and crazy, to lead such a life, and not just lead, to maintain your integrity throughout your life - is something more than commendable. That's what this grandma did. Never once I remember her loosing her integrity through all the ups and downs of life, never did I see her compromise on her values, however hard it was for her.

If she had a single penny with her, she would make sure to spend it equally among her children, if she had a single piece of bread, she would divide it equally for them. She had no grudge against any of them, even if they ignored her needs at times. She would feed the whole family and eat at last. Every time any one of her children needed her support or for the matter of fact, anyone's support, she would be there standing besides them, even without they asking for it explicitly. I remember when her daughter-in-law was ill and they had to take her to another city for treatment, none of the brothers or sisters had come forth to go with them, but grandma was there for her son and daughter in law. When a grandchild was alone at home, she would be there to take care of him or her. When they went to study far from home, the day they would come home, where ever she would be,even when old and unable to walk so much, still she would come over to meet them. When all her sons were settled except the youngest, she lived with him, taking care of him- saying to other children - "my youngest son needs me the most, you all are settled, until  he is settled, my prime duty is to take care of him". She used to do all the household work and then attend all the society events as well.

When a cat had abandoned its kitten , a newborn just a few days old, in the backyard and the children were trying to feed it in vein, she came with a box filled with cotton, placed the kitten into it and then fed it through a cotton ball, squeezing milk into its mouth. The kitten survived and 3 days later its mother took it with her.

I had seen silent tears rolling down her cheek the day her joint family had broken, but she had not uttered a word. The very next day she was her usual self , going through her daily chores, she had accepted the big blow in her life with such calm. 

If I continue writing about such incidences where her composed personality, her love her compassion for her family touched me deep down..its going to be the longest blog ever written. So, I don't want to squeeze in all the details here...let some reside in the core of my heart … :) 

When I face little problems in life, when the loved ones around me fail to meet my expectations on petty matters, I feel frustrated, sometimes furious. Then at times I think about this Grandma, and it gives me so much strength. I don’t need to look forward to any special Saint or holy person to get the inspiration on spiritual aspects of life, on selflessness and true love, when I have her to look up to. If she can do it, she can be so loving, caring, composed and giving all through the hardships that life endured upon her, each one of us can be … and the world would be so much more beautiful if each one of us could learn something from a personality like her.

Monday 17 March 2014

Tech Talk... Creating a temporary file using java

Template:

File tempFile = File.createTempFile(<temp-file-name>, <temp-file-extension>);

Using the above template would create a file with name <temp-file-name> and extension <temp-file-extension>.

Code sample:

File tempFile = File.createTempFile("mytempfile", ".txt");

Where such code gets useful:

Mostly, I find it very useful when writing unit test cases in java which require to test scenarios where a file creation is required, because, this way, I don't have have to worry about which OS I am on, what location should I choose to create a temporary file etc. In the setup method in my unit test, I can create the file and in the teardown method i can call delete() on this file to ensure that the file gets created before I run my testcase and gets deleted after the testcase is complete. 

Monday 10 March 2014

Inspirations - cheers to all the women around me…

I truly feel blessed to have so many women around me - friends, relatives, elders and youngsters, colleagues - whom I look up to and seek inspiration from. Then there are distant acquaintances and sometimes even some strangers whom I got to meet in hotels, in lift, on the roads, in the shops, on bus-stops, in the buses  and everywhere else -  for very brief span of time, yet in that small span of time they left their imprints on my mind in one way or the other - so that I remember them till today. I want to dedicate some of my posts to all those women in and around...who inspire me in everyday life in various ways.  I would like to say to those women - you are all so filled with qualities, you all have something or the other that every other person can learn from you… kudos to you for being you :). God bless you all….

I would love to dedicate some of the posts that follow to some of the shining, inspiring, guiding examples from women around me. A recollection of these always gives me strength to keep moving in tough times and fills me with positive energy in daily life....

Coming back soon with the inspirational stories....

Friday 28 February 2014

Tech talk...creating a symlink

Almost everyone knows that a symlink is a symbolic link (in simplistic words, a shortcut link) to a file or a directory and most of you would be knowing how to create a symlink on one of those linux systems. So, the question arises, why am I writing a post here on how to create a symlink, well, for some people as basic (i wont like to call naive) as me, who went through so many sites to achieve the same..somehow it was a simple line and a simple command on all those sites but yet there were contradictions due to which after 4-5 trials I was able to get the first link created properly. So, I was compelled to put it out to the world, to make a simple symlink creation even simpler. Here you go...

Create a symlink:

Command format:


ln -s [folder-or-file-for-which-symlink-is-to-be-created] [symlink-name]

Command example:


ln -s rootFolder/childFolder/folderWhoseSymlinkIsRequired symlinkToFolder
In the above case, the symlink will be created in the current directory, where the rootFolder lies.

Wednesday 22 January 2014

Tech Talk...Byte array and String conversions in Java

How to convert a byte array to a String in Java:
To convert a byte array to a string, create a new String using the byte array as an input argument to the String constructor. Something like this:

byte[] bytes = initializeByteArray();
String str = new String(bytes);


To convert a string to a byte array, you can use the String API getBytes() :

String str = "Hello"
byte[] bytes = str.getBytes();