Home  >  Article  >  Java  >  Asymmetric encryption cryptography in Java

Asymmetric encryption cryptography in Java

王林
王林forward
2023-08-19 10:25:15523browse

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="https://img.php.cn/upload/article/000/465/014/169241191890148.jpg" 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="https://img.php.cn/upload/article/000/465/014/169241191871435.jpg" 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.com. If there is any infringement, please contact admin@php.cn delete