RSA Encryption and Decryption in Java

Introduction

RSA is a short form for Rivest, Shamir, and Adleman, are the people who first publicly described it in 1977.

It is an algorithm for asymmetric cryptography which involves the use of two keys.

  1. A public key, which can be known to anybody and can be used to encrypt messages, and verify signatures.
  2. A private key, known only to the intended user, is used to decrypt messages and create signatures.

RSA is asymmetric because those who encrypt messages or verify signatures cannot decrypt messages or create signatures.

RSA algorithm involves three steps which include key generation, encryption, and decryption.

Generate RSA key pair

To generate an RSA key pair, use the getInstance() static method of the KeyPairGenerator class and pass the RSA parameter as the encryption algorithm to be used.

The generator will create a public and private key pair that can be used with the RSA algorithm and associate algorithm-specific parameters with each generated key.

The KeyPairGenerator class has a concept of key size and a source of randomness that you can initialize using the initialize() method of the class.

Note that if you do not explicitly initialize the KeyPairGenerator, the provider will supply a default initialization.

The defaults may change in future versions, so it is recommended to explicitly initialize the KeyPairGenerator instead of relying on the provider defaults.

The RSA implementations of the Java platform are required to support 1024, 2048, and 4096 key sizes.

The source of randomness will come from SecureRandom, which will be the second argument of the initialize method.

If the key size is not supported by the KeyPairGenerator object, the method throws an InvalidParameterException.

The generateKeyPair() method will generate a new KeyPair every time it is called, and we can use the getPublic() and getPrivate() methods of the KeyPair class to retrieve the public key and private key respectively.

To see the generated keys call getEncoded() on each of the methods, which return the key in its primary encoding format or null if the key does not support encoding.

Convert the keys to string using encodeToString() method of the Base64.Encoder class and log to the console to view the contents.

Output:

public key = MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj+F36LJSLmXGQFGNOHwinu2Cm9NTnpSE/Y+SXCw

private key = MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCP4XfoslIuZcZAUY04fCKe7YKb01OelIT9j5JcLD

Encrypt a random text

Create a Cipher object using the static method getInstance() and pass RSA as the transformation. The Cipher will provide the functionality of a cryptographic cipher for encryption and decryption.

The transformation describes the operation to be performed on the given input to produce some output. The name of the cryptographic algorithm form the transformation and may be accompanied by a feedback mode and a padding scheme.

The Cipher's init() method initializes the cipher with a key for encryption, decryption, key wrapping, or key unwrapping depending on the value of opmode.

The opmode stands for the operation mode of the cipher, and since we want to encrypt a text, we will use ENCRYPT_MODE as our operation mode in this case.

The Cipher's init() method will also use the private key generated by the KeyPairGenerator when encrypting the text, so it must be passed as the second argument.

The doFinal() method performs the encryption operation depending on how the cipher was initialized and resets once it finishes allowing encrypting more data.

Note that if an exception is thrown by this method, the cipher may need to be reset before it can be used again, and the exceptions that might be thrown include IllegalStateException, IllegalBlockSizeException, BadPaddingException, and AEADBadTagException.

Output

public key = MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj+F36LJSLmXGQFGNOHwinu2Cm9NTnpSE/Y+SXCw

private key = MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCP4XfoslIuZcZAUY04fCKe7YKb01OelIT9j5JcLD

encrypted message = VBnz7eObiVnkdlQxDh1rpeJUCLlH42hcZFB1mY9kfKyRuD9nVh1wKEkZ9Q/EqhkZFC4utkFijxl7N0q

Decrypt the random text

The decryption process is the same as the encryption but only the init() method of the cipher is modified to support DECRYPT_MODE.

Create a Cipher object using RSA transformation and pass the DECRYPT_MODE as the first parameter and public key generated by KeyPairGenerator as the second parameter of the init() method.

The doFinal() method performs both encryption and decryption when the right mode is initialized, and we only need to pass our encrypted message to it so that it can be decrypted.

