Asymmetric encryption cryptography in Java


Cryptography is the study and practice of different techniques to secure communication from third party. It is used for cyber security. We try to develop approaches and practices for protecting sensitive data. The sole objective of cryptography is to secure data from the attacker. Asymmetric Encryption is also referred as public/private key. Private key as goes as its name, it will be private while the public key can be distributed. Encryption is a mathematical correlation between two keys, one for encryption and the other for decryption. For example, if there are two keys “A1” and “A2”, then if key “A1” is used for encryption and “A2” is used for decryption and vice versa.

We use RSA algorithm for asymmetric encryption, first we will generate a key pair (public, private).

Asymmetric encryption cryptography in java

To generate asymmetric key following steps can be followed −

  • First we generate public & private key using the SecureRandom class. It is used to generate random number.

  • By using RSA algorithm to generate keys. This class will provide getInstance() method which is used to pass a string variable which signify the key generation algorithm and it returns to key generator object.

  • Initializing the key Generator object with 2048 bits key size and passing the random number.

  • Now, the secret key is generated and we want to look at the key we can convert it into hexbinary format by using DatatypeConvertor.

Now implementing above approach −

Syntax

// Java program to create a
// asymmetric key

package java_cryptography;
import java.security.KeyPair;
import java.security
	.KeyPairGenerator;
import java.security
	.SecureRandom;
import javax.xml.bind
	.DatatypeConverter;

// Class to create an asymmetric key
public class Asymmetric {

	private static final String RSA
		= "RSA";

	// Generating public and private keys
	// using RSA algorithm.
	public static KeyPair generateRSAKkeyPair()
		throws Exception
	{
		SecureRandom secureRandom
			= new SecureRandom();

		KeyPairGenerator keyPairGenerator
			= KeyPairGenerator.getInstance(RSA);

		keyPairGenerator.initialize(
			2048, secureRandom);

		return keyPairGenerator
			.generateKeyPair();
	}

	// Driver code
	public static void main(String args[])
		throws Exception
	{
		KeyPair keypair
			= generateRSAKkeyPair();

		System.out.println(
			"Public Key is: "
			+ DatatypeConverter.printHexBinary(
				keypair.getPublic().getEncoded()));

		System.out.println(
			"Private Key is: "
			+ DatatypeConverter.printHexBinary(
				keypair.getPrivate().getEncoded()));
	}
}

Output

Now following steps can be taken to create program code −

  • We create two different modes encryption and decryption by using the cipher class. Encryption key is private key and decryption key is public key.

  • The doFinal() method is invoked on cipher which encrypts/decrypts data in a single-part operation, or finishes a multiple-part operation and returns byte array.

  • Lastly, we get the Cipher text after Encryption with ENCRYPT_MODE.

Program, Code

// Java program to perform the
// encryption and decryption
// using asymmetric key

package java_cryptography;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.Scanner;

import javax.crypto.Cipher;
import javax.xml.bind
	.DatatypeConverter;

public class Asymmetric {

	private static final String RSA
		= "RSA";
	private static Scanner sc;

	// Generating public & private keys
	// using RSA algorithm.
	public static KeyPair generateRSAKkeyPair()
		throws Exception
	{
		SecureRandom secureRandom = new SecureRandom();
		KeyPairGenerator keyPairGenerator
			= KeyPairGenerator.getInstance(RSA);

		keyPairGenerator.initialize(
			2048, secureRandom);
		return keyPairGenerator
			.generateKeyPair();
	}

	// Encryption function which converts
	// the plainText into a cipherText
	// using private Key.
	public static byte[] do_RSAEncryption(
		String plainText,
		PrivateKey privateKey)
		throws Exception
	{
		Cipher cipher = Cipher.getInstance(RSA);
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);
		return cipher.doFinal(
			plainText.getBytes());
	}

	// Decryption function which converts
	// the ciphertext back to the
	// original plaintext.
	public static String do_RSADecryption(
		byte[] cipherText,
		PublicKey publicKey)
		throws Exception
	{
		Cipher cipher
			= Cipher.getInstance(RSA);

		cipher.init(Cipher.DECRYPT_MODE,
					publicKey);
		byte[] result
			= cipher.doFinal(cipherText);

		return new String(result);
	}

	// Driver code
	public static void main(String args[])
		throws Exception
	{
		KeyPair keypair
			= generateRSAKkeyPair();

		String plainText = "This is the PlainText "+ "I want to Encrypt using RSA.";

		byte[] cipherText
			= do_RSAEncryption(
				plainText,
				keypair.getPrivate());

		System.out.println(
			"The Public Key is: "
			+ DatatypeConverter.printHexBinary(
				keypair.getPublic().getEncoded()));

		System.out.println(
			"The Private Key is: "
			+ DatatypeConverter.printHexBinary(
				keypair.getPrivate().getEncoded()));

		System.out.print("The Encrypted Text is: ");

		System.out.println(
			DatatypeConverter.printHexBinary(
				cipherText));

		String decryptedText
			= do_RSADecryption(
				cipherText,
				keypair.getPublic());

		System.out.println(
			"The decrypted text is: "
			+ decryptedText);
	}
}

Output

Conclusion

Thus, using RSA algorithm we created encrypted text “This is the PlainText I want to Encrpyt using RSA” in this article.

Updated on: 18-Jul-2023

493 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements