Encryption Utilizing Rsa Algorithm in Java

Encryption Utilizing Rsa Algorithm in Java

Encryption utilizing RSA algorithm in java

Introduction

In this article I will offer you an strategy of utilizing RSA algorithm for prolonged String. As you know that RSA algorithm is confined 117 bytes, prolonged strings can not be encrypted or decrypted. Nonetheless it is doable to split the bytes into various chunks and then to encrypt or decrypt the contents. This algorithm is applied for asymmetric cryptography. For asymmetric cryptography, you can simply click this connection.

Technicalities

In this article I offer under the full instance for encryption and decryption of prolonged strings. If you use the method of Cipher class ie.doFinal( byte[] bytesString), it will toss exception that it can be encrypted for far more than 117 bytes for RSA.  But in the actual application, you could not be absolutely sure about the size of the String you want to encrypt or decrypt. In this case you have to split the bytes and then to encrypt it. Make sure you refer to the

Following full instance.

Full instance

Course name : SecurityUtil.java

offer com.dds.main.stability

import java.stability.KeyFactory

import java.stability.KeyPair

import java.stability.KeyPairGenerator

import java.stability.PrivateKey

import java.stability.PublicKey

import java.stability.Security

import java.stability.spec.EncodedKeySpec

import java.stability.spec.PKCS8EncodedKeySpec

import java.stability.spec.X509EncodedKeySpec

import javax.crypto.Cipher

import sun.misc.BASE64Decoder

import sun.misc.BASE64Encoder

import com.sun.crypto.company.SunJCE

/**This is a utility class which provides

 * convenient method for stability. This

 * class provides the way where by you can

 * encrypt and decrypt the String having

 * far more than 117 bytes for RSA algorithm

 * which is an asymmetric one particular.

 * @creator Debadatta Mishra(PIKU)

 *

 */

public class SecurityUtil {

            /**

             * Item of form @connection KeyPair

             */

            personal KeyPair keyPair

            /**

             * String variable which denotes the algorithm

             */

            personal static closing String ALGORITHM = “RSA”

            /**

             * varibale for the keysize

             */

            personal static closing int KEYSIZE = 1024

            /**

             * Default constructor

             */

            public SecurityUtil()

                        tremendous()

                        Security.addProvider(new SunJCE())

           

            /**

             * This method is applied to deliver

             * the key pair.

             */

            public void invokeKeys()

                        attempt

                                    KeyPairGenerator keypairGenerator = KeyPairGenerator

                                    .getInstance(ALGORITHM)

                                    keypairGenerator.initialize(KEYSIZE)

                                    keyPair = keypairGenerator.generateKeyPair()

                        capture (Exception e)

                                    e.printStackTrace()

                       

           

            /**This method is applied to attain the String

             * representation of the PublicKey.

             * @param publicKey of form @connection PublicKey

             * @return PublicKey as a String

             */

            public String getPublicKeyString(PublicKey publicKey)

                        return new BASE64Encoder().encode(publicKey.getEncoded())

           

            /**This method is applied to attain the String

             * representation of the PrivateKey.

             * @param privateKey of form @connection PrivateKey

             * @return PrivateKey as a String

             */

            public String getPrivateKeyString(PrivateKey privateKey)

                        return new BASE64Encoder().encode(privateKey.getEncoded())

           

            /**This method is applied to attain the

             * @connection PrivateKey item from the

             * String representation.

             * @param key of form String

             * @return @connection PrivateKey

             * @throws Exception

             */

            public PrivateKey getPrivateKeyFromString(String key) throws Exception

                        PrivateKey privateKey = null

