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 generatekeypair () 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");objectinputstream 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 static 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 ());}} /** * * Generating private keys * * * @param modulus * * @param privateExponent * * @return RSAPrivateKey * * @throws exception */public static 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 keys * * @param data * plaintext data to be encrypted * * @return encrypted data * * @throws exception */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 ();// , the encryption block size, such as: Before the encryption data is 128 byte, and the key_size=1024// encryption block size of 127// byte, encrypted after 128 byte; so there are 2 encryption blocks, the first 127// byte second for 1 byteint outputsize = cipher.getoutputsize (data.length);// gets the block size after the encryption block is encrypted 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 doupdate method is not available, after viewing the source code found after each doupdate and there is no actual action except theByte[] into the// bytearrayoutputstream, and finally dofinal all the byte[] to encrypt, but at this time the size of the encryption block is probably beyond the// Outputsize so had to use dofinal method. i++;} Return raw;} catch (exception e) {throw new exception (E.getmessage ());}} /** * * decryption * * * @param key * decrypted keys * * @param raw * Encrypted data * * @return decrypted plaintext * * @throws exception */public static byte[] decrypt (PRIVATEKEY PK, byte[] raw) throws Exception {try {Cipher cipher = Cipher.getinstance ("RSA", 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 rsap = (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 { // Flip the password as input ab flips to Ba stringbuffer sb = new stringbuffer (); sb.append (new string (ClinetPassword)); string bb = sb.reverse (). toString (); The //is encrypted byte[] en_test = rsautil.encrypt (RSAUtil.getKeyPair (). Getpublic (), Bb.getbytes ()), //decryption, if the database is stored in a password, The decryption is not required here byte[] de_test = rsautil.decrypt (Rsautil.getkeypair (). Getprivate (), en_test); //return encryption Password clinetpassword=new string (de_test);} catch (exception e) {// TODO Auto-generated catch Blocke.printstacktrace ();} return clinetpassword; //that the encrypted password is then matched to the database password.      &NBSP,} @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;} %> Simple case of RSA encryption algorithm