Home>

Continue from Part IJava verification code production (Part 1)I will introduce the relevant knowledge about java verification code!

Method three:

It is implemented with the open source component jcaptcha, and combined with spring can generate multiple forms of verification codes.jcaptcha is the java version of the captcha project, which is an open source project,Supports generation of graphic and sound verification codes,When generating an audio verification code,Need to use freetts. The full name of captcha is completely automated public turing test to tell computers and humans apart. It was first used as a research project at Carnegie Mellon University.Used to generate a test that is easy for humans to pass and difficult for computers to pass.Currently widely used in network applications,Used to stop robots from posting spam.Currently, the official jcaptcha website shows version 2.0, but the binary version is only available for download.

First we need to prepare the corresponding jar package

The jcaptcha project is being implemented,It also refers to two open source projects, commons-collections and commons-logging,Coupled with the implementation of jcaptcha itself,We need three packages in total,Specific information is as follows:

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

Secondly, we look at the following key configuration information in web.xml:In addition to the specific class path of the jcaptcha component, the submitactionservlet is also configured as a servlet for comparing verification codes, and both are mapped for bothCan be understood as a change of name,You can use this mapping name directly when calling components or servlets for /jcaptcha.jpg and /submit.action respectively.

<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>

web.xml

Then look at how the submissionactionservlet is implemented:Since the jcaptcha component package is imported,So directly call the encapsulated method simpleimagecaptchaservlet.validateresponse (request, usercaptcharesponse) to determine whether the information in the verification code matches the submission.It is not necessary 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 we look at a simple foreground call:

<html>
 <body>
 <h>simple captcha servlet sample</h>
 <form action="submit.action" method="post">
  <img src="jcaptcha.jpg" /><input type="text" name="japtcha" value="" />
  <input type="submit" />
 </form>
 </body>
 </html>

Implementation legend:

Method four:

It is implemented with the open source component kaptcha. Similarly, to use kaptcha, you need to download its jar component package. Kaptcha is a very practical verification code generation tool.With it, you can generate various styles of verification codes,Because it is configurable.The principle of kaptcha works is to call com.google.code.kaptcha.servlet.kaptchaservlet (it can be seen that he is an open source project by Google) to generate an image.At the same time, the generated verification code string is placed in the httpsession.

Easy configuration using kaptcha:

