How to Generate, use and store public and private keys in java

Posted By : Neha Yadav | 26-Aug-2019

Overview

 

Java has a security package  i.e. java.security for generation of private keys and their respective public keys.

This package has classes for the generation of different types of public and private key pairs based on alogrithm you want to use. Private keys need to be stored safely. And public can be distributed for further usage in public.

 

We can use the public key for various modes of use, some are the following:-

Encryption:- Public key will encrypt the data and only private can decrypt that.

 

Authentication:- Public key decrypting the data which is encrypted via public key thus proving who the data come from.

 

We can store the public and private keys in a file or in any database as per our requirement. 

 

We can sign data using private key and verify it using the public key. For this we create a Signature class object with the process of signature making we are using for it (like "SHA256WithRSA"). After this, we initialize the signature object with private key and update it with the data. And we create a signature. Then on the other hand, when we have to verify that data, we again create the Signature class object with the same algo procedure( "SHA256WithRSA"). Then we initialize with the public key for verification and update it with data. And we generate the signature and match it with the one we make with private key. If they matched this means data is verified.

 

We can understand this with an example:-

Program:-

import java.security.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

class GeneratePrivateKeys{

public static void main(String... args){

try{

// Make object of key pair generator using RSA algorithm
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
System.out.println("KeyPairGenerator  Object :- "+kpg);
OutputStream out;
//set size of key
kpg.initialize(2048);

//generate pair of public and private keys
KeyPair kp = kpg.generateKeyPair();

//make public and private keys
Key pub = kp.getPublic();
Key pvt = kp.getPrivate();

System.out.println("Generated Public key :- "+pub);
System.out.println("Generated Private key :- "+pvt);

//saving keys in binary format

String outFile = "public";
out = new FileOutputStream(outFile + ".key");
out.write(pvt.getEncoded());
out.close();
 
out = new FileOutputStream(outFile + ".pub");
out.write(pvt.getEncoded());
out.close();

System.err.println("Private key format in which it is created: " + pvt.getFormat());
// prints "Private key format"
 
System.err.println("Public key format in which it is created: " + pub.getFormat());
// prints "Public key format"

}

catch(NoSuchAlgorithmException e){

System.out.println(e);
}

catch(FileNotFoundException e){

System.out.println(e);
}

catch(IOException e){

System.out.println(e);
}


catch(Exception e){
System.out.println(e);
}

}

}

Output:- 

root@root:~/java/$ javac GeneratePrivateKeys.java 
root@root:~/java/$ java GeneratePrivateKeys 
KeyPairGenerator  Object :- java.security.KeyPairGenerator$Delegate@1ddc4ec2
Generated Public key :- Sun RSA public key, 2048 bits
  params: null
  modulus: 19786162606546395674924604801283005166628377478149704913237264715816698928176232555064602190112942853706152602785943933302153543121937666224354107073182919356819587430793715186706331178540719067247243275947034973620037059875574806606688149670686160617489230220961184774424553365224911812127842144644875202336710060927847471032773890396601260061882230324996832041215851026974094759574439063739065867250259041618800458571886948412906213914945938277470593451118580941128691212859806717539904540799353383114486568809498530001851191143339371805481075340171441649212738366815532797056002028354607378051989490555454960966889
  public exponent: 65537
 
Generated Private key :- SunRsaSign RSA private CRT key, 2048 bits
  params: null
  modulus: 19786162606546395674924604801283005166628377478149704913237264715816698928176232555064602190112942853706152602785943933302153543121937666224354107073182919356819587430793715186706331178540719067247243275947034973620037059875574806606688149670686160617489230220961184774424553365224911812127842144644875202336710060927847471032773890396601260061882230324996832041215851026974094759574439063739065867250259041618800458571886948412906213914945938277470593451118580941128691212859806717539904540799353383114486568809498530001851191143339371805481075340171441649212738366815532797056002028354607378051989490555454960966889
  private exponent: 34719451603717526017613402385637816716698405633263897722237597728289674180085550816064654345835000506221028568905863135782041556052654708268622645428018306087160726834326826776801319644356358892433785140209485053730019101968217995327359159133449936234665326081610941133387607565205378006236200110382847067590652489051093731410550429513741551019352888522557237859204122924332364073391136185461286921315280700607734049620287516976586816037065416796039902616181097285276253966635631831200224327495622961905199515342494247480487459382553759074142853608564648697643643413458049977604455119583083976669995101200762830593
Private key format: PKCS#8
Public key format: X.509

About Author

Author Image
Neha Yadav

Neha is a creative person. She is having good knowledge of core java, advance java, hibernate,spring boot. She likes to solve puzzles, sudoku. She is a fun loving person.

Request for Proposal

Name is required

Comment is required

Sending message..