Example of the RSA encryption and decryption algorithm implemented in Java, rsa encryption and decryption

Source: Internet
Author: User

Example of the RSA encryption and decryption algorithm implemented in Java, rsa encryption and decryption

This example describes the RSA encryption and decryption algorithm implemented in Java. We will share this with you 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 file";
Try{
//Keypairgenerator is used to generate public and private key pairs and generate objects based on RSA algorithm
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
//Initializes the key pair generator with a key size of 1024 bits
gen.initialize(1024);
/// / generate strong random number
//    SecureRandom random = new SecureRandom();
//    gen.initialize(1024,random);
//Generate a key pair and save it in pair
KeyPair pair = gen.generateKeyPair();
//Get private key
RSAPrivateKey priKey = (RSAPrivateKey) pair.getPrivate();
//Get public key
RSAPublicKey pubKey = (RSAPublicKey) pair.getPublic();
//Generate 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 = "error in encryption and decryption";
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 = “##% of China's”
//Decryption using public key encryption private key
System. Out. Println ("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: our RMB people + = (New)";
//Use private key to encrypt public key to decrypt
System. Out. Println ("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 encrypt 0 decrypt
* @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: if you are interested in encryption and decryption, refer to the online tools on this site:

Online text encryption and decryption tools (including AES, DES, and RC4 ):
Http://tools.jb51.net/password/txt_encode

MD5 online encryption tool:
Http://tools.jb51.net/password/CreateMD5Password

Online hash/hash algorithm encryption tool:
Http://tools.jb51.net/password/hash_encrypt

Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 encryption tools:
Http://tools.jb51.net/password/hash_md5_sha

Online sha1/shaloud/sha256/sha384/sha512 encryption tool:
Http://tools.jb51.net/password/sha_encode


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.