Sunday, 28 July 2013

How to create a property file using Java program in Plain Text and XML format?



Creating a property file using Java program in Plain Text and XML format


java.util.Propertiespackage of Java API provides multiple utility store() methods to store properties in text or xml format.  The store() method can be used to create a plain text property file where as  storeToXML() method can be used for creating a Java property file in XML format.


Below are the examples used for the creation of plain text property file and also for the creation of XML property file.


packagecom.gaurav.loadpropertyfile;

importjava.io.FileOutputStream;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.util.Properties;

public classPropertyFileWriter {
                /**
                 * This method will populate or write properties in a plain property file
                 *
                 * @param plainPropertyFileName
                 * @throws IOException
                 */
                private static voidcreatePlainPropertyFile(String plainPropertyFileName)
                                                throws IOException {
                                System.out.println("Start Writing the PLAIN property file ");
                                Properties prop = new Properties();
                                prop.setProperty("jdbc.driverClassName", "com.mysql.jdbc.Driver");
                                prop.setProperty("jdbc.username", "root");
                                prop.setProperty("jdbc.password", "root");
                                prop.store(new FileWriter(plainPropertyFileName),
                                                                "JDBC Connection Config file");
                                System.out.println(plainPropertyFileName + " written successfully");
                                System.out.println("End of writing the PLAIN property file");

                }

                /**
                 * This method will populate or write properties in a XML property file
                 *
                 * @param xmlPropertyFileName
                 * @throws IOException
                 */
                private static voidcreateXMLPropertyFile(String xmlPropertyFileName)
                                                throws IOException {

                                System.out.println("Start writing the XML property file");
                                Properties prop = new Properties();
                                prop.setProperty("jdbc.driverClassName",
                                                                "oracle.jdbc.driver.OracleDriver");
                                prop.setProperty("jdbc.username", "system");
                                prop.setProperty("jdbc.password", "system123");
                                prop.storeToXML(new FileOutputStream(xmlPropertyFileName),
                                                                "JDBC Connection Config XML file");
                                System.out.println(xmlPropertyFileName + " written successfully");
                                System.out.println("End of writing the XML Property File");
                }

                public static void main(String[] args) throws IOException {
                                // Below two properties are the name of the created property files
                                String plainPropertyFileName = "src/jdbc.properties";
                                String xmlPropertyFileName = "src/jdbc.xml";
                                createPlainPropertyFile(plainPropertyFileName);
                                createXMLPropertyFile(xmlPropertyFileName);
                }
}

Result:-

Start Writing the PLAIN property file
src/jdbc.properties written successfully
End of writing the PLAIN property file
Start writing the XML property file
src/jdbc.xml written successfully
End of writing the XML Property File

Created jdbc.property file content:-

#JDBC Connection Configfile
#Sun Jul 28 13:31:56 IST 2013
jdbc.username=root
jdbc.password=root
jdbc.driverClassName=com.mysql.jdbc.Driver

Created jdbc.xml file content:-

<?xml version="1.0"encoding="UTF-8" standalone="no"?>
<!DOCTYPE propertiesSYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>JDBC Connection ConfigXML file</comment>
<entry key="jdbc.username">system</entry>
<entry key="jdbc.password">system123</entry>
<entry key="jdbc.driverClassName">oracle.jdbc.driver.OracleDriver</entry>
</properties>



Monday, 22 July 2013

What is RSA algorithm and how to use RSA for encryption and decryption using java?



About RSA algorithm

The RSA algorithm was publicly described in 1977 by Ron Rivest, Adi Shamir, and Leonard Adleman. But the algorithm was released to the public domain by RSA Securityon September 6, 2000.

Key generation Using RSA algorithm

RSA involves a public key and a private key. The public key can be shared by everyone and is used for encrypting messages. Messages encrypted with the public key can only be decrypted in a reasonable amount of time using the private key. The keys for the RSA algorithm are generated the following way:


RSA Algorithm Example 

           1. Choose two distinct prime numbers p and q. For security purposes, the integers p and q should be chosen at random, and should be of similar bit-length.

Choose p = 3 and q = 11
      
 2. Compute n = pq. n is used as the modulus for both the public and private keys. Its length, usually expressed in bits, is the key length.

Compute n = p * q = 3 * 11 = 33
       
 3. Compute φ(n) = φ(p)φ(q) = (p − 1)(q − 1), where φ is Euler's totient function.

Compute φ(n) = (p - 1) * (q - 1) = 2 * 10 = 20
       
 4. Choose an integer e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1; i.e. e and φ(n) are coprime.
  • e is released as the public key exponent.
  • e having a short bit-length and small Hamming weight results in more efficient encryption – most commonly 216 + 1 = 65,537. However, much smaller values of e (such as 3) have been shown to be less secure in some settings.
Choose e such that 1 < e < φ(n) and e and n are coprime. Let e = 7
  1. Determine d as d−1 ≡ e (mod φ(n)), i.e., d is the multiplicative inverse of e (modulo φ(n)).  This is more clearly stated as solve for d given d⋅e≡ 1 (mod φ(n)) 
  2.    This is often computed using the extended Euclidean algorithm.
         d is kept as the private key exponent.

7. Compute a value for d such that (d * e) % φ(n) = 1. One solution is d = 3 [(3 * 7) % 20 = 1]

Public key is (e, n) => (7, 33)

Private key is (d, n) => (3, 33)

The encryption of m = 2 is c = 27 % 33 = 29

The decryption of c = 29 is m = 293 % 33 = 2


Another working example to clear the RSA algorithm

Here is an example of RSA encryption and decryption.
  1. Choose two distinct prime numbers, such as
p=61 and q=53.
  1. Compute n = pq giving
n=61*53 = 3233.
  1. Compute the totient of the product as φ(n) = (p − 1)(q − 1) giving

  1. Choose any number 1 < e < 3120 that is coprime to 3120. Choosing a prime number for e leaves us only to check that e is not a divisor of 3120.
Let

  1. Compute d, the modular multiplicative inverse of e (mod φ(n)) yielding 
       


The public key is (n = 3233, e = 17). For a padded plaintextmessage m, the encryption function is
     


The private key is (n= 3233, d = 2753). For an encrypted ciphertextc, the decryption function is c2753(mod 3233).
 


For instance, in order to encrypt m= 65, we calculate
  


To decrypt c = 2790, we calculate



Java example to use RSA algorithm to encrypt and decrypt secure information.

Jar files needed to execute the below program

1. FlexiCoreProvider-1.7p6.signed.jar
      2. CoDec-build21-jdk13.jar


AsymmetricEncryptionSampleUsingRSA.java

package com.gaurav.java.security;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyPair;
importjava.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;

import javax.crypto.Cipher;
importjavax.crypto.CipherInputStream;
importjavax.crypto.CipherOutputStream;

importde.flexiprovider.core.FlexiCoreProvider;

public classAsymmetricEncryptionSampleUsingRSA {

      publicstatic void main(String[] args) throws Exception {

            Security.addProvider(newFlexiCoreProvider());

            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "FlexiCore");
            Cipher cipher = Cipher.getInstance("RSA", "FlexiCore");

            kpg.initialize(1024);
            KeyPair keyPair = kpg.generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();

            /** This Code can be used to encrypt Data */

            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            String secureInformationFile = "C://secureInformation.txt";
            String ciphertextFile = "encryptedTextUsingRSA.txt";

            FileInputStream fileInputStream = new FileInputStream(
                        secureInformationFile);
            FileOutputStream fileOutputStream = new FileOutputStream(ciphertextFile);
            CipherOutputStream cipherOutputStream = new CipherOutputStream(
                        fileOutputStream, cipher);

            byte[] dataBlock = new byte[32];
            intdataItems;
            while((dataItems = fileInputStream.read(dataBlock)) != -1) {
                  cipherOutputStream.write(dataBlock, 0, dataItems);
            }
            System.out.println("File Written successfully in encryption mode");
            cipherOutputStream.close();

            /** This Code can be used to decrypt data */

            String cleartextAgainFile = "decryptedTextUsingRSA.txt";

            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            fileInputStream = new FileInputStream(ciphertextFile);
            CipherInputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher);
            fileOutputStream = new FileOutputStream(cleartextAgainFile);

            while((dataItems = cipherInputStream.read(dataBlock)) != -1) {
                  fileOutputStream.write(dataBlock, 0, dataItems);
            }
            System.out.println("File Written successfully in decryption mode");
            fileOutputStream.close();
      }

}


Content of secureInformation.txt

SecurePasswordIndia2013

Note: - encryptedTextUsingRSA.txt and decryptedTextUsingRSA.txt, these two file will be generated by code in the classpath location. encryptedTextUsingRSA.txt file will contain converted encrypted message corresponding to SecurePasswordIndia2013 and decryptedTextUsingRSA.txt will contain the same decrypted message value as SecurePasswordIndia2013.
 
Reference taken from http://en.wikipedia.org