Encryption Making use of Rsa Algorithm in Java

Encryption using RSA algorithm in java

Introduction

In this report I will offer you an tactic of using RSA algorithm for extended String. As you know that RSA algorithm is constrained 117 bytes, extended strings can not be encrypted or decrypted. Even so it is probable to crack the bytes into a number of chunks and then to encrypt or decrypt the contents. This algorithm is made use of for asymmetric cryptography. For asymmetric cryptography, you can click this link.

Technicalities

In this report I offer under the finish case in point for encryption and decryption of extended strings. If you use the method of Cipher class ie.doFinal( byte[] bytesString), it will throw exception that it can be encrypted for far more than 117 bytes for RSA.  But in the actual software, you may possibly not be guaranteed about the size of the String you want to encrypt or decrypt. In this scenario you have to crack the bytes and then to encrypt it. You should refer to the

Next finish case in point.

Total case in point

Course identify : SecurityUtil.java

offer com.dds.core.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 sunshine.misc.BASE64Decoder

import sunshine.misc.BASE64Encoder

import com.sunshine.crypto.provider.SunJCE

/**This is a utility class which delivers

 * hassle-free method for stability. This

 * class delivers the way in which you can

 * encrypt and decrypt the String getting

 * far more than 117 bytes for RSA algorithm

 * which is an asymmetric one.

 * @author Debadatta Mishra(PIKU)

 *

 */

general public class SecurityUtil {

            /**

             * Object of form @link KeyPair

             */

            personal KeyPair keyPair

            /**

             * String variable which denotes the algorithm

             */

            personal static final String ALGORITHM = “RSA”

            /**

             * varibale for the keysize

             */

            personal static final int KEYSIZE = 1024

            /**

             * Default constructor

             */

            general public SecurityUtil()

                        super()

                        Security.addProvider(new SunJCE())

           

            /**

             * This method is made use of to create

             * the crucial pair.

             */

            general public void invokeKeys()

                        try out

                                    KeyPairGenerator keypairGenerator = KeyPairGenerator

                                    .getInstance(ALGORITHM)

                                    keypairGenerator.initialize(KEYSIZE)

                                    keyPair = keypairGenerator.generateKeyPair()

                        catch (Exception e)

                                    e.printStackTrace()

                       

           

            /**This method is made use of to attain the String

             * representation of the PublicKey.

             * @param publicKey of form @link PublicKey

             * @return PublicKey as a String

             */

            general public String getPublicKeyString(PublicKey publicKey)

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

           

            /**This method is made use of to attain the String

             * representation of the PrivateKey.

             * @param privateKey of form @link PrivateKey

             * @return PrivateKey as a String

             */

            general public String getPrivateKeyString(PrivateKey privateKey)

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

           

            /**This method is made use of to attain the

             * @link PrivateKey object from the

             * String representation.

             * @param crucial of form String

             * @return @link PrivateKey

             * @throws Exception

             */

            general public PrivateKey getPrivateKeyFromString(String crucial) throws Exception

                        PrivateKey privateKey = null

                        try out

                                    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM)

                                    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(

                                                            new BASE64Decoder().decodeBuffer(crucial))

                                    privateKey = keyFactory.generatePrivate(privateKeySpec)

                        catch (Exception e)

                                    e.printStackTrace()

                       

                        return privateKey

           

            /**This method is made use of to attain the @link PublicKey

             * from the String representation of the General public Crucial.

             * @param crucial of form String

             * @return @link PublicKey

             * @throws Exception

             */

            general public PublicKey getPublicKeyFromString(String crucial) throws Exception

                        PublicKey publicKey = null

                        try out

                                    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM)

                                    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(

                                                            new BASE64Decoder().decodeBuffer(crucial))

                                    publicKey = keyFactory.generatePublic(publicKeySpec)

                        catch (Exception e)

                                    e.printStackTrace()

                       

                        return publicKey

           

            /**This method is made use of to attain the

             * encrypted contents from the initial

             * contents by passing the @link PublicKey.

             * This method is practical when the byte is far more

             * than 117.

             * @param textual content of form String

             * @param crucial of form @link PublicKey

             * @return encrypted worth as a String

             * @throws Exception

             */

            general public String getEncryptedValue(String textual content, PublicKey crucial)

            throws Exception {

                        String encryptedText

                        try out

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

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

                                    cipher.init(Cipher.ENCRYPT_Manner, crucial)

                                    int textBytesChunkLen = 100

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

                                    + 1

                                    // RSA returns 128 bytes as output for 100 textual content bytes

                                    int encryptedBytesChunkLen = 128

                                    int encryptedBytesLen = encryptedChunkNum * encryptedBytesChunkLen

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

                                                            + encryptedBytesChunkLen)

                                    // Determine 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)

                        catch (Exception e)

                                    throw e

                       

                        return encryptedText

            }

            /**This method is made use of to decrypt the contents.

             * This method is practical when the measurement of the

             * bytes is far more than 117.

             * @param textual content of form String indicating the

             * encrypted contents.

             * @param crucial of form @link PrivateKey

             * @return decrypted worth as a String

             */

            general public String getDecryptedValue(String textual content, PrivateKey crucial) {

                        String end result = null

                        try out

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

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

                                    cipher.init(Cipher.DECRYPT_Manner, crucial)

                                    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()

                        catch (Exception e)

                                    e.printStackTrace()

                       

                        return end result

            }

            /**This method is made use of attain the

             * @link PublicKey

             * @return @link PublicKey

             */

            general public PublicKey getPublicKey()

                        return keyPair.getPublic()

           

            /**This method is made use of to attain

             * the @link PrivateKey

             * @return @link PrivateKey

             */

            general public PrivateKey getPrivateKey()

                        return keyPair.getPrivate()

           

}

