
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
KeyPairGenerator generateKeyPair Method in Java
A key pair can be generated using the generateKeyPair() method in the class java.security.KeyPairGenerator. This method requires no parameters and it returns the key pair that is generated. Every time the generateKeyPair() method is called, it generates a new key pair.
A program that demonstrates this is given as follows −
Example
import java.security.*; import java.util.*; public class Demo { public static void main(String[] argv) throws Exception { try { KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = kpGenerator.generateKeyPair(); System.out.println(keyPair); } catch (NoSuchAlgorithmException e) { System.out.println("Error!!! NoSuchAlgorithmException"); } } }
Output
java.security.KeyPair@12a3a380
Now let us understand the above program.
A key pair is generated using the generateKeyPair() method and then this key pair is displayed. If the algorithm is wrong, then the exception of NoSuchAlgorithmException is thrown. A code snippet that demonstrates is given as follows −
try { KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = kpGenerator.generateKeyPair(); System.out.println(keyPair); } catch (NoSuchAlgorithmException e) { System.out.println("Error!!! NoSuchAlgorithmException"); }
Advertisements