Verification code font Verification code font size Verification code font font color Verification code content range (numbers, letters, Chinese characters!) Verification code picture size,Border, border thickness,Interference line of border color verification code (you can inherit com.google.code.kaptcha.noiseproducer to write a custom interference line) The style of verification code (fisheye style, 3d, ordinary blur ... Of course, you can also inherit com.google (code.kaptcha.gimpyengine custom style)

...

The configuration information for kaptcha is also placed in the web.xml:tag is the initial configuration information

<servlet>
   <servlet-name>kaptcha</servlet-name>
   <servlet-class>
    com.google.code.kaptcha.servlet.kaptchaservlet
   </servlet-class>
   <init-param>
    <description>picture border,Legal values:yes, no</description>
    <param-name>kaptcha.border</param-name>
    <param-value>yes</param-value>
   </init-param>
   <init-param>
    <description>
     Border color,Legal values:r, g, b (and optional alpha) or
     white, black, blue.
    </description>
    <param-name>kaptcha.border.color</param-name>
    <param-value>black</param-value>
   </init-param>
   <init-param>
    <description>border thickness,Legal values:></description>
    <param-name>kaptcha.border.thickness</param-name>
    <param-value></param-value>
   </init-param>
   <init-param>
    <description>picture width</description>
    <param-name>kaptcha.image.width</param-name>
    <param-value></param-value>
   </init-param>
   <init-param>
    <description>picture high</description>
    <param-name>kaptcha.image.height</param-name>
    <param-value></param-value>
   </init-param>
   <init-param>
    <description>Picture implementation class</description>
    <param-name>kaptcha.producer.impl</param-name>
    <param-value>
     com.google.code.kaptcha.impl.defaultkaptcha
    </param-value>
   </init-param>
   <init-param>
    <description>Text implementation class</description>
    <param-name>kaptcha.textproducer.impl</param-name>
    <param-value>
     com.google.code.kaptcha.text.impl.defaulttextcreator
    </param-value>
   </init-param>
   <init-param>
    <description>text collection,Captcha value is taken from this collection</description>
    <param-name>kaptcha.textproducer.char.string</param-name>
    <param-value></param-value>
    <!-<param-value>abcdegfynmnpwx</param-value>->
    <!-<param-value>An example of the verification code of the MOOC tutorial</param-value>->
   </init-param>
   <init-param>
    <description>Verification Code Length</description>
    <param-name>kaptcha.textproducer.char.length</param-name>
    <param-value></param-value>
   </init-param>
   <init-param>
    <description>font arial, courier</description>
    <param-name>kaptcha.textproducer.font.names</param-name>
    <param-value>arial, courier</param-value>
   </init-param>
   <init-param>
    <description>font size px.</description>
    <param-name>kaptcha.textproducer.font.size</param-name>
    <param-value></param-value>
   </init-param>
   <init-param>
    <description>
     font color,Legal values: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 space</description>
    <param-name>kaptcha.textproducer.char.space</param-name>
    <param-value></param-value>
   </init-param>
   <init-param>
    <description>interference implementation class</description>
    <param-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>
    <description>
     Disturbing colors,Legal values: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:Water pattern com.google.code.kaptcha.impl.waterripple
     Fisheye com.google.code.kaptcha.impl.fisheyegimpy
     Shadow com.google.code.kaptcha.impl.shadowgimpy
    </description>
    <param-name>kaptcha.obscurificator.impl</param-name>
    <param-value>
     com.google.code.kaptcha.impl.waterripple
    </param-value>
   </init-param>
   <init-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>kaptcha.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</param-name>
    <param-value>white</param-value>
   </init-param>
   <init-param>
    <description>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>
     The key that stores the verification code in the session
    </description>
    <param-name>kaptcha.session.key</param-name>
    <param-value>kaptcha_session_key</param-value>
   </init-param>
   <init-param>
    <description>
     the date the kaptcha is generated is put into the
     httpsession. this is the key value for that item in the
     session.
    </description>
    <param-name>kaptcha.session.date</param-name>
    <param-value>kaptcha_session_date</param-value>
   </init-param>
  </servlet>
  <servlet-mapping>
   <servlet-name>kaptcha</servlet-name>
   <url-pattern>/randomcode.jpg</url-pattern>
  </servlet-mapping>

Foreground call:The path of the captcha image uses the randomname.jpg, the click event onclick () calls the js function, and the js function also invalidates the browser cache with the current time to refresh the captcha image.

<html>
 <head>
 <meta http-equiv="content-type" content="text/html;charset=utf-">
 <title>randomcode</title>
 <script type="text/javascript">
  function changer (node) {
   //Used to generate different verification codes when clicked
   node.src="randomcode.jpg?time =" + new date (). gettime ();
  }
 </script>
 </head>
 <body>
 <img src="randomcode.jpg" onclick="changer (this)">
  <form action="check.jsp">
   <input type="text" name="r">
   <input type="submit" value="s">
  </form>
 </body>
 </html>

Verification code check.jsp:get (string) session.getattribute (com.google.code.kaptcha.constants.kaptcha_session_key);get string information in the verification code picture

<html>
 <head>
 <meta http-equiv="content-type" content="text/html;charset=utf-">
 <title>check</title>
 </head>
 <body>
  <%
   //check if it is the correct verification code
   string k=(string) session
     .getattribute (com.google.code.kaptcha.constants.kaptcha_session_key);
   string str=request.getparameter ("r");
   if (k.equals (str))
    out.print ("true");
   out.print (k + "---" + str);
  %>
 </body>
 </html>

Implementation legend:

You can see that our verification codes have become more and more colorful,But it is still at a stage where only English letters and numbers are verified.So can you play high-end?The answer is yes.Next, let's look at how to implement Chinese verification codes and arithmetic verification codes.All just need to modify based on the use of kaptcha above.

Implementation of Chinese verification code:

First we find the defaulttextcreator.class bytecode file under the kaptcha.jar package.As the name suggests,It is a class to generate the text in the verification code,We can implement a class that inherits from him,And configure to use your own implementation class to make the text in the verification code into Chinese.After decompiling the following class, we can see that it is implemented as such,The gettext () function is used to generate the verification code text that the getconfig () configurator will render.So we just need to inherit the configuration class and implement the text generation interface and override 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:where the program only executes the code in gettext (),The original code was written in gettext1 () and it is not executed. You can make a comparison.

public class chinesetext extends configurable implements textproducer {
  public string gettext () {
   int length=getconfig (). gettextproducercharlength ();
   //char [] chars=getconfig (). gettextproducercharstring ();
   string [] s=new string [] {"I", "Love", "Tie", "Tile", "and", "Sell", "Stop", "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 ();
  }
  /**
  * Example at noon
  * @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 before closing [,)
     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 last step is to change the value of the text implementation class in web.xml.Make the component call the class written by itself to generate a Chinese verification code.

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

Implementation legend:

Implementation of arithmetic operation verification code:

Same as the above Chinese verification code,We need to implement our own classes by inheriting classes and interfaces,And rewrite the functions in it,Then, by changing the configuration information, the component can call the class it implements to realize the diversification of the verification code form.

The decompiled code of the kaptchaservlet bytecode file is as follows:

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.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 ();
  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 ();
  }
 }
 }

Then implement the code of kaptchaservlet.java yourself as follows:Added the logic to implement the addition verification code to the original bytecode file,It 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 change the configuration at the beginning of web.xml to enable the component to call its own implemented servlet:

<servlet-name>kaptcha</servlet-name>
   <servlet-class>
    kaptchaservlet
   </servlet-class>

Implementation legend:

to sum up:

Here is just a simple implementation of the verification code,But it is not enough to use commercial projects.If the verification code is not to be cracked, various encryption algorithms are added.Even so,You can also search for the situation where a certain verification code is cracked.There is an underground database on the network,It stores our personal information,Those messages are sorted out one by one,This is terrible,But such a database exists objectively,Verification codes are an important part of protecting account passwords.Has become increasingly insecure,Because of the leakage of personal information,People who have enough information can scam you,The verification code is an important part.Recently, after a graduate was cheated with a verification code,The incident that all wealth was diverted within a few hours occurred.So please protect your verification code,Don't easily leak to others.

Of course we wo n’t sit still,There are many types of verification codes and they are becoming more and more difficult to crack.Things like speech recognition and facial recognition are familiar and not much to say.

Here we introduce a "new" concept of captcha:two-factor authentication.

Two-factor authentication is a system using time synchronization technology.A one-time password based on three variables:time, event, and key is used to replace the traditional static password.Each dynamic password card has a unique key,The key is also stored on the server side,The dynamic password card and the server are based on the same key each time they authenticate,The same random parameters (time, event) and the same algorithm calculate the authenticated dynamic password,To ensure consistent passwords,As a result, user authentication is achieved.Because the random parameters are different at each authentication,So the dynamic password generated every time is also different.Because the randomness of the parameters in each calculation guarantees the unpredictability of each password,Therefore, the security of the system is guaranteed at the most basic password authentication stage.Resolve significant losses due to password fraud,Protection against malicious intruders or man-made sabotage,Solve the intrusion problem caused by password leakage.

simply put,Two-factor authentication is an identity authentication system that works through what you know plus the two elements you can have together.For example, a bank card withdrawing money from atm is an example of a two-factor authentication mechanism.You need to know the combination of the withdrawal password and bank card to use it.The current two-factor authentication system is based on time synchronization.high market sharedkey two-factor authentication system,rsa two-factor authentication systemetc. As dkey adds support for SMS password authentication and SMS + token hybrid authentication,Compared with rsa, dkey two-factor authentication system is more competitive.

  • Previous How to add data in batch in Yii2
  • Next php file upload class complete example