The previously mentioned class delivers a number of practical strategies for era of Private crucial , General public Crucial and encryption of String and decryption of String.

You should refer to the adhering to subordinate classes for the previously mentioned class.

Course identify : KeyGenerator.java

offer com.dds.core.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 made use of to create the

 * Private and General public crucial and merchants

 * them in files.

 * @author Debadatta Mishra(PIKU)

 *

 */

general public class KeyGenerator

            /**This method is made use of to attain the

             * route of the keys listing in which

             * Private and General public crucial files are

             * stored.

             * @return route of the keys listing

             */

            personal static String getKeyFilePath()

                        String keyDirPath = null

                        try out

                                    keyDirPath = Technique.getProperty(“user.dir”) + File.separator

                                    + “keys”

                                    File keyDir = new File(keyDirPath)

                                    if (!keyDir.exists())

                                                keyDir.mkdirs()

                        catch (Exception e)

                                    e.printStackTrace()

                       

                        return keyDirPath

           

            /**

             * This method is made use of to create the

             * Private and General public keys.

             */

            general public static void generateKeys()

                        Homes publicProp = new Homes()

                        Homes privateProp = new Homes()

                        try out

                                    OutputStream pubOut = new FileOutputStream(getKeyFilePath()

                                                            + File.separator + “general public.crucial”)

                                    OutputStream priOut = new FileOutputStream(getKeyFilePath()

                                                            + File.separator + “personal.crucial”)

                                    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.place(“crucial”, publicString)

                                    publicProp.store(pubOut, “General public Crucial Facts”)

                                    privateProp.place(“crucial”, privateString)

                                    privateProp.store(priOut, “Private Crucial Facts”)

                        catch (Exception e)

                                    e.printStackTrace()

                       

           

The previously mentioned class is made use of to create the General public and Private keys. It generates and merchants them in diverse files called General public.crucial and Private.crucial. You should refer the check harness class for the previously mentioned class.

Course identify: TestKeyGenerator

