SPRINGMVC Integrated RSA encryption algorithm

Source: Internet
Author: User
Tags base64 md5 encryption modulus tomcat server

Technology Exchange Group: 233513714

This article describes the integrated use of RSA encryption algorithm +spring security in SPRINGMVC.

What is Spring security?

Reference: Spring Security is a secure framework that provides declarative, secure access control solutions for spring-based Enterprise Applications. It provides a set of beans that can be configured in the context of the spring application, taking full advantage of the spring Ioc,di (control inversion inversion of controls, di:dependency injection  Dependency Injection) and AOP (aspect-oriented Programming) capabilities provide declarative, secure access control for application systems, reducing the effort to write large amounts of repetitive code for enterprise system security Controls.  Spring security, formerly known as acegi, became a sub-project of spring and is currently the most popular security rights management framework that is tightly integrated with spring. Spring Security is focused on serving you at the Enterprise Application Security layer, where you will find a wide variety of requirements for business problem Areas. Banking systems are very different from E-commerce Applications. E-commerce Systems and Enterprise sales automation tools are very different. These customized requirements make application security interesting, challenging and Worthwhile. Spring Security provides a comprehensive set of security solutions for ee-based Enterprise Applications.

Learn Spring Security's URL Http://www.iteye.com/blogs/subjects/spingsecurity3inside.

Spring-security's own encryption Algorithm has

-bcrypt
-plaintext
-sha
-sha-256
-md5
-md4
-{sha}
-{ssha}

Because of the MD5 encryption algorithm, the use is more common, but can be cracked by the way of collision, not Adopted.

What is rsa?

Like RSA (Ron Rivest,adi shamir,len adleman three-bit genius), ECC (Elliptic Curves cryptography, Elliptic curve Cryptography) also belongs to the public key algorithm. But the ECC algorithm joins the support after jdk1.5, at present only can complete the key generation and the Parsing.

RSA is currently the most influential Public-key encryption algorithm, it can resist the most known password attacks so far, has been recommended by the ISO public key data encryption Standard. Only short RSA keys today can be broken by brute force Mode. Until 2008, there was no reliable way to attack the RSA algorithm in the WORLD. As long as its key length is long enough, the information encrypted with RSA is not actually Broken. however, with the maturity of distributed computing and quantum computer theory, RSA encryption Security has been Challenged. The RSA algorithm is based on a very simple number theory fact: it is easy to multiply two large primes, but it is extremely difficult to factorization the product, so you can expose the product as an encryption key.

RSA key lengths increase quickly with the level of Secrecy. The following table lists the key lengths that correspond to the same security level.

Level of secrecy Symmetric key Length (bit) RSA Key Length (bit) ECC Key Length (bit) Duration of secrecy
80 80 1024 160 2010
112 112 2048 224 2030
128 128 3072 256 2040
192 192 7680 384 2080
256 256 15360 512 2120

How to implement the implementation of Rsa+spring Security in Spring mvc, directly on the Web. XML

The com.user.sec in Xml. MyHttpsessioneventpublisher is used for both custom org.springframework.security.web.session.HttpSessionEventPublisher.
<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:web= "http://java.sun.com/xml/ns/javaee" xmlns= "http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "http ://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "metadata-complete=" false " version= "2.5" > <!--configuration context parameters, specifying the location of the spring configuration file--
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*: Spring/applicationcontext-*.xml</param-value> </context-param>
<!--Spring Security filter--
<filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.spri Ngframework.web.filter.delegatingfilterproxy</filter-class> </filter> <filter-mapping> < Filter-name>springsecurityfilterchain</filter-name> <url-pattern>/*</url-pattern> </filt Er-mapping>
<!--Spring Character Set filter--
<!--contains set two parameters encoding and forceencoding--> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param > <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-par am> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-patter n>*</url-pattern> </filter-mapping> <filter> <filter-name>hibernatefilter</ Filter-name> <filter-class>org.springframework.orm.hibernate4.support.opensessioninviewfilter</ filter-class> <init-param> <param-name>excludeSuffixs</param-name> <param-value>js ,css,jpg,gif</param-value> </init-param> </filter> <filter-mapping> <filter-name>hib Ernatefilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping> <listener> <listener-class> Org.springframework.web.util.log4jconfiglistener</listener-class> </listener> <listener> < Listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener > <listener> <listener-class>com.user.sec.MyHttpSessionEventPublisher</listener-class> </ Listener> <!--<listener> <listener-class> Org.springframework.security.web.session.httpsessioneventpublisher</listener-class> </listener>-- > <listener> <listener-class>org.springframework.web.util.introspectorcleanuplistener</ listener-class> </listener> <context-param> <param-name>log4jconfiglocation</param-name > <param-value>WEB-INF/classes/properties/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jrefreshinterval</param-name> <param-value>60000</param-value> </context-param> <servlet > <servlet-name>springmvc</servlet-name> <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name> Contextconfiglocation</param-name> <param-value>classpath*:spring/applicationcontext-springmvc.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <ser Vlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> < /servlet-mapping> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> < Filter-class>org.springframework.web.filter.hiddenhttpmethodfilter</filter-class> </filter> < Filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <servlet-name>springmvc</servlet-name> </filter-mapping> <session-config> <session-timeout>30</ session-timeout> </session-config> <welcome-file-list> <welcome-file>index.html</ welcome-file> </welcome-file-list> <error-page> <error-code>500</error-code> <locati On>/500.html</location> </error-page></web-app>

Applicationcontext-security.xml

Spring security uses the proximity principle that when there are multiple constraints, it returns from top to bottom as soon as the first satisfaction is found, so that the most restrictive constraints are placed at the top, and the most relaxed constraints are placed on the last Side. the Auto-config property allows spring Security for our automatic configuration of several commonly used rights control mechanisms, including form,anonymous, RememberMe and so On. Of course you can also manually configure. Example:

For the settings that intercept pattern, specify the Following:

/ALL Requests with/

/* represents the request under this domain for EXAMPLE:/USER/XXX this will be intercepted but will not intercept/user/xxx/xxx

/** represents cross-domain requests for example:/user/xxx and/user/xxx/xxx will be Intercepted.

<?xml version= "1.0" encoding= "UTF-8"? ><beans:beans xmlns= "http://www.springframework.org/schema/security "xmlns:beans=" Http://www.springframework.org/schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.2.xsd http://www.springframework.org/schema/security http://www.springframework.org/ Schema/security/spring-security-3.2.xsd "> <global-method-security secured-annotations=" enabled "/>
  
<!--configuration of non-filtered resources, including login requests, static resource access, registration page, Get login Registration verification code, of course, including this article is involved in the background obtained from the public key interface--
<beans:bean id= "rsaencoder" class= "com.common.component.util.RSAPasswordEncoder"/> <authentica Tion-manager alias= "authenticationmanager" erase-credentials= "false" > <authentication-provider user-se rvice-ref= "userdetailservice" > <password-encoder ref= "rsaencoder"/> </authentication-provid er> <!--customize provider-<!--<authentication-provider ref= "myauthenticationprovider" > < /authentication-provider>--</authentication-manager> <beans:bean id= "mydefinefilter" class= "com.user.sec.MyFilterSecurityInterceptor" > <beans:proper Ty name= "authenticationmanager" ref= "authenticationmanager"/> <!--<beans:property name= "accessDecisionMa Nager "ref=" accessdecisionmanager "/>-to <beans:property name=" securitymetadatasource "ref=" D Atabasedefinitionsource "/> <beans:property name=" accessdecisionmanager "ref=" myAccessDecisionManager "/> </beans:bean> <!--<beans:bean id= "myauthenticationprovider" class= " Crowdfunding.user.sec.MyAuthenticationProvider "/>--<beans:bean id=" Databasedefinitionsource "class=" Com.user.sec.DefinitionSourceFactoryBean "> <beans:constructor-arg ref=" resourcedetailservice "/> &L t;! --<beans:constructor-arg ref= "userdetailservice"/>--</beans:bean> <beans:bean id= "myaccessdec Isionmanager "class=" com.user.sec.MyAccessDecisionManager "> </beans:bean> <beans:bean id=" accessdeniedhandler "class=" Com.user.sec.MyAccessDeniedHandler "/></beans:beans>

Rsapasswordencoder.java

Package Com.common.component.util;import Java.net.urldecoder;import Org.apache.commons.lang3.stringutils;import Org.springframework.security.authentication.encoding.passwordencoder;import Decoder.BASE64Decoder;import Decoder.base64encoder;import com.common.component.util.mpbsecurersautil;/************************************** * Description: custom RSA Processing class * To add additional encryption to spring Security, redefine such <br/> *********** /public class Rsapasswordencoder implements Passwordencoder {/******** * Description: plaintext Encryption <br/> * @return * @param rawpass * Secret Code ******************************************/public string Encodepassword (string rawpass, Object Salt) {St        Ring encoder = "";        Try {encoder = mpbsecurersautil.decryptstring (rawpass);        } catch (Exception E) {e.printstacktrace (); } return Encoder; }/***************************************** * Description: Verifying that the password is valid is primarily the use of this method <br/> * * @return Boolea  N ******************************************/public boolean ispasswordvalid (string encpass, string rawpass, Object Salt) {if (! Mpbstringutil.isnotblank (encpass) | |        Encpass.length () = = 0) {return false;        } String DECPSW = mpbsecurersautil.decryptstring (encpass);        String INPDECPSW = Mpbsecurersautil.decryptstringbyjs (rawpass);        Try {DECPSW = Urldecoder.decode (decpsw, "UTF-8");            } catch (Exception E) {e.printstacktrace ();        Return false;    } return inpdecpsw.equals (decpsw); }/***************************************** * Description: private key Decryption <br/> * * @return **************        /public string Decryptpassword (string rawpass, Object salt) {string encoder = ""; Try {encoder = MpbsecurerSautil.decryptstring (rawpass);        } catch (Exception E) {e.printstacktrace ();    } return encoder;     }/***************************************** * description:base64 Decryption <br/> * @param key * @return * @throws Exception ******************************************/public static byte[] decoderBase64 (String Key) thro    WS Exception {return (new base64decoder ()). decodebuffer (key); }/***************************************** * DESCRIPTION:BASE64 Encryption <br/> * * @param key * @retu RN * @throws Exception ******************************************/public static String encoderBase64 (byte[] ke    Y) throws Exception {return (new base64encoder ()). encodebuffer (key); }}

