Discussion on Java Verification Code production (next) _java

Source: Internet
Author: User
Tags arithmetic border color current time flush gettext rand two factor stringbuffer

Next on the Java Verification Code production (above) to introduce you to the Java Verification Code related knowledge!

Method Three:

With the open source component Jcaptcha implementation, the use of the spring combination can produce multiple forms of authentication code, Jcaptcha is the Java version of the CAPTCHA project, which is an open source project, supporting the generation of graphics and sound version of the code, in the generation of sound version of the verification code, you need to use the Freetts. The CAPTCHA full name completely automated public Turing Test to tell Computers and humans Apart, the earliest as a research project at Carnegie Mellon University to build a human easy to pass and computer Tests that are difficult to pass are now widely used in Web applications to prevent robots from releasing spam. At present, the official website of Jcaptcha has 2.0 versions, but only 1.0 editions of the binary plate are available for downloading.

First we need to prepare the corresponding jar package

Jcaptcha project in the implementation, but also cited the commons-collections and commons-logging two open source projects, coupled with the implementation of Jcaptcha itself, we need a total of three packages, the specific information as follows:

Jcaptcha-2.0-all.jarcommons-logging-1.1.1.jarcommons-collections-3.2.jar

Next we look at the key configuration information in the following web.xml: In addition to configuring the specific class path for the Jcaptcha component, the Submitactionservlet is configured as a servlet for the authentication code, and is mapped for both, which is understood to be a different name, Use this mapping name directly when/jcaptcha.jpg and/submit.action invoke a component or servlet.

<servlet>
    <servlet-name>jcaptcha</servlet-name>
    <servlet-class> Com.octo.captcha.module.servlet.image.simpleimagecaptchaservlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>submit</servlet-name>
    <servlet-class> Com.octo.captcha.module.servlet.image.sample.submitactionservlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>jcaptcha</servlet-name>
    <url-pattern>/ jcaptcha.jpg</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    < servlet-name>submit</servlet-name>
    <url-pattern>/submit.action</url-pattern>
  </servlet-mapping>

Xml

Then let's see how Submitactionservlet does it: by importing the Jcaptcha component package, call directly into the encapsulated method Simpleimagecaptchaservlet.validateresponse (Request , Usercaptcharesponse) to determine whether the information in the verification code matches the submission, and does not need to consider the specific implementation process.