import com.dds.core.stability.KeyGenerator

/**This is a testharness class

 * for the KeyGenerator class.

 * @author Debadatta Mishra(PIKU)

 *

 */

general public class TestKeyGenerator

      general public static void key(String[] args)

            KeyGenerator.generateKeys()

     

If you operate the previously mentioned class, you will uncover a listing called keys in your root route of your software folder. In this folder you will uncover two files one is for Private Crucial information and a different is for General public Crucial.

There is a different class which is made use of to attain the Private crucial and General public crucial information stored in the files.

Course identify: KeyReader.java

offer com.dds.core.stability

import java.io.File

import java.io.FileInputStream

import java.io.InputStream

import java.stability.PublicKey

import java.util.Homes

/**This class is made use of to browse the

 * keys from the file.

 * @author Debadatta Mishra(PIKU)

 *

 */

general public class KeyReader

            /**This method is made use of to attain the

             * string worth of the General public Crucial

             * from the file.

             * @return String of @link PublicKey

             */

            general public static String getPublicKeyString()

                        String publicString = null

                        try out

                                    Homes prop = new Homes()

                                    String publicKeyPath = Technique.getProperty(“user.dir”)

                                    + File.separator + “keys” + File.separator + “general public.crucial”

                                    InputStream in = new FileInputStream(publicKeyPath)

                                    prop.load(in)

                                    publicString = prop.getProperty(“crucial”)

                        catch (Exception e)

                                    e.printStackTrace()

                       

                        return publicString

           

            /**This method is made use of to attain the

             * String of Private Crucial from the file.

             * @return String of personal crucial

             */

            general public static String getPrivateKeyString()

                        String publicString = null

                        try out

                                    Homes prop = new Homes()

                                    String publicKeyPath = Technique.getProperty(“user.dir”)

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

                                    InputStream in = new FileInputStream(publicKeyPath)

                                    prop.load(in)

                                    publicString = prop.getProperty(“crucial”)

                        catch (Exception e)

                                    e.printStackTrace()

                       

                        return publicString

           

This is a utility class to browse the General public and Private keys from the files.

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

import java.stability.PrivateKey

import java.stability.PublicKey

import com.dds.core.stability.KeyReader

import com.dds.core.stability.SecurityUtil

/**

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

 *

 * @author Debadatta Mishra(PIKU)

 *

 */

general public class TestEncryption

            general public static void key(String[] args)

                        String privateKeyString = KeyReader.getPrivateKeyString()

                        SecurityUtil securityUtil = new SecurityUtil()

                        String publicKeyString = KeyReader.getPublicKeyString()

                        try out

                                    PublicKey publicKey = securityUtil

                                    .getPublicKeyFromString(publicKeyString)

                                    PrivateKey privateKey = securityUtil

                                    .getPrivateKeyFromString(privateKeyString)

                                    String originalValue = “offer some quite extended string”

                                    String encryptedValue = securityUtil.getEncryptedValue(

                                                            originalValue, publicKey)

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

                                    String decryptedValue = securityUtil.getDecryptedValue(

                                                            encryptedValue, privateKey)

                                    Technique.out.println(“Primary Value——” + decryptedValue)

                        catch (Exception e)

                                    e.printStackTrace()

                       

           

This check harness class is made use of to encrypt and decrypt the extended string contents. You can also use the similar method for file encryption and decryption. Initial you have to browse the contents of a file as String and then you can utilize method to encrypt it.

Conclusion

I hope that you will love my report for this asymmetric cryptography for RSA. For asymmetric cryptography remember to refer to the link http://www.articlesbase.com/information-technology-content articles/asymmetric-cryptography-in-java-438155.html. If you uncover any difficulties or faults, remember to really feel free to send out me a mail in the address [email protected] . This report is only intended for those who are new to java enhancement. This report does not bear any commercial significance. You should offer me the feedback about this report