This article illustrates how Java generates asymmetric cryptographic public and private keys. Share to everyone for your reference. Specifically 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 plaintext, and this public key can not be reversed decryption, ciphertext sent to the server after the server with the private key to decrypt, so that the plaintext encrypted transmission.
Asymmetric encryption also has its inherent shortcomings, encryption, decryption slow control of its play, if you have a large number of text needs to be encrypted transmission, it is recommended that you through asymmetric encryption to the symmetric ' key ' distribution to the client, in time to update the symmetric ' key '.
Keyrsa.java is as follows:
Import java.io.*;
Import java.security.*;
Import javax.crypto.*;
Import javax.crypto.spec.*;
/** * RSA Asymmetric encryption of public and private keys * * * * * * * * 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; /** * constructor * @param in the specified key length (value range: 512~2048) * @throws nosuchalgorithmexception exception/public keyrsa (int in, Strin G address) throws NoSuchAlgorithmException, FileNotFoundException, ioexception {KPG = Keypairgenerator.getinstance (" RSA "); Create ' key pair ' generator kpg.initialize (in); Specifies the key length (value range: 512~2048) KP = Kpg.genkeypair (); Generate ' key pair ', which contains a public key and a private key information Public_key = Kp.getpublic (); Obtain public Key Private_key = Kp.getprivate (); Get private key//save 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 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 will help you with your Java programming.