Asymmetric encryption cryptography in Java
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/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/465/014/169241191890148.jpg" 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/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/465/014/169241191871435.jpg" 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to write a simple student performance report generator using Java? Student Performance Report Generator is a tool that helps teachers or educators quickly generate student performance reports. This article will introduce how to use Java to write a simple student performance report generator. First, we need to define the student object and student grade object. The student object contains basic information such as the student's name and student number, while the student score object contains information such as the student's subject scores and average grade. The following is the definition of a simple student object: public

How to write a simple student attendance management system using Java? With the continuous development of technology, school management systems are also constantly updated and upgraded. The student attendance management system is an important part of it. It can help the school track students' attendance and provide data analysis and reports. This article will introduce how to write a simple student attendance management system using Java. 1. Requirements Analysis Before starting to write, we need to determine the functions and requirements of the system. Basic functions include registration and management of student information, recording of student attendance data and

How to use Java programming to implement the address location search of the Amap API Introduction: Amap is a very popular map service and is widely used in various applications. Among them, the search function near the address location provides the ability to search for nearby POI (Point of Interest, points of interest). This article will explain in detail how to use Java programming to implement the address location search function of the Amap API, and use code examples to help readers understand and master related technologies. 1. Apply for Amap development

ChatGPTJava: How to build an intelligent music recommendation system, specific code examples are needed. Introduction: With the rapid development of the Internet, music has become an indispensable part of people's daily lives. As music platforms continue to emerge, users often face a common problem: how to find music that suits their tastes? In order to solve this problem, the intelligent music recommendation system came into being. This article will introduce how to use ChatGPTJava to build an intelligent music recommendation system and provide specific code examples. No.

How to use Java to implement the inventory statistics function of the warehouse management system. With the development of e-commerce and the increasing importance of warehousing management, the inventory statistics function has become an indispensable part of the warehouse management system. Warehouse management systems written in the Java language can implement inventory statistics functions through concise and efficient code, helping companies better manage warehouse storage and improve operational efficiency. 1. Background introduction Warehouse management system refers to a management method that uses computer technology to perform data management, information processing and decision-making analysis on an enterprise's warehouse. Inventory statistics are

How to use Java to implement breadth-first search algorithm Breadth-First Search algorithm (Breadth-FirstSearch, BFS) is a commonly used search algorithm in graph theory, which can find the shortest path between two nodes in the graph. BFS is widely used in many applications, such as finding the shortest path in a maze, web crawlers, etc. This article will introduce how to use Java language to implement the BFS algorithm, and attach specific code examples. First, we need to define a class for storing graph nodes. This class contains nodes

Astringisaclassof'java.lang'packagethatstoresaseriesofcharacters.ThosecharactersareactuallyString-typeobjects.Wemustenclosethevalueofstringwithindoublequotes.Generally,wecanrepresentcharactersinlowercaseanduppercaseinJava.And,itisalsopossibletoconver

IntroductionSymmetric encryption, also known as key encryption, is an encryption method in which the same key is used for encryption and decryption. This encryption method is fast and efficient and suitable for encrypting large amounts of data. The most commonly used symmetric encryption algorithm is Advanced Encryption Standard (AES). Java provides strong support for symmetric encryption, including classes in the javax.crypto package, such as SecretKey, Cipher, and KeyGenerator. Symmetric encryption in Java The JavaCipher class in the javax.crypto package provides cryptographic functions for encryption and decryption. It forms the core of the Java Cryptozoology Extensions (JCE) framework. In Java, the Cipher class provides symmetric encryption functions, and K
