search
HomeJavajavaTutorialAsymmetric encryption cryptography in Java

Asymmetric encryption cryptography in Java

Aug 19, 2023 am 10:25 AM
asymmetric encryptionjava programmingCryptography

Cryptography is the study and practice of different techniques to protect communications from interference by third parties. It is used for network security. We attempt to develop methods and practices to protect sensitive data. The only goal of cryptography is to protect data from attackers. Asymmetric encryption is also known as public/private key encryption. The private key, as the name suggests, will remain private, while the public key can be distributed. Encryption is a mathematical relationship 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, "A2" is used for decryption and vice versa.

We use the RSA algorithm for asymmetric encryption. First we will generate a pair of keys (public key, private key).

Cryptography of Asymmetric Encryption in Java

To generate asymmetric key following steps can be followed −

  • First, we use the SecureRandom class to generate the public and private keys. It is used to generate random numbers.

  • 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.

  • Initialize the key generator object with a 2048-bit key size, passing a 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 implement the above method −

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

<p style="color:#D2593F;"><img src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/article/000/465/014/169241191890148.jpg?x-oss-process=image/resize,p_40"  class="lazy" alt="Asymmetric encryption cryptography in Java" /><b></b></p>

You can now take the following steps to create program code −

  • We use the cipher class to create two different modes: encryption and decryption. The encryption key is the private key and the decryption key is the public key.

  • Call the doFinal() method on the cipher, which can perform a single-part operation on the data to encrypt/decrypt, or complete a multi-part operation and return a byte array.

  • Finally, we got the ciphertext after using ENCRYPT_MODE for encryption.

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

<p style="text-align: center; color: rgb(210, 89, 63);"><img src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/article/000/465/014/169241191871435.jpg?x-oss-process=image/resize,p_40"  class="lazy" alt="Asymmetric encryption cryptography in Java" /><b></b></p>

in conclusion

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

The above is the detailed content of Asymmetric encryption cryptography in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools