Asymmetric Encryption Cryptography in Java
Last Updated :
14 Jul, 2021
Cryptography is the study of different techniques to secure data from an unauthorized entity. In computer science, we try to develop strategies and practices for protecting sensitive data. Most of the cryptography involves very advanced Mathematical functions used for securing data. The sole purpose of the algorithms developed for cryptography is to hide data from the attacker or middleman.
In the previous article, we have studied the different methods, classes and approach to perform the symmetric encryption and decryption. In this article, we will understand asymmetric encryption.
Asymmetric Encryption also called as private/public key Encryption is a mathematical relation between two keys, one for encryption and the other for decryption. For example, if there are two keys "K1" and "K2", then if key "K1" is used for encryption and "K2" is used for decryption. If "K1" is used for decryption, then "K2" is used for encryption.
Before implementing the asymmetric encryption using the RSA algorithm, we will first see how to generate a keypair(public, private). The following steps can be followed in order to generate asymmetric key:
- We need to first generate public & private key using the SecureRandom class. SecureRandom class is used to generate random number.
SecureRandom random = new SecureRandom();
- The KeyGenerator class will provide getInstance() method which can be used to pass a string variable which denotes the Key Generation Algorithm. It returns KeyGenerator Object. We are using RSA algorithm for generating the keys.
KeyPairGenerator KPGenerator = KeyPairGenerator.getInstance(Key_Generation_Algorithm_string_variable);
- Initializing the keyGenerator object with 2048 bits key size and passing the random number.
keyPairGenerator.initialize(2048, secureRandom);
- Now, the secret key is generated and if we wish to actually see the generated key which is an object, we can convert it into hexbinary format using DatatypeConverter.
Below is the implementation of the above approach:
Java
// 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:
Encryption and Decryption using the asymmetric key: In the above steps, we have created the public & private keys for Encryption and Decryption. Now, let us implement Asymmetric Encryption using the RSA algorithm. The following steps can be followed in order to implement the encryption and decryption.
- The cipher class is used for two different modes the encryption and decryption. As Asymmetric encryption uses different keys, we use the private key for encryption and the public key for decryption.
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
- 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.
- Finally we get the Cipher text after Encryption with ENCRYPT_MODE.
Below is the implementation of the above approach:
Java
// 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:
Similar Reads
Symmetric Encryption Cryptography in Java Cryptography is the study of different techniques to secure data from an unauthorized entity. In computer science, we try to develop strategies and practices for protecting sensitive data. Most of the cryptography involves very advanced Mathematical functions used for securing data. The sole purpose
10 min read
Cryptographic Hash Function in Java Cryptographic Hash is a Hash function that takes random size input and yields a fixed-size output. It is easy to calculate but challenging to retrieve the original data. It is strong and difficult to duplicate the same hash with unique inputs and is a one-way function so revert is not possible. Hash
5 min read
What is Java AES Encryption and Decryption? Java has introduced a new approach in the technology sector as a programming language. Java takes the top spot of technologies used for coding. A Java application design firm can do everything from comprehensive business software to apps for mobile phones and wireless devices. Omnipresent of this So
5 min read
Database encryption in Java Basically, encryption is the process or conversion of user data in code or more specifically in the cyphertext form in order to prevent unauthorized access, So, encryption is very much important in today's world where we all are working on large datasets stored in databases and the credentials of th
4 min read
Encrypt and Decrypt Image using Java Encryption is the process of converting information or data into a secrete code, especially to prevent unauthorized access. In these cases also we will do the same, For encryption, we will convert the image into a byte array and after converting it we will apply XOR operation on each value of the by
5 min read
Java implementation of Digital Signatures in Cryptography Digital Signatures are an Asymmetrically encrypted hash of a digital message(data). It is a value that can provide a guarantee of authenticity, non-repudiation, and integrity. In other terms, it means you can verify the sender, date & time and message content have not been revealed or compromise
4 min read