December 8, 2024

Baskentmuhendislik

The technology folks

Encryption Using Rsa Algorithm in Java

Encryption employing RSA algorithm in java

Introduction

In this write-up I will offer you an tactic of employing RSA algorithm for lengthy String. As you know that RSA algorithm is restricted 117 bytes, lengthy strings can not be encrypted or decrypted. Nevertheless it is achievable to break the bytes into quite a few chunks and then to encrypt or decrypt the contents. This algorithm is used for asymmetric cryptography. For asymmetric cryptography, you can click this url.

Technicalities

In this write-up I offer beneath the comprehensive instance for encryption and decryption of lengthy strings. If you use the method of Cipher class ie.doFinal( byte[] bytesString), it will toss exception that it can be encrypted for a lot more than 117 bytes for RSA.  But in the true software, you might not be certain about the length of the String you want to encrypt or decrypt. In this situation you have to break the bytes and then to encrypt it. Be sure to refer to the

Subsequent comprehensive instance.

Full instance

Course name : SecurityUtil.java

package deal com.dds.main.protection

import java.protection.KeyFactory

import java.protection.KeyPair

import java.protection.KeyPairGenerator

import java.protection.PrivateKey

import java.protection.PublicKey

import java.protection.Safety

import java.protection.spec.EncodedKeySpec

import java.protection.spec.PKCS8EncodedKeySpec

import java.protection.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

 * effortless method for protection. This

 * class provides the way where you can

 * encrypt and decrypt the String having

 * a lot more than 117 bytes for RSA algorithm

 * which is an asymmetric a person.

 * @writer Debadatta Mishra(PIKU)

 *

 */

community class SecurityUtil {

            /**

             * Object of type @url KeyPair

             */

            non-public KeyPair keyPair

            /**

             * String variable which denotes the algorithm

             */

            non-public static final String ALGORITHM = “RSA”

            /**

             * varibale for the keysize

             */

            non-public static final int KEYSIZE = 1024

            /**

             * Default constructor

             */

            community SecurityUtil()

                        super()

                        Safety.addProvider(new SunJCE())

           

            /**

             * This method is used to make

             * the crucial pair.

             */

            community void invokeKeys()

                        try

                                    KeyPairGenerator keypairGenerator = KeyPairGenerator

                                    .getInstance(ALGORITHM)

                                    keypairGenerator.initialize(KEYSIZE)

                                    keyPair = keypairGenerator.generateKeyPair()

                        catch (Exception e)

                                    e.printStackTrace()

                       

           

            /**This method is used to attain the String

             * representation of the PublicKey.

             * @param publicKey of type @url PublicKey

             * @return PublicKey as a String

             */

            community String getPublicKeyString(PublicKey publicKey)

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

           

            /**This method is used to attain the String

             * representation of the PrivateKey.

             * @param privateKey of type @url PrivateKey

             * @return PrivateKey as a String

             */

            community String getPrivateKeyString(PrivateKey privateKey)

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

           

            /**This method is used to attain the

             * @url PrivateKey item from the

             * String representation.

             * @param crucial of type String

             * @return @url PrivateKey

             * @throws Exception

             */

            community PrivateKey getPrivateKeyFromString(String crucial) throws Exception

                        PrivateKey privateKey = null

                        try

                                    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 used to attain the @url PublicKey

             * from the String representation of the Community Critical.

             * @param crucial of type String

             * @return @url PublicKey

             * @throws Exception

             */

            community PublicKey getPublicKeyFromString(String crucial) throws Exception

                        PublicKey publicKey = null

                        try

                                    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 used to attain the

             * encrypted contents from the primary

             * contents by passing the @url PublicKey.

             * This method is beneficial when the byte is a lot more

             * than 117.

             * @param textual content of type String

             * @param crucial of type @url PublicKey

             * @return encrypted benefit as a String

             * @throws Exception

             */

            community String getEncryptedValue(String textual content, PublicKey crucial)

            throws Exception {

                        String encryptedText

                        try

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

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

                                    cipher.init(Cipher.ENCRYPT_Method, crucial)

                                    int textBytesChunkLen = one hundred

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

                                    + 1

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

                                    int encryptedBytesChunkLen = 128

                                    int encryptedBytesLen = encryptedChunkNum * encryptedBytesChunkLen

                                    Method.out.println(“Encrypted bytes length——-“

                                                            + 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.length – textBytesChunkIndex,

                                                                                    encryptedBytes, encryptedBytesChunkIndex)

                                               

                                   

                                    encryptedText = new BASE64Encoder().encode(encryptedBytes)

                        catch (Exception e)

                                    toss e

                       

                        return encryptedText

            }

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

             * This method is beneficial when the size of the

             * bytes is a lot more than 117.

             * @param textual content of type String indicating the

             * encrypted contents.

             * @param crucial of type @url PrivateKey

             * @return decrypted benefit as a String

             */

            community String getDecryptedValue(String textual content, PrivateKey crucial) {

                        String end result = null

                        try

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

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

                                    cipher.init(Cipher.DECRYPT_Method, crucial)

                                    int encryptedByteChunkLen = 128

                                    int encryptedChunkNum = encryptedBytes.length

                                    / 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.length – encryptedIndex,

                                                                                    decryptedBytes, decryptedIndex)

                                               

                                   

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

                        catch (Exception e)

                                    e.printStackTrace()

                       

                        return end result

            }

            /**This method is used attain the

             * @url PublicKey

             * @return @url PublicKey

             */

            community PublicKey getPublicKey()

                        return keyPair.getPublic()

           

            /**This method is used to attain

             * the @url PrivateKey

             * @return @url PrivateKey

             */

            community PrivateKey getPrivateKey()

                        return keyPair.getPrivate()

           

}

The over class provides quite a few beneficial approaches for technology of Non-public crucial , Community Critical and encryption of String and decryption of String.

Be sure to refer to the next subordinate courses for the over class.

Course name : KeyGenerator.java

package deal com.dds.main.protection

import java.io.File

import java.io.FileOutputStream

import java.io.OutputStream

import java.protection.PrivateKey

import java.protection.PublicKey

import java.util.Homes

/**This class is used to make the

 * Non-public and Community crucial and merchants

 * them in files.

 * @writer Debadatta Mishra(PIKU)

 *

 */

community class KeyGenerator

            /**This method is used to attain the

             * route of the keys listing where

             * Non-public and Community crucial files are

             * stored.

             * @return route of the keys listing

             */

            non-public static String getKeyFilePath()

                        String keyDirPath = null

                        try

                                    keyDirPath = Method.getProperty(“consumer.dir”) + File.separator

                                    + “keys”

                                    File keyDir = new File(keyDirPath)

                                    if (!keyDir.exists())

                                                keyDir.mkdirs()

                        catch (Exception e)

                                    e.printStackTrace()

                       

                        return keyDirPath

           

            /**

             * This method is used to make the

             * Non-public and Community keys.

             */

            community static void generateKeys()

                        Homes publicProp = new Homes()

                        Homes privateProp = new Homes()

                        try

                                    OutputStream pubOut = new FileOutputStream(getKeyFilePath()

                                                            + File.separator + “community.crucial”)

                                    OutputStream priOut = new FileOutputStream(getKeyFilePath()

                                                            + File.separator + “non-public.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.put(“crucial”, publicString)

                                    publicProp.store(pubOut, “Community Critical Information”)

                                    privateProp.put(“crucial”, privateString)

                                    privateProp.store(priOut, “Non-public Critical Information”)

                        catch (Exception e)

                                    e.printStackTrace()

                       

           

The over class is used to make the Community and Non-public keys. It generates and merchants them in unique files termed Community.crucial and Non-public.crucial. Be sure to refer the test harness class for the over class.

Course name: TestKeyGenerator

import com.dds.main.protection.KeyGenerator

/**This is a testharness class

 * for the KeyGenerator class.

 * @writer Debadatta Mishra(PIKU)

 *

 */

community class TestKeyGenerator

      community static void key(String[] args)

            KeyGenerator.generateKeys()

     

If you operate the over class, you will locate a listing termed keys in your root route of your software folder. In this folder you will locate two files a person is for Non-public Critical details and an additional is for Community Critical.

There is an additional class which is used to attain the Non-public crucial and Community crucial details stored in the files.

Course name: KeyReader.java

package deal com.dds.main.protection

import java.io.File

import java.io.FileInputStream

import java.io.InputStream

import java.protection.PublicKey

import java.util.Homes

/**This class is used to study the

 * keys from the file.

 * @writer Debadatta Mishra(PIKU)

 *

 */

community class KeyReader

            /**This method is used to attain the

             * string benefit of the Community Critical

             * from the file.

             * @return String of @url PublicKey

             */

            community static String getPublicKeyString()

                        String publicString = null

                        try

                                    Homes prop = new Homes()

                                    String publicKeyPath = Method.getProperty(“consumer.dir”)

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

                                    InputStream in = new FileInputStream(publicKeyPath)

                                    prop.load(in)

                                    publicString = prop.getProperty(“crucial”)

                        catch (Exception e)

                                    e.printStackTrace()

                       

                        return publicString

           

            /**This method is used to attain the

             * String of Non-public Critical from the file.

             * @return String of non-public crucial

             */

            community static String getPrivateKeyString()

                        String publicString = null

                        try

                                    Homes prop = new Homes()

                                    String publicKeyPath = Method.getProperty(“consumer.dir”)

                                    + File.separator + “keys” + File.separator + “non-public.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 study the Community and Non-public keys from the files.

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

import java.protection.PrivateKey

import java.protection.PublicKey

import com.dds.main.protection.KeyReader

import com.dds.main.protection.SecurityUtil

/**

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

 *

 * @writer Debadatta Mishra(PIKU)

 *

 */

community class TestEncryption

            community static void key(String[] args)

                        String privateKeyString = KeyReader.getPrivateKeyString()

                        SecurityUtil securityUtil = new SecurityUtil()

                        String publicKeyString = KeyReader.getPublicKeyString()

                        try

                                    PublicKey publicKey = securityUtil

                                    .getPublicKeyFromString(publicKeyString)

                                    PrivateKey privateKey = securityUtil

                                    .getPrivateKeyFromString(privateKeyString)

                                    String originalValue = “offer some quite lengthy string”

                                    String encryptedValue = securityUtil.getEncryptedValue(

                                                            originalValue, publicKey)

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

                                    String decryptedValue = securityUtil.getDecryptedValue(

                                                            encryptedValue, privateKey)

                                    Method.out.println(“Primary Benefit——” + decryptedValue)

                        catch (Exception e)

                                    e.printStackTrace()

                       

           

This test harness class is used to encrypt and decrypt the lengthy string contents. You can also use the exact method for file encryption and decryption. Initially you have to study the contents of a file as String and then you can utilize method to encrypt it.

Conclusion

I hope that you will enjoy my write-up for this asymmetric cryptography for RSA. For asymmetric cryptography remember to refer to the url http://www.articlesbase.com/details-technology-article content/asymmetric-cryptography-in-java-438155.html. If you locate any complications or faults, remember to truly feel cost-free to ship me a mail in the handle [email protected] . This write-up is only meant for those people who are new to java advancement. This write-up does not bear any commercial significance. Be sure to offer me the feed-back about this write-up