Java method to generate asymmetric cryptographic public and private keys

  • 2020-04-01 04:00:33
  • OfStack

This article illustrates a Java method for generating asymmetric cryptographic public and private keys. Share with you for your reference. The details are as follows:

Asymmetric encryption is very suitable for the secret communication between multiple clients and servers. The client USES the same public key to encrypt the plaintext, but the public key cannot be decrypted in reverse. After the ciphertext is sent to the server, the server USES the private key to decrypt the ciphertext.
Asymmetric encryption also has its inherent shortcomings, encryption, decryption speed is slow to restrict its play, if you have a large number of text to encrypt the transmission, it is recommended that you use asymmetric encryption to distribute the symmetric 'key' to the client, timely update the symmetric 'key'.

KeyRSA. Java is as follows:


import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class KeyRSA {
 private KeyPairGenerator kpg = null;
 private KeyPair kp = null;
 private PublicKey public_key = null;
 private PrivateKey private_key = null;
 private FileOutputStream public_file_out = null;
 private ObjectOutputStream public_object_out = null;
 private FileOutputStream private_file_out = null;
 private ObjectOutputStream private_object_out = null;
 
 public KeyRSA(int in, String address) throws NoSuchAlgorithmException,
   FileNotFoundException, IOException {
  kpg = KeyPairGenerator.getInstance("RSA"); //Create the 'key pair' generator
  kpg.initialize(in); //Specify key length (value range: 512 ~ 2048)
  kp = kpg.genKeyPair(); //Generate a 'key pair' that contains information about a public key and a private key
  public_key = kp.getPublic(); //For public key
  private_key = kp.getPrivate(); //Get the private key
  //Save the public key
  public_file_out = new FileOutputStream(address + "/public_key.dat");
  public_object_out = new ObjectOutputStream(public_file_out);
  public_object_out.writeObject(public_key);
  //Save the private key
  private_file_out = new FileOutputStream(address + "/private_key.dat");
  private_object_out = new ObjectOutputStream(private_file_out);
  private_object_out.writeObject(private_key);
 }
 public static void main(String[] args) {
  try {
   new KeyRSA(1024, "c:/key_rsa");
  }
  catch (IOException ex) {
  }
  catch (NoSuchAlgorithmException ex) {
  }
 }
}

I hope this article has been helpful to your Java programming.


Related articles: