Example of RSA encryption and decryption algorithm implemented by Java

  • 2021-01-03 20:53:28
  • OfStack

This paper introduces RSA encryption and decryption algorithm implemented by Java. To share for your reference, the details are as follows:


import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
public class RSAUtils{
 public static String makekeyfile(String pubkeyfile, String prikeyfile) {
  String result = " Failed to generate public and private key files ";
  try{
    // KeyPairGenerator Used to generate public-private key pairs based on RSA Algorithm generated object 
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    //  Initializes the key pair generator with a key size of 1024 position 
    gen.initialize(1024);
//    // Generate strongly random numbers 
//    SecureRandom random = new SecureRandom();
//    gen.initialize(1024,random);
    //  generate 1 Two key pairs, save in pair In the 
    KeyPair pair = gen.generateKeyPair();
    //  Get the private key 
    RSAPrivateKey priKey = (RSAPrivateKey) pair.getPrivate();
    //  To get the public key 
    RSAPublicKey pubKey = (RSAPublicKey) pair.getPublic();
    //  Generate a private key file 
    ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(prikeyfile));
    os.writeObject(priKey);
    os.flush();
    os.close();
    // Generate public key file 
    os = new ObjectOutputStream(new FileOutputStream(pubkeyfile));
    os.writeObject(pubKey);
    os.flush();
    os.close();
    result = " Generate public key file [ "+pubkeyfile+" 【 Generate private key file  】  "+prikeyfile+" 】 ";
  }catch(Exception e){
  e.printStackTrace();
  }
  return result;
  }
  public static void main(String[] args) {
  try{
    String pubfile = "F:/images/pub.key";
    String prifile = "F:/images/pri.key";
    String result = null;
    //result = makekeyfile(pubfile, prifile);
    result = markPuPra(pubfile, prifile);
    System.out.println(result);
  }catch(Exception e){
  e.printStackTrace();
  }
  }
  public static String markPuPra(String pubfile,String prifile){
  String results = " Encryption and decryption error ";
  try{
    ObjectInputStream os = new ObjectInputStream(new FileInputStream(pubfile));
    RSAPublicKey pubkey = (RSAPublicKey) os.readObject();
    os.close();
    os = new ObjectInputStream(new FileInputStream(prifile));
    RSAPrivateKey prikey = (RSAPrivateKey) os.readObject();
    os.close();
    String utf = "UTF-8";
    String msg = "## China %% ) @+_";
    //  Use the public key to encrypt the private key for decryption 
    System.out.println(" The original : " + msg);
    byte[] puk = handleData(pubkey, msg.getBytes(utf), 1);
    System.out.println(" Encrypted file data : " + new String(puk, utf));
    byte[] dpuk = handleData(prikey, puk, 0);
    System.out.println(" Decrypted file data : " + new String(dpuk, utf));
    msg = "jd# I 0 The RMB +=# new ";
    //  Encrypt the public key and decrypt it using the private key 
    System.out.println(" The original : " + msg);
    byte[] prk = handleData(prikey, msg.getBytes(utf), 1);
    System.out.println(" Encrypted file data : " + new String(prk, utf));
    byte[] dprk = handleData(pubkey, prk, 0);
    System.out.println(" Decrypted file data : " + new String(dprk, utf));
    results = " Encryption and decryption completed ";
  }catch(Exception e){
  e.printStackTrace();
  }
  return results;
  }
  /**
   *
   * @param k
   * @param data
   * @param encrypt 1  encryption  0 decryption 
   * @return
   * @throws Exception
   */
  public static byte[] handleData(Key key, byte[] data, int type) throws Exception {
    if (key != null) {
      Cipher ci = Cipher.getInstance("RSA");
      if (type == 1) {
        ci.init(Cipher.ENCRYPT_MODE, key);
        byte[] res = ci.doFinal(data);
        return res;
      }
      if (type == 0) {
        ci.init(Cipher.DECRYPT_MODE, key);
        byte[] res = ci.doFinal(data);
        return res;
      }
    }
    return null;
  }
}

PS: For those who are interested in encryption and decryption, please refer to our online tools:

Text online encryption and decryption tools (including AES, DES, RC4, etc.) :
http://tools.ofstack.com/password/txt_encode

MD5 Online encryption tools:
http://tools.ofstack.com/password/CreateMD5Password

Online hashing/hashing algorithm encryption tools:
http://tools.ofstack.com/password/hash_encrypt

Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 Encryption tools:
http://tools.ofstack.com/password/hash_md5_sha

Online sha1 sha224 / sha256 sha384 / sha512 encryption tools:
http://tools.ofstack.com/password/sha_encode

For more information about java, please refer to Java Math Skills Summary, Java Data Structure and Algorithm Tutorial, Java Character and String Manipulation Skills Summary, Java DOM Node Manipulation Skills Summary and Java Cache manipulation Skills Summary.

I hope this article has helped you with java programming.


Related articles: