A simple case of RSA encryption algorithm

Source: Internet
Author: User
Tags decrypt getmessage modulus

RSA encryption algorithm is the most influential public key encryption algorithm, it can resist the most known password attacks so far.

What are the applications of RSA encryption algorithms? Here's a case for database authentication.

When using the data set for authentication, the password exists in the database, the authentication user entered the password and the password in the database is the same authentication passed, if the database is cracked the system poses a threat, how to ensure the security of the system? The RSA encryption algorithm can be applied here to encrypt the permissions.

Ideas:

is to pass the user name password in the URL, first flip the user name, and then encrypt, such as the input password is 12, the actual background to encrypt the value of 21, and then verify with the database, so you can avoid the database is cracked check see is 21 plus password, landing system to 21 is unable to log on successfully.

Take the report software Finereport as an example, this is a can read all kinds of database report software, sub-client and front-end display.

Implementation scenarios:

1, the RSA encrypted use of the third-party package, put in the Project Web-inf/lib folder can be.

2. Call JS file

RSA folder for the front-end JS encryption needs to call JS file, so you need to put barrett.js, Bigint.js, rsa.js into the project directory such as: Webreport/js, new JS folder into the JS file.

3. Define RSA Encryption Class

Define the Rsautil.java class file, run the class Generatekeypair () method first, will generate a random RSAKey.txt file in Server D, save the public key and the key, each time this method is accessed will refresh the TXT file.

