Maven small project Registration Service (2) -- CAPTCHA Module

Source: Internet
Author: User

Verification code generation module. The configuration information is basically the same as that of the previous module. The account-CAPTCHA service is required to generate a Random verification code primary key. Then, you can use this primary key to ask the waiter to generate a verification code image. The corresponding value of this image should be random, finally, the user reads the value of the image with the naked eye, and submits the primary key and value of the verification code to the service for verification. The interface corresponding to this service can be defined as follows:

Code:

Public interface authorization {// generate the main component: String authorization () throws accountcaptchaexception; byte [] authorization (string captchakey) throws accountcaptchaexception; // verify the primary key and value Boolean validatecaptcha) throws accountcaptchaexception; List <string> getpredefinedtexts (); void setpredefinedtexts (list <string> predefinedtexts );}

The getpredefinedtext and set methods can predefine the value of the Verification Code image to improve the predictability of the program.

You can generate a Random verification code primary key, and define a class randomgenerator as follows:

public class RandomGenerator {private static String rangeString = "0123456789qwertyuiopasdfghjklzxcvbnm";public static synchronized String getRandomString(){Random random = new Random();StringBuffer result = new StringBuffer();for (int i = 0; i < 8; i++) {result.append(rangeString.charAt(random.nextInt(rangeString.length())));}return result.toString();}}

 

This method provides a thread-safe and static method. nextint () returns an integer greater than or equal to 0 and less than N.

Interface implementation:

public class AccountCaptchaServiceImpl implements AccountCaptchaService,InitializingBean {private DefaultKaptcha producer;private Map<String,String> captchaMap = new HashMap<String, String>();private List<String> preDefinedTexts;private int textCount = 0;
public void afterPropertiesSet() throws Exception {producer = new DefaultKaptcha();producer.setConfig(new Config(new Properties()));}public String generateCaptchaKey() throws AccountCaptchaException {String key = RandomGenerator.getRandomString();String value = getCaptchaText();captchaMap.put(key, value);return key;}private String getCaptchaText() {if(preDefinedTexts != null && !preDefinedTexts.isEmpty()){String text = preDefinedTexts.get(textCount);textCount = (textCount+1)%preDefinedTexts.size();return text;}else {return producer.createText();}}public byte[] generateCaptchaImage(String captchaKey)throws AccountCaptchaException {String text = captchaMap.get(captchaKey);if (text == null) {throw new AccountCaptchaException("captaha key"+captchaKey+"not found");}BufferedImage image = producer.createImage(text);ByteArrayOutputStream out = new ByteArrayOutputStream();try {ImageIO.write(image,"jpg" , out);} catch (Exception e) {throw new AccountCaptchaException("failed to write image");}return out.toByteArray();}public boolean validateCaptcha(String captchaKey, String captchaValue)throws AccountCaptchaException {String text = captchaMap.get(captchaKey);if (text == null) {throw new AccountCaptchaException("captaha key"+captchaKey+"not found");}if (text.equals(captchaValue)) {captchaMap.remove(captchaKey);return true;}else {return false;}}public List<String> getPreDefinedTexts() {return preDefinedTexts;}public void setPreDefinedTexts(List<String> preDefinedTexts) {this.preDefinedTexts = preDefinedTexts;}}

Afterpropertiesset will be called during framework initialization. This method initializes the verification code generator and provides default configuration.

Generatecaptchakey () generates a Random verification code primary key. Each primary key is associated with a verification code string, and the association is stored in captchamap for future verification. The purpose of a primary key is only to identify the verification code image, which has no practical significance. Getcaptchatext () is used to generate a verification code string. When predefinedtexts exists or is empty, it creates a random string using the verification code image generator producer. When predefinedtexts is not empty, the value of the string list is read sequentially. Predefinedtexts has a set of get and STET methods, which allows you to predefine the value of the verification code string. The generatecaptchaimage method can generate a bufferedlmage through producer. The subsequent code converts the image object into a JPG byte array and returns it. With this byte array, you can save it as a file or display it on a webpage at will.

The user obtains the verification code image and the primary key. The system recognizes the string information contained in the image and sends the value of the verification code along with the primary key to the validatecaptcha Method for verification.

Test code:
public class AccountCaptchaServiceTest {private AccountCaptchaService service;@Beforepublic void prepare() throws Exception{ApplicationContext ctx = new ClassPathXmlApplicationContext("account_captcha.xml");service = (AccountCaptchaService) ctx.getBean("accountCaptchaService");}@Testpublic void testGenerateCaptcha() throws Exception{String captchaKey = service.generateCaptchaKey();assertNotNull(captchaKey);byte[] captchaImage = service.generateCaptchaImage(captchaKey);assertTrue(captchaImage.length>0);File image = new File("target"+captchaKey +".jpg");OutputStream output = null;try {output = new FileOutputStream(image);output.write(captchaImage);} finally {if (output != null) {output.close();}}assertTrue(image.exists() && image.length()>0);}@Testpublic void testValidateCaptchaCorrect() throws Exception{List<String> preDefinedTexts = new ArrayList<String>();preDefinedTexts.add("12345");preDefinedTexts.add("abcde");service.setPreDefinedTexts(preDefinedTexts);String captchaKey = service.generateCaptchaKey();service.generateCaptchaImage(captchaKey);assertTrue(service.validateCaptcha(captchaKey, "12345"));captchaKey = service.generateCaptchaKey();service.generateCaptchaImage(captchaKey);assertTrue(service.validateCaptcha(captchaKey, "abcde"));}@Testpublic void testValidateCaptchaIncorrect()throws Exception{List<String> preDefinedTexts = new ArrayList<String>();preDefinedTexts.add("12345");service.setPreDefinedTexts(preDefinedTexts);String captchaKey = service.generateCaptchaKey();service.generateCaptchaImage(captchaKey);assertFalse(service.validateCaptcha(captchaKey, "67809"));}}

  

public class RandomGeneratorTest {@Testpublic void testGetRandomTest() throws Exception{Set<String> randoms = new HashSet<String>(100);for (int i = 0; i < 100; i++) {String random = RandomGenerator.getRandomString();assertFalse(randoms.contains(random));randoms.add(random);}}}

This test code is easy to understand. After running the test, you can view the generated Verification Code image in the target directory of the project.

 

Maven small project Registration Service (2) -- CAPTCHA Module

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.