Examples of RSA encryption and decryption in Java

Source: Internet
Author: User
Tags decrypt decrypt text asymmetric encryption

Encryption is one of the means to ensure data security. Encryption is the conversion of plain text data into unintelligible ciphertext; decryption is the conversion of ciphertext back to plain text.
The encryption and decryption of data belong to the category of cryptography. In general, encryption and decryption require the use of secret information, which is called a key, which is used to convert plain text into ciphertext or back.
Symmetric encryption refers to the encryption and decryption method that the sender and receiver share the same key.
Asymmetric encryption (also known as public key encryption) refers to the need for a private key to a public key, two different encryption and decryption system of the key. Although different, the two parts of the key pair are associated with the algorithm. One key encrypts plaintext, and the other decrypts the ciphertext. There is no key to the encryption and encryption of the function to complete their own. The public key, or the key used to encrypt the data, can be freely distributed.
RSA is one of the algorithms of public key cryptography based on large integer decomposition. RSA represents Ron Rivest, Adi Shamir, and Leonard Adleman,rsa, the three of whom were raised together.
The following example shows how to use the RSA algorithm to decrypt information in Java.
An instance of the Java.security.KeyPairGenerator class is used to generate a public and private key pair for an RSA algorithm, which is then saved to a file.
An instance of the Javax.crypto.Cipher class is used to decrypt the information using the key pair generated above.
Import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.security.keypair;import Java.security.keypairgenerator;import Java.security.nosuchalgorithmexception;import Java.security.privatekey;import Java.security.PublicKey;import javax.crypto.cipher;/** * @author javadigest * */public class Encryptionutil {/** * String to hold name of the ENCRYP   tion algorithm.  */public static final String algorithm = "RSA";   /** * String to hold the name of the private key file.  */public static final String private_key_file = "C:/keys/private.key";   /** * String to hold name of the public key file.  */public static final String public_key_file = "C:/keys/public.key"; /** * Generate key which contains a pair of private and public key using the 1024x768 * bytes.   Store the set of keys in Prvate.key and Public.key files. *   * @throws nosuchalgorithmexception * @throws ioexception * @throws filenotfoundexception */public static void G      Eneratekey () {try {final keypairgenerator KeyGen = keypairgenerator.getinstance (algorithm);      Keygen.initialize (1024);      Final KeyPair key = Keygen.generatekeypair ();      File Privatekeyfile = new file (private_key_file);      File Publickeyfile = new file (public_key_file); Create files to store public and private key if (privatekeyfile.getparentfile () = null) {privatekeyfile.g      Etparentfile (). Mkdirs ();      } privatekeyfile.createnewfile ();      if (publickeyfile.getparentfile () = null) {Publickeyfile.getparentfile (). Mkdirs ();      } publickeyfile.createnewfile (); Saving the public key in a file ObjectOutputStream Publickeyos = new ObjectOutputStream (New FILEOUTPUTST      Ream (Publickeyfile));      Publickeyos.writeobject (Key.getpublic ());      Publickeyos.close (); Saving the Private keY in a file objectoutputstream Privatekeyos = new ObjectOutputStream (new FileOutputStream (Privatekeyfile));      Privatekeyos.writeobject (Key.getprivate ());    Privatekeyos.close ();    } catch (Exception e) {e.printstacktrace ();   }}/** * The method checks if the pair of public and private key has been generated.   * * @return flag indicating if the pair of keys were generated.    */public static Boolean arekeyspresent () {File Privatekey = new File (private_key_file);    File PublicKey = new file (public_key_file);    if (privatekey.exists () && publickey.exists ()) {return true;  } return false;   }/** * Encrypt The Plain text using public key. * * @param text *: Original plain text * @param key *: The public key * @return Encrypted TE  XT * @throws Java.lang.Exception */public static byte[] Encrypt (String text, PublicKey key) {byte[] ciphertext =    Null try {//Get an RSA cipher obJect and print the provider final Cipher Cipher = cipher.getinstance (algorithm);      Encrypt the plain text using the public key Cipher.init (Cipher.encrypt_mode, key);    ciphertext = Cipher.dofinal (Text.getbytes ());    } catch (Exception e) {e.printstacktrace ();  } return ciphertext;   }/** * Decrypt text using private key. * * @param text *: Encrypted text * @param key *: The private key * @return Plain text * @t Hrows java.lang.Exception */public static String decrypt (byte[] text, Privatekey key) {byte[] Dectyptedtext = null    ;      try {//Get an RSA cipher object and print the provider final cipher cipher = cipher.getinstance (algorithm);      Decrypt the text using the private key Cipher.init (Cipher.decrypt_mode, key);    Dectyptedtext = cipher.dofinal (text);    } catch (Exception ex) {ex.printstacktrace ();  } return new String (Dectyptedtext); }/** * Test the Encryptionutil */ public static void Main (string[] args) {try {//Check if the pair of keys is present else generate those. if (!arekeyspresent ()) {//Method generates a pair of keys using the RSA algorithm and stores it//in th      EIR respective files GenerateKey ();      } final String originaltext = "Text to is encrypted";      ObjectInputStream inputstream = null;       Encrypt the string using the public key InputStream = new ObjectInputStream (new FileInputStream (Public_key_file));      Final PublicKey PublicKey = (publickey) inputstream.readobject ();      Final byte[] ciphertext = Encrypt (Originaltext, publickey);      Decrypt the cipher text using the private key.      InputStream = new ObjectInputStream (new FileInputStream (Private_key_file));      Final Privatekey Privatekey = (privatekey) inputstream.readobject ();      Final String plaintext = decrypt (ciphertext, privatekey); Printing the Original, Encrypted and decrypted Text SystEm.out.println ("Original:" + originaltext);      System.out.println ("Encrypted:" +ciphertext.tostring ());    System.out.println ("decrypted:" + plaintext);    } catch (Exception e) {e.printstacktrace (); }  }}


Original link: https://javadigest.wordpress.com/2012/08/26/rsa-encryption-example/.

Examples of RSA encryption and decryption in Java

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.