Login.html

<script type= "text/javascript" src= "resources/js/rsa/security.js" ></script>

    function Mysubmit () {if ($ ("input[name= ' _spring_security_remember_me ')"). attr ("checked") = = "checked") {        If you remember that the user name and password box is selected, execute the Remenber () method Remember ();        }else{//if unchecked, Empty the cookie $.mpbsetcookie ("ebs_ischecked", "");                    }//get the public key from the background and encrypt, transfer encrypted ciphertext to the server processing $.mpbpost ("/admin/user/getpairkey", { "_method": "GET"}, function (data) {var modulus = data[' m                    Odul '];                    var exponent = data[' exponent '];                    var key = Rsautils.getkeypair (exponent, ", modulus);                    var pwd = $ ("#psw"). val ();                    PWD = encodeURIComponent (pwd);                    PWD = rsautils.encryptedstring (key, pwd);                    $ ("#psw"). attr ("value", pwd);                    $ ("input[name= ' J_password ')"). val (pwd);                $ ("#myform"). Submit ();                });    } 

Controler.java

@ResponseBody    @RequestMapping (value = "/getpairkey", method = Requestmethod.get) public    map<?,? > GetKey () throws Exception {        rsapublickey publickey = Mpbsecurersautil.getdefaultpublickey ();        map<string, string> key = new hashmap<string,string> ();        Key.put ("modul",                New String (hex.encodehex (publickey.getmodulus (). tobytearray ())));        Key.put ("exponent",                New String (hex.encodehex (publickey.getpublicexponent ()                        . tobytearray ())));        return key;    }

File Address:

Http://files.cnblogs.com/files/Sonet-life/security.js

Http://files.cnblogs.com/files/Sonet-life/MpbSecureRSAUtil.rar

The whole idea of cryptography:

1, the project at startup to check whether to generate a key pair of files, not to force the generation of new, remember to use RSA registered users in the database is encrypted ciphertext, RSA key to the file to ensure consistency, if the key to the file generated a new, and you do not back up the key to the file, will result in irreversible consequences. The best way to do this is to set the path of the key pair file in the Mpbsecurersautil to the hard disk, not to the Tomcat server, or the key-to-file will be regenerated every time you delete the project or Redeploy. or, each time you replace the new build with the old one, keep the Availability.

2, The front desk requests the Server's public key, transmits to the foreground, because the public key is public, uses the public key to encrypt the user login registration or other confidential information in the foreground, transmits the public key encrypted ciphertext to the Server. The server passes the private key corresponding to the public key, decrypts the ciphertext of the database and transmits the cipher text, compares the decrypted character typeface, and then returns the confirmation information to the foreground for the next Operation.

SPRINGMVC Integrated 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.