                        attempt

                                    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM)

                                    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(

                                                            new BASE64Decoder().decodeBuffer(key))

                                    privateKey = keyFactory.generatePrivate(privateKeySpec)

                        capture (Exception e)

                                    e.printStackTrace()

                       

                        return privateKey

           

            /**This method is applied to attain the @connection PublicKey

             * from the String representation of the Community Critical.

             * @param key of form String

             * @return @connection PublicKey

             * @throws Exception

             */

            public PublicKey getPublicKeyFromString(String key) throws Exception

                        PublicKey publicKey = null

                        attempt

                                    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM)

                                    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(

                                                            new BASE64Decoder().decodeBuffer(key))

                                    publicKey = keyFactory.generatePublic(publicKeySpec)

                        capture (Exception e)

                                    e.printStackTrace()

                       

                        return publicKey

           

            /**This method is applied to attain the

             * encrypted contents from the initial

             * contents by passing the @connection PublicKey.

             * This method is practical when the byte is far more

             * than 117.

             * @param textual content of form String

             * @param key of form @connection PublicKey

             * @return encrypted value as a String

             * @throws Exception

             */

            public String getEncryptedValue(String textual content, PublicKey key)

            throws Exception {

                        String encryptedText

                        attempt

                                    byte[] textBytes = textual content.getBytes(“UTF8”)

                                    Cipher cipher = Cipher.getInstance(“RSA/ECB/PKCS1Padding”)

                                    cipher.init(Cipher.ENCRYPT_Manner, key)

                                    int textBytesChunkLen = a hundred

                                    int encryptedChunkNum = (textBytes.size – one) / textBytesChunkLen

                                    + one

                                    // RSA returns 128 bytes as output for a hundred textual content bytes

                                    int encryptedBytesChunkLen = 128

                                    int encryptedBytesLen = encryptedChunkNum * encryptedBytesChunkLen

                                    Process.out.println(“Encrypted bytes size——-“

                                                            + encryptedBytesChunkLen)

                                    // Outline the Output array.

                                    byte[] encryptedBytes = new byte[encryptedBytesLen]

                                    int textBytesChunkIndex =

                                    int encryptedBytesChunkIndex =

                                    for (int i = i < encryptedChunkNum i++)

                                                if (i < encryptedChunkNum - 1)

                                                            encryptedBytesChunkIndex = encryptedBytesChunkIndex

                                                            + cipher.doFinal(textBytes, textBytesChunkIndex,

                                                                                    textBytesChunkLen, encryptedBytes,

                                                                                    encryptedBytesChunkIndex)

                                                            textBytesChunkIndex = textBytesChunkIndex

                                                            + textBytesChunkLen

                                                else

                                                            cipher.doFinal(textBytes, textBytesChunkIndex,

                                                                                    textBytes.size – textBytesChunkIndex,

                                                                                    encryptedBytes, encryptedBytesChunkIndex)

                                               

                                   

                                    encryptedText = new BASE64Encoder().encode(encryptedBytes)

                        capture (Exception e)

                                    toss e

                       

                        return encryptedText

            }

            /**This method is applied to decrypt the contents.

             * This method is practical when the size of the

             * bytes is far more than 117.

             * @param textual content of form String indicating the

             * encrypted contents.

             * @param key of form @connection PrivateKey

             * @return decrypted value as a String

             */

            public String getDecryptedValue(String textual content, PrivateKey key) {

                        String end result = null

                        attempt

                                    byte[] encryptedBytes = new BASE64Decoder().decodeBuffer(textual content)

                                    Cipher cipher = Cipher.getInstance(“RSA/ECB/PKCS1Padding”)

                                    cipher.init(Cipher.DECRYPT_Manner, key)

                                    int encryptedByteChunkLen = 128

                                    int encryptedChunkNum = encryptedBytes.size

                                    / encryptedByteChunkLen

                                    int decryptedByteLen = encryptedChunkNum * encryptedByteChunkLen

                                    byte[] decryptedBytes = new byte[decryptedByteLen]

                                    int decryptedIndex =

                                    int encryptedIndex =

                                    for (int i = i < encryptedChunkNum i++)

                                                if (i < encryptedChunkNum - 1)

                                                            decryptedIndex = decryptedIndex

                                                            + cipher.doFinal(encryptedBytes, encryptedIndex,

                                                                                    encryptedByteChunkLen, decryptedBytes,

                                                                                    decryptedIndex)

                                                            encryptedIndex = encryptedIndex + encryptedByteChunkLen

                                                else

                                                            decryptedIndex = decryptedIndex

                                                            + cipher.doFinal(encryptedBytes, encryptedIndex,

                                                                                    encryptedBytes.size – encryptedIndex,

                                                                                    decryptedBytes, decryptedIndex)

                                               

                                   

                                    end result = new String(decryptedBytes).trim()

                        capture (Exception e)

                                    e.printStackTrace()

                       

                        return end result

            }

            /**This method is applied attain the

             * @connection PublicKey

             * @return @connection PublicKey

             */

            public PublicKey getPublicKey()

                        return keyPair.getPublic()

           

            /**This method is applied to attain

             * the @connection PrivateKey

             * @return @connection PrivateKey

             */

            public PrivateKey getPrivateKey()

                        return keyPair.getPrivate()

           

}

The previously mentioned class provides various practical solutions for era of Private key , Community Critical and encryption of String and decryption of String.

Make sure you refer to the following subordinate courses for the previously mentioned class.

Course name : KeyGenerator.java

offer com.dds.main.stability

import java.io.File

import java.io.FileOutputStream

import java.io.OutputStream

import java.stability.PrivateKey

import java.stability.PublicKey

import java.util.Homes

/**This class is applied to deliver the

 * Private and Community key and merchants

 * them in files.

 * @creator Debadatta Mishra(PIKU)

 *

 */

public class KeyGenerator

            /**This method is applied to attain the

             * path of the keys listing where by

             * Private and Community key files are

             * stored.

             * @return path of the keys listing

             */

            personal static String getKeyFilePath()

                        String keyDirPath = null

                        attempt

                                    keyDirPath = Process.getProperty(“person.dir”) + File.separator

                                    + “keys”

                                    File keyDir = new File(keyDirPath)

                                    if (!keyDir.exists())

                                                keyDir.mkdirs()

                        capture (Exception e)

                                    e.printStackTrace()

                       

                        return keyDirPath

           

            /**

             * This method is applied to deliver the

             * Private and Community keys.

             */

            public static void generateKeys()

                        Homes publicProp = new Homes()

                        Homes privateProp = new Homes()

                        attempt

                                    OutputStream pubOut = new FileOutputStream(getKeyFilePath()

                                                            + File.separator + “public.key”)

                                    OutputStream priOut = new FileOutputStream(getKeyFilePath()

                                                            + File.separator + “personal.key”)

                                    SecurityUtil secureUtil = new SecurityUtil()

                                    secureUtil.invokeKeys()

                                    PublicKey publicKey = secureUtil.getPublicKey()

                                    PrivateKey privateKey = secureUtil.getPrivateKey()

                                    String publicString = secureUtil.getPublicKeyString(publicKey)

                                    String privateString = secureUtil.getPrivateKeyString(privateKey)

                                    publicProp.put(“key”, publicString)

                                    publicProp.retailer(pubOut, “Community Critical Facts”)

                                    privateProp.put(“key”, privateString)

                                    privateProp.retailer(priOut, “Private Critical Facts”)

                        capture (Exception e)

                                    e.printStackTrace()

                       

           

The previously mentioned class is applied to deliver the Community and Private keys. It generates and merchants them in diverse files named Community.key and Private.key. Make sure you refer the test harness class for the previously mentioned class.

Course name: TestKeyGenerator

import com.dds.main.stability.KeyGenerator

/**This is a testharness class

 * for the KeyGenerator class.

 * @creator Debadatta Mishra(PIKU)

 *

 */

public class TestKeyGenerator

      public static void main(String[] args)

            KeyGenerator.generateKeys()

     

If you run the previously mentioned class, you will uncover a listing named keys in your root path of your application folder. In this folder you will uncover two files one particular is for Private Critical data and one more is for Community Critical.

There is one more class which is applied to attain the Private key and Community key data stored in the files.

Course name: KeyReader.java

offer com.dds.main.stability

import java.io.File

import java.io.FileInputStream

import java.io.InputStream

import java.stability.PublicKey

import java.util.Homes

/**This class is applied to read the

 * keys from the file.

 * @creator Debadatta Mishra(PIKU)

 *

 */

public class KeyReader

            /**This method is applied to attain the

             * string value of the Community Critical

             * from the file.

             * @return String of @connection PublicKey

             */

            public static String getPublicKeyString()

                        String publicString = null

                        attempt

                                    Homes prop = new Homes()

                                    String publicKeyPath = Process.getProperty(“person.dir”)

                                    + File.separator + “keys” + File.separator + “public.key”

                                    InputStream in = new FileInputStream(publicKeyPath)

                                    prop.load(in)

                                    publicString = prop.getProperty(“key”)

                        capture (Exception e)

                                    e.printStackTrace()

                       

                        return publicString

           

            /**This method is applied to attain the

             * String of Private Critical from the file.

             * @return String of personal key

             */

            public static String getPrivateKeyString()

                        String publicString = null

                        attempt

                                    Homes prop = new Homes()

                                    String publicKeyPath = Process.getProperty(“person.dir”)

                                    + File.separator + “keys” + File.separator + “personal.key”

                                    InputStream in = new FileInputStream(publicKeyPath)

                                    prop.load(in)

                                    publicString = prop.getProperty(“key”)

                        capture (Exception e)

                                    e.printStackTrace()

                       

                        return publicString

           

This is a utility class to read the Community and Private keys from the files.

Now refer to the test harness class which would make encryption and decryption of String.

import java.stability.PrivateKey

import java.stability.PublicKey

import com.dds.main.stability.KeyReader

import com.dds.main.stability.SecurityUtil

/**

 * This is a test harness class for encryption and decryption.

 *

 * @creator Debadatta Mishra(PIKU)

 *

 */

public class TestEncryption

            public static void main(String[] args)

                        String privateKeyString = KeyReader.getPrivateKeyString()

                        SecurityUtil securityUtil = new SecurityUtil()

                        String publicKeyString = KeyReader.getPublicKeyString()

                        attempt

                                    PublicKey publicKey = securityUtil

                                    .getPublicKeyFromString(publicKeyString)

                                    PrivateKey privateKey = securityUtil

                                    .getPrivateKeyFromString(privateKeyString)

                                    String originalValue = “offer some incredibly prolonged string”

                                    String encryptedValue = securityUtil.getEncryptedValue(

                                                            originalValue, publicKey)

                                    Process.out.println(“EncryptedValue—–” + encryptedValue)

                                    String decryptedValue = securityUtil.getDecryptedValue(

                                                            encryptedValue, privateKey)

                                    Process.out.println(“Unique Benefit——” + decryptedValue)

                        capture (Exception e)

                                    e.printStackTrace()

                       

           

This test harness class is applied to encrypt and decrypt the prolonged string contents. You can also use the very same method for file encryption and decryption. 1st you have to read the contents of a file as String and then you can use method to encrypt it.

Summary

I hope that you will get pleasure from my article for this asymmetric cryptography for RSA. For asymmetric cryptography make sure you refer to the connection http://www.articlesbase.com/data-technology-content/asymmetric-cryptography-in-java-438155.html. If you uncover any troubles or glitches, make sure you truly feel cost-free to ship me a mail in the address [email protected] . This article is only meant for these who are new to java advancement. This article does not bear any industrial importance. Make sure you offer me the responses about this article

Comments are closed.