Package Com.fr.privilege;import Java.io.bytearrayoutputstream;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.math.biginteger;import Java.security.keyfactory;import Java.security.keypair;import Java.security.keypairgenerator;import Java.security.nosuchalgorithmexception;import Java.security.PrivateKey; Import Java.security.publickey;import Java.security.securerandom;import Java.security.interfaces.RSAPrivateKey; Import Java.security.interfaces.rsapublickey;import Java.security.spec.invalidkeyspecexception;import Java.security.spec.rsaprivatekeyspec;import Java.security.spec.rsapublickeyspec;import javax.crypto.Cipher;/** * RSA Tool class. Provides encryption, decryption, and generation of key equivalence methods. * Need to download Bcprov-jdk14-123.jar to http://www.bouncycastle.org. * */public class Rsautil {/** * * Generate key Pair * * * @return KeyPair * * @throws encryptexception */public static KeyPair Gener Atekeypair () throws Exception {try {keypairgenerator Keypairgen = KeyPairGenerator.getinstance ("RSA", New Org.bouncycastle.jce.provider.BouncyCastleProvider ()); final int key_size = 1024;// Nothing to say, this value is related to the size of the block encryption, can be changed, but not too large, otherwise the efficiency will be low keypairgen.initialize (key_size, New SecureRandom ()); KeyPair KeyPair = Keypairgen.generatekeypair (); Savekeypair (KeyPair); return KeyPair;} catch (Exception e) {throw new Exception (E.getmessage ());}} public static KeyPair Getkeypair () throws Exception {FileInputStream fis = new FileInputStream ("C:/rsakey.txt"); O Bjectinputstream Oos = new ObjectInputStream (FIS); KeyPair KP = (KeyPair) oos.readobject (); Oos.close (); Fis.close (); return KP;} public static void Savekeypair (KeyPair kp) throws Exception {FileOutputStream fos = new FileOutputStream ("C:/rsakey.txt") ; ObjectOutputStream oos = new ObjectOutputStream (FOS);//Generate Key Oos.writeobject (KP); Oos.close (); Fos.close ();} /** * * Generate public key * * * @param modulus * * @param publicexponent * * @return rsapublickey * * @throws Exception */public Stati C Rsapublickey Generatersapublickey (byte[] modulus,byte[] PubliCexponent) throws Exception {Keyfactory Keyfac = null;try {KEYFAC = keyfactory.getinstance ("RSA", new Org.bouncycastle.jce.provider.BouncyCastleProvider ());} catch (NoSuchAlgorithmException ex) {throw new Exception (Ex.getmessage ());} Rsapublickeyspec Pubkeyspec = new Rsapublickeyspec (new BigInteger (modulus), new BigInteger (publicexponent)); try { Return (Rsapublickey) keyfac.generatepublic (PUBKEYSPEC);} catch (Invalidkeyspecexception ex) {throw new Exception (Ex.getmessage ());}} /** * * Generate private key * * * @param modulus * * @param privateexponent * * @return rsaprivatekey * * @throws Exception */public STA Tic Rsaprivatekey Generatersaprivatekey (byte[] modulus,byte[] privateexponent) throws Exception {Keyfactory KeyFac = null;try {KEYFAC = keyfactory.getinstance ("RSA", New Org.bouncycastle.jce.provider.BouncyCastleProvider ());} catch ( NoSuchAlgorithmException ex) {throw new Exception (Ex.getmessage ());} Rsaprivatekeyspec Prikeyspec = new Rsaprivatekeyspec (new BigInteger (modulus), new BigInteger (privateExponent)); try {return (Rsaprivatekey) keyfac.generateprivate (PRIKEYSPEC);} catch (Invalidkeyspecexception ex) {throw New Exception (Ex.getmessage ());}} /** * * Encryption * * * * @param key * Encrypted key * * @param data * PlainText data to be encrypted * * @return Encrypted data * * @throws EXCEP tion */public static byte[] Encrypt (PublicKey PK, byte[] data) throws Exception {try {Cipher Cipher = cipher.getinstance (" RSA ", New Org.bouncycastle.jce.provider.BouncyCastleProvider ()); Cipher.init (Cipher.encrypt_mode, PK); int blockSize = Cipher.getblocksize ();//Obtain an encrypted block size, such as: 128 byte before encryption, and key_size=1024//encryption block size of 127//byte, encrypted after 128 byte; so there are 2 encryption blocks, First 127//byte The second is 1 byteint outputsize = cipher.getoutputsize (data.length);//Get encrypted block encrypted after block size int leavedsize = data.length% Blocksize;int blockssize = leavedsize! = 0? Data.length/blocksize + 1:data.length/blocksize;byte[] Raw = new Byte[outputsize * Blockssize];int i = 0;while (data. Length-i * blockSize > 0) {if (Data.length-i * blockSize > BlockSize) cipher.dofinal (daTA, I * blockSize, blockSize, Raw, i* outputsize); elsecipher.dofinal (data, I * blockSize, data.length-i* blockSize, Raw, I * outputsize);//This inside DoUpdate method is not available, after viewing the source code found after each doupdate and there is no actual action except to put byte[] in//Bytearrayoutputstream, And finally dofinal all the byte[] to encrypt, but at this time the size of the encryption block is likely to have exceeded//outputsize so had to use dofinal method. i++;} return raw;} catch (Exception e) {throw new Exception (E.getmessage ());}} /** * * Decrypt * * * * @param key * decrypted keys * * @param RAW * Encrypted data * * @return decrypted plaintext * * @throws Excepti On */public Static byte[] Decrypt (Privatekey PK, byte[] raw) throws Exception {try {Cipher Cipher = cipher.getinstance ("RS A ", New Org.bouncycastle.jce.provider.BouncyCastleProvider ()); Cipher.init (cipher. Decrypt_mode, PK); int blockSize = Cipher.getblocksize (); Bytearrayoutputstream bout = new Bytearrayoutputstream (+), int j = 0;while (raw.length-j * blockSize > 0) {bout.write (Cipher.dofinal (Raw, J * blockSize, BlockSize)); J + +;} return Bout.tobytearray ();} catch (Exception e) {throw new Exception(E.getmessage ());}} /** * * * * * @param args * * @throws Exception */public static void Main (string[] args) throws Exception {Rsapublickey R SAP = (Rsapublickey) Rsautil.generatekeypair (). Getpublic (); String test = "Hello World"; byte[] En_test = Encrypt (Getkeypair (). Getpublic (), test.getbytes ()); System.out.println ("123:" + new String (en_test)); byte[] De_test = Decrypt (Getkeypair (). Getprivate (), en_test); System.out.println (New String (De_test));}}

4. Define the Password Authentication class

Defining the Testpasswordvalidatorrsa.java Password validation class

Define a class, Named Testpasswordvalidatorrsa.java, extended to Abstractpasswordvalidator, override the password authentication method Encodepassword, the input password is flipped, and then encrypted, return the password to verify, the specific code such as Under

package Com.fr.privilege;  Import Com.fr.privilege.providers.dao.AbstractPasswordValidator;  public class Testpasswordvalidatorrsa extends abstractpasswordvalidator{//@Override public String Encodepassword (          String Clinetpassword) {try {//flips the password as input ab flips to ba stringbuffer sb = new StringBuffer ();        Sb.append (New String (Clinetpassword));    String BB = Sb.reverse (). toString ();         Encrypt byte[] en_test = Rsautil.encrypt (Rsautil.getkeypair (). Getpublic (), bb.getbytes ());      Decryption, if the database is saved with a password, then there is no need to decrypt byte[] De_test = Rsautil.decrypt (Rsautil.getkeypair (). Getprivate (), en_test); Returns the encrypted password Clinetpassword=new String (de_test);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return Clinetpassword;      That is, obtain the encrypted password and match the database password. } @Overridepublic Boolean ValidatePassword (String arg0, String arg1) {//TODO auto-generated method Stubreturn false;}} 

5. Compile the class file

First compile the Rsautil.java class file on the server's D disk to generate the RSAKey.txt file, and then compile the Testpasswordvalidatorrsa.java class, put the compiled class file to project engineering web-inf/classes/ The Com/fr/privilege folder.

6, Login login.jsp Page Setup

Client requests to the login page, randomly generate a string, this random string as the key to encrypt the password, the following code:

<% @page contenttype= "text/html" pageencoding= "UTF-8"%><% @page import= " Com.fr.privilege.providers.dao.RSAUtil "%><%!public string Testmo () {String module =" "; try { Java.security.interfaces.RSAPublicKey rsap = (Java.security.interfaces.RSAPublicKey) Rsautil.getkeypair (). Getpublic (); module = Rsap.getmodulus (). toString (16);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return module;} %><%!public string Testem () {String empoent = ""; try {java.security.interfaces.RSAPublicKey rsap = ( Java.security.interfaces.RSAPublicKey) Rsautil.getkeypair (). Getpublic (); empoent = Rsap.getpublicexponent (). ToString (16);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return empoent;} %>

  

A simple case of RSA encryption algorithm

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.