Asymmetric Cryptography in Java

              * {@link PrivateKey}. In this
Security plays a significant role in our day to day life.method you have to pass
So far software applications are concerned, security             * the file name of the
of data is required for authentication and for severalPrivate.key file.
validations. Normally while developing the applications,             * @param filename of type
we use the concept of cryptography for passwordString indicating the
encryption and decryption. Some applications require             * file name.
more security, so they go for high end security system             * @return the object of type
like trusted security certificates. The security mainly{@link PrivateKey}
focuses on the integrity of the data at the several             * @throws Exception
ends.             */
Technicalities For data security Java Cryptography            public PrivateKey getPrivateKey(
provides a suitable framework to implement severalString filename ) throws Exception
kinds of cryptography. However there are basically            {
two types of cryptography. Once is Symmetric                        PrivateKey
Cryptography and Asymmetric Cryptography. WhenprivateKey = null;
both the ends communicate the secured data with a                        try
common key for encryption and decryption, it is called                        {
the Symmetric Cryptography. In this case a shared     byte[] keydata = getKeyData(filename);
key is used by both the parties to encrypt and decrypt     PKCS8EncodedKeySpec encodedPrivateKey
the data. However there is a problem relating to= new PKCS8EncodedKeySpec(keydata);
exchange of key for symmetric cryptography. To     privateKey =
overcome this problem java provides anotherkeyFactory.generatePrivate(encodedPrivateKey);
approach for the cryptography called Asymmetric                        }
Cryptography. In case of Asymmetric cryptography,                        catch(
there will be two keys unlike one key in case ofException e )
symmetric cryptography. One key is called Private key                        {
and other is called Public key. These two keys are     e.printStackTrace();
generated together and can be used for encryption                        }
and decryption. In this case the Public key is used by                        return
anyone who wishes to communicate securely with theprivateKey;
owner of the Private key. The Private key is used by            }
the main owner and the owner gives the Public key so            /**This method is used to return
that they can decrypt the data. In this article I will givethe object of type
you the example on Asymmetric cryptography. You             * {@link PublicKey}. In this
can find more tutorials and concept on Sun’smethod you have to pass
JCE(Java Cryptography Extension). In my next article, I             * the file name of the Public.key
will provide you the example on Symmetricfile.
cryptography.             * @param filename of type
Complete Example This example is only meant forString indicating the
learning and not for any specific use. You can take the             * file name.
piece of code to test in your system to learn the             * @return the object of type
above concept.{@link PublicKey}
The following class is used to create the Public key             * @throws Exception
and Private key. This class contains generic methods             */
to generate the Public and Private key. If you run the            public PublicKey getPublicKey(
testharness class, you will find the two files calledString filename ) throws Exception
“Public.key” and “Private.key”. Please go            {
through the java docs mentioned in the methods.                        PublicKey
Class Name : - KeyCreator.javapackagepublicKey = null;
com.dds.security;                        try
 import java.io.FileOutputStream;import                        {
java.io.IOException;import java.security.KeyPair;import     byte[] keydata = getKeyData(filename);
java.security.KeyPairGenerator;import     X509EncodedKeySpec encodedPublicKey =
java.security.PrivateKey;import java.security.PublicKey;new X509EncodedKeySpec(keydata);
      publicKey =
/**This class is used to generate the Private and PublickeyFactory.generatePublic(encodedPublicKey);
key file.                        }
 * The Public.key file and Private.key file will be                        catch(
generated in theException e )
 * current directory.                        {
 * @author Debadatta Mishra(PIKU)     e.printStackTrace();
 *                        }
 */public class KeyCreator                        return
{publicKey;
            /**            }
             * Object of type {@link}
PublicKey}The following class is a utility class which is used to
             */encrypt and decrypt the data.
            private PublicKey publicKey = null;ClassName :- SecurityUtil.javapackage
            /**com.dds.security;
             * Object of type {@link import java.security.PrivateKey;import
PrivateKey}java.security.PublicKey;
             */ import javax.crypto.Cipher;
            private PrivateKey privateKey = 
null;/**This is a utility class to provide
            * encryption and decryption based upon
            /**Default constructor. * the key. The key can be your either
             * Here KeyPair object is * Public or Private .
initialized and * @author Debadatta Mishra(PIKU)
             * thereby public key and private *
key objects */public class SecurityUtil
             * are created.{
             * @throws Exception            /**
             */             * Object of type {@link Cipher}
            public KeyCreator() throws             */
Exception            private static Cipher cipher = null;
            {            /*
                        super();             * The following static is used to
                        /*             * initialize the Cipher object
                         * The             */
following line is used to            static
                         * generate            {
the Public and Private                        try
                         * key.                        {
                         */     cipher = Cipher.getInstance("RSA");
                        KeyPair                        }
keyPair = KeyPairGenerator                        catch(
                       Exception e )
.getInstance("RSA")                        {
                            e.printStackTrace();
.generateKeyPair();                        }
                        publicKey =            }
keyPair.getPublic();            /**Method used to encrypt the
                        privateKeystring and return as bytes.
= keyPair.getPrivate();             * Here the input parameter will
            }be your Private key.
                        * You have to encrypt the string
            /**Method to return the {@linkusing your private
PublicKey}             * key at your end.
             * @return the {@link PublicKey}             * @param messsageBytes , it is
             */the bytes from the
            public PublicKey getPublicKey() {             * string to encrypt
                        return             * @param privateKey of type
publicKey;{@link PrivateKey}
            }             * @return encrypted bytes
              * @throws Exception
            /**Method to return the {@link             */
PrivateKey}            public static byte[]
             * @return the {@linkgetEncryptedBytes( byte[] messsageBytes ,
PrivateKey}PrivateKey privateKey) throws Exception
             */            {
            public PrivateKey getPrivateKey()                        byte[]
{encryptedBytes = null;
                        return                       
privateKey;cipher.init(Cipher.ENCRYPT_MODE , privateKey );
            }                       
           encryptedBytes = cipher.doFinal(messsageBytes);
            /**Method used to write the Public                        return
or PrivateencryptedBytes;
             * key file.            }
             * @param filename of type            /**Method used to decrypt the
String indicatingstring and return as bytes.
             * the name of Public or Private             * Here the input parameter will
keybe your Public key.
             * @param contents of the key             * You have to decrypt the string
             */using your Public
            public void writeKey(String             * key at the destination end.
filename, byte[] contents)             * @param messsageBytes , it is
            {the bytes from the
        try             * string to encrypt
        {             * @param publicKey of type
            FileOutputStream fos = new{@link PublicKey}
FileOutputStream(filename);             * @return decrypted bytes
            fos.write(contents);             * @throws Exception
            fos.flush();             */
            fos.close();            public static byte[]
        }getDecryptedBytes( byte[] messsageBytes ,
        catch (IOException e)PublicKey publicKey)throws Exception
        {            {
            e.printStackTrace();                        byte[]
        }decryptedBytes = null;
    }                       
}cipher.init(Cipher.DECRYPT_MODE , publicKey );
                        
The following class is used to read thedecryptedBytes = cipher.doFinal( messsageBytes );
“Public.key” and “Private.key” generated                        return
by the above program. If you are the owner you candecryptedBytes;
have the “Private.key” file based upon which            }
you have to encrypt the data and give your}
“Public.key” file to other end who wants to 
decrypt the data. In this following class, you can readThe following is test harness class to test the
both the “Public.key” and “Private.key”functionality of the above program. Please go through
files.the comments and java docs of the above and below
Class Name:- KeyReader.javapackageprograms.
com.dds.security;Class Name :- SecurityTestHarness.javapackage
 import java.io.ByteArrayOutputStream;importcom.security.testharness;
java.io.FileInputStream;import java.io.IOException;import import java.security.PrivateKey;import
java.security.KeyFactory;importjava.security.PublicKey;
java.security.PrivateKey;import import com.dds.security.KeyCreator;import
java.security.PublicKey;importcom.dds.security.KeyReader;import
java.security.spec.PKCS8EncodedKeySpec;importcom.dds.security.SecurityUtil;
java.security.spec.X509EncodedKeySpec; 
 /**This is a test harness class used to
/** * encrypt and decrypt the string based
 * This class is used to read the Private and Public * upon the Public and Private key.
key * This class also helps to test how
 * files generated using the Java's Asysmmetric * Public and Private key can be created.
Security * @author Debadatta Mishra(PIKU)
 * system. *
 * @author Debadatta Mishra(PIKU) */public class SecurityTestHarness
 *{
 */public class KeyReader            public static void main(String[]
{args)
            /**            {
             * Object of type {@link                        try
KeyFactory}                        {
             */     /*
            private KeyFactory keyFactory =      * The following lines will generate the
null;      * PublicKey and PrivateKey files.
            /**      */
             * Default constructor to initialize     KeyCreator keyCreator = new KeyCreator();
the     PublicKey publicKey =
             * keyFactory.keyCreator.getPublicKey();
             */     PrivateKey privateKey =
            public KeyReader()keyCreator.getPrivateKey();
            {     /*
                        super();      * Generate two files named Public.key and
                        tryPrivate.key
                        {      */
     keyFactory = KeyFactory.getInstance("RSA");     keyCreator.writeKey("Public.key",
                        }publicKey.getEncoded());
                        catch(     keyCreator.writeKey("Private.key",
Exception e )privateKey.getEncoded());
                        {     /*
     e.printStackTrace();      * Get the public and private key
                        }      */
            }     KeyReader keyReader = new KeyReader();
      PublicKey publicKey2 =
            /**This method is used to readkeyReader.getPublicKey("Public.key");
the bytes from the file.     System.out.println("Public Key----"+publicKey2);
             * The file can be a Public key     PrivateKey privateKey2 =
file or a Private keykeyReader.getPrivateKey("Private.key");
             * file. In this file, you have stored     System.out.println("Private
the security key,Key----"+privateKey2);
             * based upon which encryption    
and decryption can be     String str = "Hi, Hello World, Welcome to the
             * performed.World of Java";
             * @param fileName of type     byte[] stringBytes = str.getBytes();
String indicating the file name     byte[] encryptedBytes =
             * @return the bytes from theSecurityUtil.getEncryptedBytes(
file                            
             * @throws ExceptionstringBytes, privateKey2);
             */     String encryptedString = new
            private byte[] getKeyData( StringString(encryptedBytes);
fileName ) throws Exception    
            {;
                           
FileInputStream fis = new FileInputStream(fileName);     byte[] decryptedBytes =
                       SecurityUtil.getDecryptedBytes(encryptedBytes,
ByteArrayOutputStream baos = newpublicKey2);
ByteArrayOutputStream();     System.out.println("Decrypted String----"+new
                        int b;String(decryptedBytes));
                        try                        }
                        {                        catch(
     while ((b = fis.read()) != -1)Exception e )
     {                        {
                 baos.write(b);     e.printStackTrace();
     }                        }
     fis.close();            }
     baos.flush();}
     baos.close();To test the above programs, please create the
                        } catchappropriate package as mentioned in the program.
(IOException e) {You can also create your own package and modify
     e.printStackTrace();the package name in the above programs. You can all
                        }the code in your favorable java editor.
                        returnConclusion I hope that you will enjoy my article. If you
baos.toByteArray();find any problems or errors, please feel free to send
            }me a mail in the address . This article is only meant for
 those who are new to java development. This article
            /**This method is used to returndoes not bear any commercial significance. Please
the object of typeprovide me the feedback about this article.