Encryption using RSA algorithm in Java Introduction In this article I will give you an approach of using RSA algorithm for a long string. How do you know that RSA is 117 bytes long strings limited can not be encrypted or decrypted. However, it is possible to break the bytes into several pieces and then encrypt or decrypt the contents. This algorithm is used for asymmetric cryptography. For asymmetric cryptography, you can click on this link. Technicalities In this article I will provide below the complete example for encryption and decryption of long strings. If you mean the method of the Cipher class. doFinal (byte [] bytes string), it is the exception that it encodes more than 117 bytes for RSA to be removed. But in the real application can not be sure about the length of the string to encrypt or decrypt. In this case, you need to break the bytes and then encrypt. Please read After the complete example. Complete example Class name: SecurityUtil. Java com package. DDS. Core. Security; import java. Security. KeyFactory; import java. Security. KeyPair; import java. Security. KeyPairGenerator; import java. Security. PrivateKey; import java. Security. PublicKey; import java. Security. Security; import java. Security. spec. EncodedKeySpec; import java. Security. spec. PKCS8EncodedKeySpec; import java. Security. spec. X509EncodedKeySpec; Import javax. Crypto. Cipher; People just misc. BASE64Decoder; People just misc. BASE64Encoder; Import com. Sun Crypto. Manufacturer. SunJCE; / ** This is a utility class provides the * Convenient method for security. This * Class represents the way where you * Encrypt and decrypt the string with * More than 117 bytes for RSA algorithm * This is to be asymmetrical. * @ Author Debadatta Mishra (PIKU) * * / public class SecurityUtil ( / ** * Object of type (@ link) KeyPair * / key private key pair; / ** * String variable that identifies the algorithm * / private static final String ALGORITHM = “RSA”; / ** * Varibale for the key length * / private static final int keysize = 1024; / ** * Default Constructor * / public SecurityUtil () ( super (); Security. addProvider (new SunJCE ()); ) / ** * This method is for the production of * The key pair. * / public void invokeKeys () ( try ( KeyPairGenerator keypairGenerator = KeyPairGenerator . getInstance (algorithm); keypairGenerator. initialize (key length); Key = keypairGenerator. generateKeyPair (); ) Catch (Exception e) ( e. printStackTrace (); ) ) / ** This method is used to get the string * Representation of the PublicKey. * @ Param publicKey of type (@ link) PublicKey * @ Return a string PublicKey * / public String getPublicKeyString (PublicKey publicKey) ( return new BASE64Encoder (). encode (publicKey. getEncoded ()); ) / ** This method is used to get the string * Representation of the private key. * @ Param privateKey of type (@ link) PrivateKey * @ Return PrivateKey as a string * / public String getPrivateKeyString (PrivateKey privateKey) ( return new BASE64Encoder (). encode (privateKey. getEncoded ()); ) / ** This method is used to * (@ Link) PrivateKey object from the * String representation. * @ Param key of type String * @ Return (@ link) PrivateKey * @ Throws Exception * / public PrivateKey getPrivateKeyFromString (String key) throws Exception ( PrivateKey privateKey = null; try ( KeyFactory keyFactory = KeyFactory. getInstance (algorithm); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec ( BASE64Decoder new (). decodeBuffer (key)); privateKey = keyFactory. generate Private (privateKeySpec); ) Catch (Exception e) ( e. printStackTrace (); ) PrivateKey return; ) / ** This method is used to obtain the (@ link PublicKey) * From the string representation of the Public Key. * @ Param key of type String * @ Return (@ link) PublicKey * @ Throws Exception * / public PublicKey getPublicKeyFromString (String key) throws Exception ( PublicKey PublicKey = null; try ( KeyFactory keyFactory = KeyFactory. getInstance (algorithm); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec ( BASE64Decoder new (). decodeBuffer (key)); publicKey = keyFactory. generate Public (publicKeySpec); ) Catch (Exception e) ( e. printStackTrace (); ) PublicKey return; ) / ** This method is used to * Encrypted content from the original * Content by the (@ link) PublicKey. * This method is useful when the more byte * The 117th * @ Param text a String * @ Param key of type (@ link) PublicKey * @ Return encrypted value as a string * @ Throws Exception * / getEncryptedValue public String (String text, PublicKey key) throws Exception ( String encryptedText; try ( byte [] text = text bytes. getBytes (“utf8″); Cipher cipher = Cipher. getInstance (“RSA/ECB/PKCS1Padding”); Cipher. init (Cipher. ENCRYPT_MODE, key); textBytesChunkLen int = 100; int encryptedChunkNum = (textBytes. length – 1) / textBytesChunkLen + 1; / / RSA 128 bytes provides a starting text for 100 bytes encryptedBytesChunkLen int = 128; int = encryptedBytesChunkLen encryptedBytesLen encryptedChunkNum *; System. out. (Println “Encrypted byte length ——-” + EncryptedBytesChunkLen); / / Define the output array. byte [] encryptedBytes = new byte [] encryptedBytesLen; textBytesChunkIndex int = 0; encryptedBytesChunkIndex int = 0; for (int i = 0; i if (i encryptedBytesChunkIndex = encryptedBytesChunkIndex + Cipher. doFinal (text bytes textBytesChunkIndex, textBytesChunkLen, encryptedBytes, encryptedBytesChunkIndex); textBytesChunkIndex = textBytesChunkIndex + TextBytesChunkLen; ) Else ( Cipher. doFinal (text bytes textBytesChunkIndex, text bytes. Length – textBytesChunkIndex, encryptedBytes, encryptedBytesChunkIndex); ) ) encryptedText BASE64Encoder = new (). encode (encryptedBytes); ) Catch (Exception e) ( throw e; ) EncryptedText return; ) / ** This method is used to decrypt the content. * This method is useful when the size of the * Bytes is more than 117th * @ Param text of type string, the * Encrypted content. * @ Param key of type (@ link) PrivateKey * @ Return decrypted value as a String * / getDecryptedValue public String (String text, PrivateKey key) ( String result = null; try ( byte [] = new encryptedBytes BASE64Decoder (). decodeBuffer (text); Cipher cipher = Cipher. getInstance (“RSA/ECB/PKCS1Padding”); Cipher. init (Cipher. DECRYPT_MODE, key); encryptedByteChunkLen int = 128; int = encryptedChunkNum encryptedBytes. Length / EncryptedByteChunkLen; int = encryptedByteChunkLen decryptedByteLen encryptedChunkNum *; byte [] decryptedBytes = new byte [] decryptedByteLen; decryptedIndex int = 0; encryptedIndex int = 0; for (int i = 0; i if (i decryptedIndex = decryptedIndex + Cipher. doFinal (encryptedBytes, encryptedIndex, encryptedByteChunkLen, decryptedBytes, decryptedIndex); encryptedByteChunkLen encryptedIndex encryptedIndex = +; ) Else ( decryptedIndex = decryptedIndex + Cipher. doFinal (encryptedBytes, encryptedIndex, encryptedBytes. Length – encryptedIndex, decryptedBytes, decryptedIndex); ) ) result = new String (decryptedBytes). trim (); ) Catch (Exception e) ( e. printStackTrace (); ) return result; ) / ** This method is used to obtain the * (@ Link) PublicKey * @ Return (@ link) PublicKey * / public PublicKey GetPublicKey () ( Return of keys. getPublic (); ) / ** This method is used to obtain The * (@ link) PrivateKey * @ Return (@ link) PrivateKey * / public PrivateKey getPrivateKey () ( Return of keys. getPrivate (); ) ) The above class provides some useful methods for the generation of private key, public key and the encryption and decryption of string by string. Please note the following sub-classes relating to the above classes. Class name: Keygenerator. Java com package. DDS. Core. Security; import java. io. File; import java. io. FileOutputStream; import java. io. Output Stream; import java. Security. PrivateKey; import java. Security. PublicKey; import java. util. Real estate; / ** This class is used to generate the * Private and public keys and stores * In files. * @ Author Debadatta Mishra (PIKU) * * / public class (Keygenerator / ** This method is used to * Path to the directory where the key * Private and public key files are * Filed. * @ Return path of the directory key * / private static String getKeyFilePath () ( KeyDirPath String = null; try ( keyDirPath = System. getProperty (“user. dir”) + File. Separator + “Keys”; KeyDir File = new File (keyDirPath); if (! keyDir. exists ()) keyDir. mkdir (); ) Catch (Exception e) ( e. printStackTrace (); ) KeyDirPath return; ) / ** * This method is used to generate the * Private and public keys. * / public static void generateKeys () ( PublicProp properties = new Properties (); PrivateProp properties = new Properties (); try ( OutputStream = new FileOutputStream pubOut (getKeyFilePath () + File. separator + “public. key”); OutputStream = new FileOutputStream priOut (getKeyFilePath () + File. separator + “private. key”); SecurityUtil secureUtil SecurityUtil = new (); secureUtil. invokeKeys (); PublicKey = publicKey secureUtil. GetPublicKey (); PrivateKey privateKey = secureUtil. getPrivateKey (); String public String = secureUtil. getPublicKeyString (publicKey); String = privateString secureUtil. getPrivateKeyString (privateKey); publicProp. put (“key” public String); publicProp. Store pubOut (, “Public Key Info”); privateProp. put (“key”, privateString); privateProp. Store priOut (“Private Key Info”); ) Catch (Exception e) ( e. printStackTrace (); ) ) ) The above class is used to generate the public and private key. It generates and stores them in different files with the name Public. Key and Private. Key. Please note the lab class for the above classes. Class name: TestKeyGenerator Import com. DDS. Core. Security. Keygenerator; / ** This is a class TestHarness * For the Keygenerator class. * @ Author Debadatta Mishra (PIKU) * * / public class TestKeyGenerator ( public static void main (String [] args) ( Keygenerator. generateKeys (); ) ) When you run the above class, you will find a directory called keys in your root path of your application folder. This folder contains two files one is for the private key and other information for public key. There is another class get used to the private key and public key is stored in the files. Class name: KeyReader. Java com package. DDS. Core. Security; import java. io. File; import java. io. FileInputStream; import java. io. InputStream; import java. Security. PublicKey; import java. util. Real estate; / ** This class is used to read the * Key from the file. * @ Author Debadatta Mishra (PIKU) * * / public class KeyReader ( / ** This method is used to * String value of the Public Key * From the file. * @ Return string of (@ link) PublicKey * / public static String getPublicKeyString () ( Public String string = null; try ( Properties prop = new Properties (); String publicKeyPath = System. getProperty (“user. you”) + File. separator + “keys” + File. separator + “public. key”; InputStream in = new FileInputStream (publicKeyPath); prop. Load (in); public String prop =. getProperty (“key”); ) Catch (Exception e) ( e. printStackTrace (); ) Public String return; ) / ** This method is used to * String the private key from the file. * @ Return string the private key * / public static String getPrivateKeyString () ( Public String string = null; try ( Properties prop = new Properties (); String publicKeyPath = System. getProperty (“user. you”) + File. separator + “keys” + File. separator + “private. key”; InputStream in = new FileInputStream (publicKeyPath); prop. Load (in); public String prop =. getProperty (“key”); ) Catch (Exception e) ( e. printStackTrace (); ) Public String return; ) ) This is a utility class to read the public and private key from the file. Now for the test environment class encryption and decryption of string makes reference. import java. Security. PrivateKey; import java. Security. PublicKey; Import com. DDS. Core. Security. KeyReader; Import com. DDS. Core. Security. SecurityUtil; / ** * This is a test environment class for encryption and decryption. * * @ Author Debadatta Mishra (PIKU) * * / public class TestEncryption ( public static void main (String [] args) ( String = privateKeyString KeyReader. getPrivateKeyString (); SecurityUtil SecurityUtil SecurityUtil = new (); String = publicKeyString KeyReader. getPublicKeyString (); try ( PublicKey = publicKey SecurityUtil . getPublicKeyFromString (publicKeyString); PrivateKey privateKey = SecurityUtil . getPrivateKeyFromString (privateKeyString); Original Value String = “offer some very long string”; String = encryptedValue SecurityUtil. getEncryptedValue ( original value, publicKey); System. out. Println (“EncryptedValue —–” encryptedValue +); String = decryptedValue SecurityUtil. getDecryptedValue ( encryptedValue, privateKey); System. out. Println (“+ decryptedValue ——” original value); ) Catch (Exception e) ( e. printStackTrace (); ) ) ) This lab class is used to encrypt and decrypt the contents of long string. You can also use the same method for file encryption and decryption. First you need to read the contents of a file as a string and then you can apply method to encrypt it. Completion I hope you enjoy my article for this asymmetric cryptography for RSA. For asymmetric cryptography, please refer to the link http://www. articlesbase. com/information-technology-articles/asymmetric-cryptography-in-java-438155. html. If you have any problems or mistakes, please send me an e-mail address in the debadattamishra @ AOL. com. This item is only for those who are new in Java Development meant. This article makes no commercial significance. Please give me feedback on this article