The method returns an array of bites which is simply our message, and we can convert it to a string and log it to the console to verify our text is similar to the decrypted text.

Output

public key = MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj+F36LJSLmXGQFGNOHwinu2Cm9NTnpSE/Y+SXCw

private key = MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCP4XfoslIuZcZAUY04fCKe7YKb01OelIT9j5JcLD

encrypted message = VBnz7eObiVnkdlQxDh1rpeJUCLlH42hcZFB1mY9kfKyRuD9nVh1wKEkZ9Q/EqhkZFC4utkFijxl7N0q

decrypted message = Hello world

Conclusion

In this tutorial, You have learned how to encrypt and decrypt a random text by leveraging RSA asymmetric encryption algorithm by generating a private key and public key using java KeyPairGenerator and a Cipher class that provided encryption and decryption functionalities. In the next tutorial, you will learn how to encrypt and decrypt using Java AES and Java AES 256.

That’s all about RSA Encryption and Decryption in Java.

    Related Posts

    • Python add commas to number
      11 September

      Python add commas to number

      Table of ContentsUsing the format() function to add commas to numbers in PythonUsing the fstrings to add commas to numbers in PythonUsing the regular expressions to add commas to numbers in PythonUsing the locale module to add commas to numbers in Python Python allows us to format values to get the final result in our […]

    • 10 September

      How to remove element from Arraylist in java while iterating

      Table of ContentsIntroductionUsing Collection’s removeIf() methodUsing ListIterator classUsing removeAll() methodUsing Java 8 Stream to filter List itemsConclusion Introduction In this tutorial, you will learn how to remove element from Arraylist in java while iterating using different implementations provided by Java. It is necessary to understand the right way to remove items from a List because […]

    • Watch New Release Movies Online Free Without Signing Up
      10 September

      Watch New Release Movies Online Free Without Signing Up: Top 22 Websites

      Table of ContentsWatch New Release Movies Online Free Without Signing UpWatch New Release Movies Online Free Without Signing Up: Best Websites123MoviesFMoviesWatchFreeYes MoviesYifi MoviesWatch Movie StreamSolar MoviesPut LockerSony CrackleMovies JoyYo MoviesPopcorn FlixCracklePluto TVSome other Platforms to Watch New Release Movies Online Free Without Signing Up It is Saturday night again, and are you tired of signing […]

    • 10 September

      Change the font size of title in Matplotlib

      In Python, there are a lot of libraries that are used for data visualization. One of the libraries is the Matplotlib library. The Matplotlib library is a very good library when it comes to data visualisation in python. With the help of this library, many types of graphs and visual representations of the data can […]

    • Free movie apps for android
      08 September

      22 Best Free Movie Apps For Android

      Table of ContentsThe Most Promising Free Movie Apps for AndroidPopcornflixSony CrackleFreeFlix HQVuduTubi TVFilm RiseUKMovNowCrunchyrollCyberflix TVYidioPluto TVTea TVPlexMovies AnywhereOld MoviesCinema HDVideoMixKodiSnagfilmsIMDB OriginalsFree Movie Tube App for AndroidMegabox HDFrequently Asked Questions About Free Movie Apps for AndroidDo there exist free movie apps for Android?Which are the best free movie apps for Android?Is it safe to use the […]

    • Free live tv streaming sites
      08 September

      Best Free Live TV Streaming Sites in 2021

      Table of ContentsBest Free Live TV Streaming Sites in 2021Stream2WatchTVPlayerUSTVGO123TVPluto TVUStreamXumoOK Live TVAiry TVPlex Live TVDistro TVCrackstreamsSquid TVFree TVMX PlayerTV CatchupTime4TVPeacock TVYupp TVSports SurgeFrequently Asked Questions About Free Live TV Streaming SitesIs watching free live tv streaming sites possible on Android/Firestick?What are the best free live TV streaming sites?Are the free live tv streaming sites […]

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Subscribe to our newletter

    Get quality tutorials to your inbox. Subscribe now.