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

  • Make requirements.txt in Python
    03 May

    Make requirements.txt in python

    Table of ContentsWhat is the requirements.txt file in Python?Ways to make requirements.txt file in PythonUsing the pip to make requirements.txt in PythonUsing the conda command to make requirements.txt file in PythonUsing the pipreqs package to make requirements.txt file in PythonConclusion What is the requirements.txt file in Python? Every package is also updated regularly and features […]

  • Create an array of 1 to 10 in Python
    03 May

    Create an Array of 1 to 10 in Python

    Table of ContentsIntroductionHow to create an array of 1 to 10 in Python?Using the range() function to create an array of 1 to 10 in Python.Using list comprehension along with the range() function to create an array of 1 to 10 in Python.Using a user-defined function to create an array of 1 to 10 in […]

  • Remove Urls from String in Python
    03 May

    Remove Urls from Text in Python

    Table of ContentsIntroductionWays to remove URLs from Text in PythonUsing the re.sub() function to remove URLs from Text in PythonUsing the re.findall() function to remove URLs from Text in PythonUsing the re.search() function to remove URLs from Text in PythonUsing the urllib.urlparse class to remove URLs from Text in PythonConclusion In this post, we will […]

  • Create a list from 1 to 100 in Python
    03 May

    Create a List from 1 to 100 in Python

    Table of ContentsWays to create a list from 1 to 100 in PythonUsing the range() function to create a list from 1 to 100 in PythonUsing the numpy.arange() function to create a list from 1 to 100 in PythonUsing the for loop with range() to create a list from 1 to 100 in PythonConclusion In […]

  • How to initialize an array in Constructor in C++
    23 April

    How to initialize an Array in Constructor in C++

    Table of ContentsArraysConstructors of a ClassWays to initialize an array in Constructor in C++Initialize an array in Constructor With std::fill()Initialize an array in Constructor Using for LoopInitialize an array in Constructor Using Member Initializer ListConclusion This article discusses methods of initializing an array in constructor in C++. Let us first discuss arrays and constructors in […]

  • Set an array to another array in java
    23 April

    Set an Array Equal to Another Array in Java

    Table of ContentsSetting an Array Variable Equal to Another Array VariableSet an Array Equal to Another Array in Java Using the clone() MethodSet an Array Equal to Another Array in Java Using the arraycopy() MethodSet an Array Equal to Another Array in Java Using the copyOf() MethodSet an Array Equal to Another Array in Java […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.