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 sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

  • Remove nan from list in Python
    16 November

    Remove nan From List In Python?

    Table of ContentsWhat is nan in python?How to remove nan from list in python?Remove nan from list using the str() functionRemove nan from list using math.isnan() functionRemove nan from list using numPy.isnan() functionRemove nan from list using pandas.isnull() functionConclusion In python, nan is a special value used to represent missing values. In this article, we […]

  • Python print type of variable
    16 November

    Print type of variable in Python

    Table of ContentsWhat is the type of variable in Python?Ways to print type of variable in PythonUsing the type() functionUsing the isinstance() functionUsing the __class__() functionConclusion What is the type of variable in Python? We use variables to store data in a reserved memory location. The type of a variable defines the memory allocated to […]

  • Python float array to int
    11 November

    Convert float array to int array in Python

    Table of ContentsWhat are the types of arrays?Ways to convert float arrays to int in PythonUsing the numpy.asarray() functionUsing the numpy.astype() functionUsing the numpy.int_() functionUsing the numpy.round_() functionUsing the numpy.rint() functionUsing the numpy.floor() functionUsing the numpy.ceil() functionUsing the numpy.trunc() functionConclusion What are the types of arrays? An array is a common structure that stores multiple […]

  • List intersection in Python
    11 November

    List intersection in python

    Table of ContentsWhat is the list intersection in Python?Ways to find the list intersection in PythonUsing the for loop to achieve list intersection in PythonUsing the set() function to find list intersection in PythonUsing the intersection() function to find list intersection in PythonUsing the filter() and lambda functions to find list intersection in PythonUsing the […]

  • Bilinear Interpolation in Python
    11 November

    Bilinear Interpolation in Python

    Table of ContentsWhat is Bilinear Interpolation?Creating a function to perform bilinear interpolation in PythonUsing the scipy.interpolate.interp2d() function to perform bilinear interpolation in Python What is Bilinear Interpolation? Linear Interpolation in mathematics helps curve fitting by using linear polynomials that make new data points between a specific range of a discrete set of definite data points. […]

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.