public class Submitactionservlet extends HttpServlet
{
 protected void DoPost (HttpServletRequest request, HttpServletResponse response)
 throws Servletexception, IOException
 {
 String usercaptcharesponse = Request.getparameter ("Japtcha");
 Boolean captchapassed = Simpleimagecaptchaservlet.validateresponse (request, usercaptcharesponse);
 if (captchapassed)
  response.getwriter (). Write ("Captcha passed");
 else {
  response.getwriter (). Write ("Captcha failed");
 Response.getwriter (). Write ("<br/><a href= ' index.jsp ' >try again</a>");
 }
Submitactionservlet

Finally, let's take a look at the simple foreground call:

 
 

Implementation legend:

Method Four:

With the open source component Kaptcha implementation, the same use Kaptcha need to download its jar component package, Kaptcha is a very useful verification code generation tool. With it, you can generate a variety of style verification codes because it is configurable. The principle of kaptcha work is to call Com.google.code.kaptcha.servlet.KaptchaServlet (you can see that he is an open-source project of Google) and generate a picture. The generated verification code string is also placed in the httpsession.

The Kaptcha can be easily configured with:

Verification Code font Verification Code font size verification Code font font Color Verification Code content range (number, letter, Chinese characters!) Verify code picture size, border, border thickness, border color Verification Code interference line (you can inherit com.google.code.kaptcha.NoiseProducer write a custom interference line) Verification code style (fish eye style, 3D, general Blur ...) Of course, you can also inherit the Com.google.code.kaptcha.GimpyEngine custom style)

......

The configuration information for the Kaptcha is also placed in the configuration information that is initialized in the Web.xml:<init-param> tag

<servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class> Com.google.code.kaptcha. Servlet. Kaptchaservlet </servlet-class> <init-param> <description> picture border, legal value: Yes, No</description&gt
    ; <param-name>kaptcha.border</param-name> <param-value>yes</param-value> </init-param
    > <init-param> <description> border Color, legal value: r,g,b (and optional alpha) or White,black,blue. </description> <param-name>kaptcha.border.color</param-name> <param-value>black</para m-value> </init-param> <init-param> <description> border thickness, legal value:></description> < Param-name>kaptcha.border.thickness</param-name> <param-value></param-value> </ init-param> <init-param> <description> picture width </description> <param-name>kaptcha.image.w
    Idth</param-name><param-value></param-value> </init-param> <init-param> <description> picture High &LT;/DESCR iption> <param-name>kaptcha.image.height</param-name> <param-value></param-value> &L T;/init-param> <init-param> <description> Picture implementation class </description> <param-name>kaptcha.pro ducer.impl</param-name> <param-value> Com.google.code.kaptcha.impl.DefaultKaptcha </param-valu e> </init-param> <init-param> <description> Text implementation class </description> <param-name> Kaptcha.textproducer.impl</param-name> <param-value> Com.google.code.kaptcha.text.impl.DefaultTextCr Eator </param-value> </init-param> <init-param> <description> text collection, validation code values from this collection </de Scription> <param-name>kaptcha.textproducer.char.string</param-name> <param-value></ Param-value> <!--<param-value>abcdegfynmnpwx</param-value>--> <!--<param-value> mu Course Network Tutorial Verification Code Instance </param-value >--> </init-param> <init-param> <description> Verification code length </description> <param-n Ame>kaptcha.textproducer.char.length</param-name> <param-value></param-value> </ init-param> <init-param> <description> Font Arial, courier</description> <param-name>ka Ptcha.textproducer.font.names</param-name> <param-value>arial, courier</param-value> </ init-param> <init-param> <description> font size px.</description> <param-name>kaptcha.tex tproducer.font.size</param-name> <param-value></param-value> </init-param> <init-para
    m> <description> font Color, legal value: R,g,b or White,black,blue.
    </description> <param-name>kaptcha.textproducer.font.color</param-name><param-value>black</param-value> </init-param> <init-param> <description> text Interval < /description> <param-name>kaptcha.textproducer.char.space</param-name> <param-value></ param-value> </init-param> <init-param> <description> Interference implementation class </description> <para M-name>kaptcha.noise.impl</param-name> <param-value> <!--com.google.code.kaptcha.impl.NoNoise --> com.google.code.kaptcha.impl.DefaultNoise </param-value> </init-param> <init-param&gt
    ;
    <description> interference color, legal value: R,g,b or White,black,blue. </description> <param-name>kaptcha.noise.color</param-name> <param-value>black</ param-value> </init-param> <init-param> <description> Picture style: Watermark Com.google.code.kaptcha. Impl. Waterripple Fish Eye Com.google.code.kaptcha.impl.FishEyeGimpy Shadow com.google.cOde.kaptcha.impl.ShadowGimpy </description> <param-name>kaptcha.obscurificator.impl</param-name&
    Gt <param-value> com.google.code.kaptcha.impl.WaterRipple </param-value> </init-param> <i nit-param> <description> Background Implementation class </description> <param-name>kaptcha.background.impl</ param-name> <param-value> Com.google.code.kaptcha.impl.DefaultBackground </param-value> ;/init-param> <init-param> <description> background color gradient, start color </description> <param-name>kaptch A.background.clear.from</param-name> <param-value>green</param-value> </init-param> < init-param> <description> background color gradient, end color </description> <param-name>kaptcha.background.clear.to& lt;/param-name> <param-value>white</param-value> </init-param> <init-param> <d escription> Text Renderer </descriPtion> <param-name>kaptcha.word.impl</param-name> <param-value> Com.google.code.kaptcha. Text.impl.DefaultWordRenderer </param-value> </init-param> <init-param> <description&gt
     ; Key key </description> <param-name>kaptcha.session.key</param-name> <param-val to store the verification code in session ue>kaptcha_session_key</param-value> </init-param> <init-param> <description> Th E date The Kaptcha is generated was put into the HttpSession.
    This is the key value of the session. </description> <param-name>kaptcha.session.date</param-name> <param-value>kaptcha_ session_date</param-value> </init-param> </servlet> <servlet-mapping> &LT;SERVLET-NAME&G T Kaptcha</servlet-name> <url-pattern>/randomcode.jpg</url-pattern> </servlet-mapping>

Front Call: The path to the verification code picture with the mapping name randomcode.jpg, click the event onclick () called the JS function, the same JS function in the current time so that the browser cache invalidation to refresh the verification code picture.

 
 

Comparison of the verification Code check.jsp: Through (String) Session.getattribute (Com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); Get the string information in the CAPTCHA picture.

  
 

Implementation legend:

We can find that our verification code has become more and more colorful, but still in a verification of English letters and numbers of the stage, then can play a bit high-end, the answer is yes. Let's take a look at how the Chinese verification code and the arithmetic Operation verification code are implemented. Can only be modified based on the use of the above Kaptcha.

Implementation of the Chinese Verification Code:

First we find the Kaptcha.jar package has a defaulttextcreator.class bytecode file, as the name suggests, he is to produce a code in the text of a class, we can implement a class that inherits from him, and through configuration to use their own implementation class to make the text in the verification code into Chinese. We can see that the GetText () function is used to produce the captcha text that the GetConfig () configurator will render, so we simply inherit the configuration class and implement the text generation interface and rewrite the GetText () method.

 public class Defaulttextcreator
 extends configurable
 implements Textproducer
 {public
 String GetText ()
 {
  int length = GetConfig (). Gettextproducercharlength ();
  char[] chars = GetConfig (). gettextproducercharstring ();
  int randomcontext = chars.length-;
  Random rand = new Random ();
  StringBuffer Text = new StringBuffer ();
  for (int i =; i < length; i++) {
  text.append (chars[(Rand.nextint (Randomcontext) +)]);
  return text.tostring ();
 }
 

The following is the specific implementation of Chinesetext.java: The program only executes the code in GetText (), the original code written to the GETTEXT1 (), do not execute, we can make a comparison.

public class Chinesetext extends configurable implements Textproducer {public String getText () {int length = Getco
   Nfig (). Gettextproducercharlength ();
   char[] CharS = GetConfig (). gettextproducercharstring ();
   String[] s = new string[]{"I", "Love", "Tie", "Tile", "and", "sell", "plug", "buckle"};
   Random rand = new Random ();
   StringBuffer sb = new StringBuffer ();
    for (int i =; i < length; i++) {int ind = Rand.nextint (s.length);
   Sb.append (S[ind]);
  return sb.tostring ();
   /** * Noon Instance * @return/Public String getText () {int length = GetConfig (). Gettextproducercharlength ();
   String Finalword = "", FirstWord = "";
   int tempint =;
   String[] Array = {"," "," "," "," "," "," "," "," "," "," "," "," "," a "," B "," C "," D "," E "," F "};
   Random rand = new Random (); for (int i =; i < length; i++) {switch (Rand.nextint (array.length)) {case:tempint = Rand.nextint () +
     ;
     FirstWord = string.valueof ((char) tempint);
    Break Case:iNT R, R, R, R; String STRH, strl;//high&low r = rand.nextint () +;
     Open after front [,) if (r = =) {R = Rand.nextint ();
     else {r = Rand.nextint ();
     } r = Rand.nextint () +;
     if (r = =) {R = rand.nextint () +;
     else if (r = =) {R = Rand.nextint ();
     else {r = Rand.nextint ();
     } STRH = Array[r] + array[r];
     Strl = Array[r] + array[r];
     byte[] bytes = new byte[];
     Bytes[] = (byte) (Integer.parseint (STRH,));
     Bytes[] = (byte) (Integer.parseint (Strl,));
     FirstWord = new String (bytes);
    Break
     Default:tempint = Rand.nextint () +;
     FirstWord = string.valueof ((char) tempint);
    Break
   } Finalword + = FirstWord;
  return Finalword; }
 }

The final step is to web.xml the text to implement the value of the class, so that the component calls its own write the class generated in Chinese authentication code.

<init-param>
    <description> Text Implementation class </description>
    <param-name> kaptcha.textproducer.impl</param-name>
    <param-value>
     chinesetext
    </param-value>
   

Implementation legend:

Implementation of the Arithmetic verification code:

As with the Chinese authentication code above, we need to implement our own classes by inheriting classes and interfaces, rewrite the functions in them, and then change the configuration information to make the component invoke its own implementation of the class to realize the diversity of the Verification code form.

The Kaptchaservlet bytecode file has the following decompile code:

public class Kaptchaservlet extends HttpServlet implements Servlet {private properties props = new properties ();
 Private Producer kaptchaproducer = null;
 Private String sessionkeyvalue = null;
  public void init (ServletConfig conf) throws Servletexception {super.init (conf);
  Imageio.setusecache (FALSE);
  Enumeration<?> initparams = Conf.getinitparameternames ();
  while (Initparams.hasmoreelements ()) {string key = (String) initparams.nextelement ();
  String value = Conf.getinitparameter (key);
  This.props.put (key, value);
  Config config = new config (this.props);
  This.kaptchaproducer = Config.getproducerimpl ();
 This.sessionkeyvalue = Config.getsessionkey (); public void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {resp.se
  Tdateheader ("Expires", L);
  Resp.setheader ("Cache-control", "No-store, No-cache, must-revalidate");
  Resp.addheader ("Cache-control", "post-check=, pre-check="); Resp.setheader ("Pragma", "No-cache");
  Resp.setcontenttype ("Image/jpeg");
  String Captext = This.kaptchaProducer.createText ();
  Req.getsession (). setattribute (This.sessionkeyvalue, Captext);
  BufferedImage bi = this.kaptchaProducer.createImage (captext);
  Servletoutputstream out = Resp.getoutputstream ();
  Imageio.write (BI, "JPG", out);
  try {out.flush ();
  finally {out.close (); }
 }
 }

The

Then implements the Kaptchaservlet.java code as follows: The logic to implement the addition verification code is added to the original bytecode file and can be found by comparison.

public class Kaptchaservlet extends HttpServlet implements Servlet {private Properties props;
  Private Producer Kaptchaproducer;
  Private String Sessionkeyvalue;
   Public Kaptchaservlet () {this.props = new Properties ();
   This.kaptchaproducer = null;
  This.sessionkeyvalue = null;
   public void init (ServletConfig conf) throws Servletexception {super.init (conf);
   Imageio.setusecache (FALSE);
   Enumeration initparams = Conf.getinitparameternames ();
    while (Initparams.hasmoreelements ()) {string key = (String) initparams.nextelement ();
    String value = Conf.getinitparameter (key);
   This.props.put (key, value);
   Config config = new config (this.props);
   This.kaptchaproducer = Config.getproducerimpl ();
  This.sessionkeyvalue = Config.getsessionkey (); public void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {resp
   . Setdateheader ("Expires", L); Resp.setheader ("Cache-control", "No-store, no-cAche, must-revalidate ");
   Resp.addheader ("Cache-control", "post-check=, pre-check=");
   Resp.setheader ("Pragma", "No-cache");
   Resp.setcontenttype ("Image/jpeg");
   String Captext = This.kaptchaProducer.createText ();
   String s = captext.substring (,);
   String s = captext.substring (,);
   int r = integer.valueof (s). Intvalue () + integer.valueof (s). Intvalue ();
   Req.getsession (). setattribute (This.sessionkeyvalue, string.valueof (R));
   BufferedImage bi = this.kaptchaProducer.createImage (s+ "+" +s+ "=?");
   Servletoutputstream out = Resp.getoutputstream ();
   Imageio.write (BI, "JPG", out);
   try {out.flush ();
   finally {out.close (); }
  }
 }

We also need to make a change configuration at the beginning of web.xml so that the component can invoke its own implementation servlet:

<servlet-name>Kaptcha</servlet-name>
   <servlet-class>
    kaptchaservlet
   </ Servlet-class>

Implementation legend:

Summarize:

Here is a simple implementation of the verification code, but to use a commercial project is still far from enough, the verification code want to not be cracked and add a variety of encryption algorithms, even if so, can also search everywhere to a certain verification code is cracked. There is an underground database on the network, it is stored in our personal information, the information is a good arrangement, which is very frightening, but such a database is an objective existence, the verification code as a protection of the account password is an important link, has become increasingly unsafe, because the disclosure of personal information, If you have enough information, you will be able to cheat, in which the verification code is an important link, recently a graduate has been cheated verification code, within a few hours of all the wealth has been diverted to take place. So please protect your verification code, do not easily leaked to others.

Of course, we will not sit still, the current verification code a wide range of more and more difficult to crack, such as speech recognition, facial recognition of these are familiar to say no more.

Here we introduce a validation code "new" concept: two factor authentication.

Two-factor authentication is a system adopting time synchronization technology, which adopts a one-time password based on time, event and key three variables to replace the traditional static password. Each dynamic password card has a unique key, the key is also stored on the server side, each time the dynamic password card and the server according to the same key, the same random parameters (time, events) and the same algorithm to calculate the authentication of dynamic passwords, so as to ensure the consistency of the password, so as to achieve the user's authentication. Because the random parameters of each authentication are different, so each generated dynamic password is also different. Because the randomness of the parameters of each calculation guarantees the unpredictability of each password, the security of the system is ensured in the most basic password authentication process. To solve the serious loss caused by password fraud, to prevent malicious intruders or man-made damage, to solve the intrusion caused by password leaks.

In simple terms, two-factor identity authentication is a system of identity authentication that you know and combine with the two elements you can have. For example, a bank card that is used to withdraw money from ATM is an example of a two-factor authentication mechanism, which requires the combination of the two elements of the withdrawal code and the bank card. At present, the two-factor authentication system is based on time synchronization type, high market share has Dkey dual-factor authentication system ,RSA dual-factor authentication system, and so on, because the dkey increases to SMS password authentication and SMS + token mixed authentication support, compared with RSA, Dkey Dual-Factor certification system is more competitive.

The above is a small series to introduce the Java verification code produced by the relevant content, I hope to help you!

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.