RSA Encryption Decryption

Source: Internet
Author: User
Tags modulus

Http://files.cnblogs.com/files/liuJava/rsa.zip,

Directly on the tool class JAR and the foreground JS are in the link above

Package My.tools.security;import Java.io.file;import Java.io.fileinputstream;import java.io.FileOutputStream; Import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.math.biginteger;import Java.security.keypair;import Java.security.keyfactory;import Java.security.keypairgenerator;import Java.security.provider;import Java.security.publickey;import Java.security.privatekey;import Java.security.securerandom;import Java.security.nosuchalgorithmexception;import Java.security.invalidparameterexception;import Java.security.interfaces.rsapublickey;import Java.security.interfaces.rsaprivatekey;import Java.security.spec.rsapublickeyspec;import Java.security.spec.rsaprivatekeyspec;import Java.security.spec.invalidkeyspecexception;import Javax.crypto.cipher;import Org.apache.commons.io.ioutils;import Org.apache.commons.io.fileutils;import Org.apache.commons.codec.decoderexception;import Org.apache.commons.codec.binary.hex;import Org.bouncycastle.jce.provider.BouncyCastleProviDer;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.apache.commons.lang.stringutils;import org.apache.commons.lang.time.dateformatutils;/** * RSA algorithm encryption/Decryption tool class. * * @author Fuchun * @version 1.0.0, 2010-05-05 */public abstract class Rsautils {private static final Logger Logger    = Loggerfactory.getlogger (Rsautils.class);    /** algorithm name */private static final String Algorithom = "RSA"; /** Save the file name of the generated key pair.    */private static final String Rsa_pair_filename = "/__rsa_pair.txt";    /** Key size */private static final int key_size = 1024;    /** Default Security Service provider */private static final Provider Default_provider = new Bouncycastleprovider ();    private static Keypairgenerator Keypairgen = null;    private static keyfactory keyfactory = null; /** the cached key pair.    */private static KeyPair Onekeypair = null;    private static File rsapairfile = null;            static {try {Keypairgen = keypairgenerator.getinstance (Algorithom, Default_provider); Keyfactory= Keyfactory.getinstance (Algorithom, Default_provider);        } catch (NoSuchAlgorithmException ex) {Logger.error (Ex.getmessage ());    } rsapairfile = new File (Getrsapairfilepath ());     Private Rsautils () {}/** * generates and returns an RSA key pair. */private static synchronized KeyPair Generatekeypair () {try {keypairgen.initialize (key_size, new            SecureRandom (Dateformatutils.format ("YyyyMMdd"). GetBytes ());            Onekeypair = Keypairgen.generatekeypair ();            Savekeypair (Onekeypair);        return onekeypair; } catch (Invalidparameterexception ex) {Logger.error ("Keypairgenerator does not support a key length of" + KE        Y_size + ".", ex); } catch (NullPointerException ex) {Logger.error ("Rsautils#key_pair_gen is null, can not generate Keypairgenera        Tor instance. ", ex);    } return null;     }/** * Returns the path of the generated/read key pair file. */private static String GETRSAPAIRFIlepath () {String URLPath = RSAUtils.class.getResource ("/"). GetPath ();    Return (new File (URLPath). GetParent () + rsa_pair_filename);     }/** * If you need to create a new key pair file, return {@code true}, otherwise {@code false}.        */Private static Boolean Iscreatekeypairfile () {//whether to create a new key pair file, Boolean createnewkeypair = false;        if (!rsapairfile.exists () | | rsapairfile.isdirectory ()) {Createnewkeypair = true;    } return Createnewkeypair;     /** * Saves the specified RSA key pair as a file.     * * @param keyPair the key pair to be saved.        */private static void Savekeypair (KeyPair KeyPair) {FileOutputStream fos = null;        ObjectOutputStream oos = null;            try {fos = Fileutils.openoutputstream (rsapairfile);            Oos = new ObjectOutputStream (FOS);        Oos.writeobject (KeyPair);        } catch (Exception ex) {ex.printstacktrace ();            } finally {ioutils.closequietly (oos);        ioutils.closequietly (FOS);}}/** * Returns the RSA key pair.  */public static KeyPair Getkeypair () {///first determine if a new key pair file needs to be regenerated if (Iscreatekeypairfile ()) {//            Directly forces the key pair file to be generated and stored in the cache.        return Generatekeypair ();        } if (Onekeypair! = null) {return onekeypair;    } return Readkeypair ();        }//synchronously read out the saved key pair private static KeyPair Readkeypair () {FileInputStream FIS = null;        ObjectInputStream ois = null;            try {fis = Fileutils.openinputstream (rsapairfile);            OIS = new ObjectInputStream (FIS);            Onekeypair = (KeyPair) ois.readobject ();        return onekeypair;        } catch (Exception ex) {ex.printstacktrace ();            } finally {ioutils.closequietly (OIS);        ioutils.closequietly (FIS);    } return null;     /** * Constructs an RSA-specific public key object based on a given coefficient and a dedicated exponent.     * * @param modulus coefficient.     * @param publicexponent Special index.     * @return RSA private Public Key object. */PublIC Static Rsapublickey Generatersapublickey (byte[] modulus, byte[] publicexponent) {Rsapublickeyspec PublicKeySpec        = new Rsapublickeyspec (new BigInteger (modulus), new BigInteger (publicexponent));        try {return (Rsapublickey) keyfactory.generatepublic (PUBLICKEYSPEC);        } catch (Invalidkeyspecexception ex) {Logger.error ("Rsapublickeyspec is unavailable.", ex); } catch (NullPointerException ex) {Logger.error ("rsautils#key_factory is null, can not generate Keyfactory ins        Tance. ", ex);    } return null;     /** * Constructs an RSA private key object based on the given coefficients and the dedicated exponent.     * * @param modulus coefficient.     * @param privateexponent Special index.     * @return RSA private Key object.  */public static Rsaprivatekey Generatersaprivatekey (byte[] modulus, byte[] privateexponent) {Rsaprivatekeyspec        Privatekeyspec = new Rsaprivatekeyspec (new BigInteger (modulus), new BigInteger (privateexponent)); try {return (Rsaprivatekey) keyfactory.generateprivate (PRIVATEKEYSPEC);        } catch (Invalidkeyspecexception ex) {Logger.error ("Rsaprivatekeyspec is unavailable.", ex); } catch (NullPointerException ex) {Logger.error ("rsautils#key_factory is null, can not generate Keyfactory ins        Tance. ", ex);    } return null;     /** * Constructs an RSA private key object based on a given 16-factor and a dedicated exponential string.     * * @param modulus coefficient.     * @param privateexponent Special index.     * @return RSA private Key object. */public static Rsaprivatekey Getrsaprivatekey (String hexmodulus, String hexprivateexponent) {if (stringutils.i Sblank (hexmodulus) | | Stringutils.isblank (hexprivateexponent)) {if (logger.isdebugenabled ()) {Logger.debug ("Hexmodulu S and hexprivateexponent cannot be empty.            Rsaprivatekey value is a null to return. ");        return null;        } byte[] modulus = null;        byte[] privateexponent = null; try {modulus = hex.deCodehex (Hexmodulus.tochararray ());        Privateexponent = Hex.decodehex (Hexprivateexponent.tochararray ()); } catch (Decoderexception ex) {logger.error ("Hexmodulus or hexprivateexponent value is invalid.        return null (Rsaprivatekey). "); if (modulus = null && privateexponent! = null) {return Generatersaprivatekey (modulus, privateexponent)        ;    } return null;     /** * Constructs an RSA-specific public key object based on a given 16-factor and a dedicated exponential string.     * * @param modulus coefficient.     * @param publicexponent Special index.     * @return RSA private Public Key object. */public static Rsapublickey Getrsapublidkey (String hexmodulus, String hexpublicexponent) {if (STRINGUTILS.ISBL Ank (hexmodulus) | |  Stringutils.isblank (hexpublicexponent)) {if (logger.isdebugenabled ()) {Logger.debug ("Hexmodulus And hexpublicexponent cannot be empty.            return null (Rsapublickey). ");        return null;        } byte[] modulus = null; byte[] publicexponent = null;            try {modulus = Hex.decodehex (Hexmodulus.tochararray ());        Publicexponent = Hex.decodehex (Hexpublicexponent.tochararray ()); } catch (Decoderexception ex) {logger.error ("Hexmodulus or hexpublicexponent value is invalid.        return null (Rsapublickey). ");        if (modulus! = NULL && publicexponent! = null) {return Generatersapublickey (modulus, publicexponent);    } return null;     /** * Encrypts data using the specified public key.     * * @param publickey the given public key.     * @param data to be encrypted.     * @return the encrypted data. */public static byte[] Encrypt (PublicKey publickey, byte[] data) throws Exception {Cipher ci = Cipher.getinsta        NCE (Algorithom, Default_provider);        Ci.init (Cipher.encrypt_mode, PublicKey);    return ci.dofinal (data);     /** * Decrypts data using the specified private key.     * * @param privatekey the given private key.     * @param data to decrypt.     * @return the original data. */public static byte[] Decrypt (PrivaTekey Privatekey, byte[] data) throws Exception {Cipher ci = cipher.getinstance (Algorithom, Default_provider);        Ci.init (Cipher.decrypt_mode, Privatekey);    return ci.dofinal (data);     /** * Encrypts the given string with the given public key.     * <p/> * If {@code PublicKey} is {@code null}, or {@code plaintext} is {@code null} then return {@code * null}.     * * @param publickey the given public key.     * @param plaintext string.     * @return ciphertext for a given string. */public static String encryptstring (PublicKey publickey, string plaintext) {if (PublicKey = null | | plaintex        T = = null) {return null;        } byte[] data = Plaintext.getbytes ();            try {byte[] En_data = Encrypt (publickey, data);        return new String (Hex.encodehex (en_data));        } catch (Exception ex) {Logger.error (Ex.getcause (). GetMessage ());    } return null;     /** * Encrypts the given string with the default public key. * <p/> * If {@code plaintext} is {@code null} then return {@code NULL}.     * * @param plaintext string.     * @return ciphertext for a given string.        */public static String encryptstring (string plaintext) {if (plaintext = = null) {return null;        } byte[] data = Plaintext.getbytes ();        KeyPair KeyPair = Getkeypair ();            try {byte[] En_data = Encrypt ((rsapublickey) keypair.getpublic (), data);        return new String (Hex.encodehex (en_data));        } catch (NullPointerException ex) {logger.error ("KeyPair cannot be null.");        } catch (Exception ex) {Logger.error (Ex.getcause (). GetMessage ());    } return null;     /** * Decrypts the given string with the given private key.     * <p/> * Returns {@code null} if the private key is {@code null}, or {@code null} or an empty string {@code Encrypttext}.     * Returns {@code null} when the private key does not match.     * * @param privatekey the given private key.     * @param encrypttext ciphertext.     * @return the original string. */public static string decryptstring (Privatekey Privatekey, string encrypttext) {if (Privatekey = =null | |        Stringutils.isblank (Encrypttext)) {return null;            } try {byte[] En_data = Hex.decodehex (Encrypttext.tochararray ());            byte[] data = Decrypt (Privatekey, en_data);        return new String (data); } catch (Exception ex) {Logger.error (String.Format ("\"%s\ "decryption failed.        Cause:%s ", Encrypttext, Ex.getcause (). GetMessage ()));    } return null;     /** * Decrypts the given string using the default private key.     * <p/> * Returns {@code null} if {@code Encrypttext} is {@code null} or an empty string.     * Returns {@code null} when the private key does not match.     * * @param encrypttext ciphertext.     * @return the original string. */public static String decryptstring (string encrypttext) {if (Stringutils.isblank (Encrypttext)) {RE        Turn null;        } KeyPair KeyPair = Getkeypair ();            try {byte[] En_data = Hex.decodehex (Encrypttext.tochararray ());            byte[] data = Decrypt ((Rsaprivatekey) keypair.getprivate (), en_data); REturn new String (data);        } catch (NullPointerException ex) {logger.error ("KeyPair cannot be null."); } catch (Exception ex) {Logger.error (String.Format ("\"%s\ "decryption failed.        Cause:%s ", Encrypttext, Ex.getmessage ()));    } return null;     /** * uses the default private key to decrypt strings that are encrypted by JS encryption (using the public key provided by this class).     * * @param encrypttext ciphertext.     * @return The original string of {@code Encrypttext}.        */public static string Decryptstringbyjs (String encrypttext) {string text = decryptstring (encrypttext);        if (text = = null) {return null;    } return Stringutils.reverse (text); /** returns the default public key that has been initialized.        */public static Rsapublickey Getdefaultpublickey () {KeyPair KeyPair = Getkeypair ();        if (KeyPair! = null) {return (Rsapublickey) keypair.getpublic ();    } return null; /** returns the default private key that has been initialized. */public static Rsaprivatekey Getdefaultprivatekey () {KeyPair KeyPair = Getkeypair();        if (KeyPair! = null) {return (Rsaprivatekey) keypair.getprivate ();    } return null; }}

  

Use the following: or directly in the Java test:

public static void Main (string[] args) {Rsapublickey PublicKey = Rsautils.getdefaultpublickey ();        char[] Encodehex = Hex.encodehex (Publickey.getpublicexponent (). Tobytearray ());        string exponent = new String (Encodehex);        char[] EncodeHex2 = Hex.encodehex (Publickey.getmodulus (). Tobytearray ());        String Modulus=new string (ENCODEHEX2);        String encryptstring = rsautils.encryptstring (publickey, "Hello Ah ah ah");        System.out.println (encryptstring);           String decryptstringbyjs = Rsautils.decryptstringbyjs (encryptstring);        char[] Chararray = Decryptstringbyjs.tochararray ();        String resultstring = "";         for (int i=chararray.length-1; i>=0; i--) {             resultstring + = Chararray[i];           }         System.out.println (resultstring);           }

When encrypting some data that needs to be encrypted in a Web project

Background distribution secret key

Rsapublickey PublicKey = Rsautils.getdefaultpublickey ();        char[] Encodehex = Hex.encodehex (Publickey.getpublicexponent (). Tobytearray ());        string exponent = new String (Encodehex);        Actioncontext.getcontext (). Put ("exponent", exponent);         Actioncontext.getcontext (). put ("modulus", New String (Hex.encodehex (Publickey.getmodulus (). Tobytearray ())));

  

Demonstrates the process of JS request background key

function DLs () {///These 2 are the requested    var modulus = $ ("#modulus"). Val (), exponent = $ ("#exponentid"). Val (); var key = Rsaut Ils.getkeypair (Exponent, "", modulus);p wd2 = rsautils.encryptedstring (Key, $ ("#passwordid"). Val ()); $ ("#passwordid") . Val (pwd2) document.getElementById ("Formid"). Submit ();   }

The process of background decryption

Decryption: Password = rsautils.decryptstringbyjs (password);

  

RSA Encryption Decryption

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.