生成 图片验证码

来源:互联网 发布:大和抚子 知乎 编辑:程序博客网 时间:2024/05/16 09:02
/**
* 生成验证码
* @param response
*/
@RequestMapping("/valicode")
public void actionValicode(HttpServletResponse response){
BufferedImage image = new BufferedImage(90, 30, BufferedImage.TYPE_INT_RGB);

String valicode = Valicode.drawImage(image) ; 

//将验证码加密后保存到cookie中,用于后期对输入的验证码的校验

String encryptString = BaseUtil.encrypt(valicode.toUpperCase(), BaseUtil.VALICODE_SALT) ;

Cookie cookie = new Cookie("vali", encryptString);

//cookie.setHttpOnly(true);//增强安全,避免一定程度的跨站攻击,tomcat7

cookie.setMaxAge(600);cookie.setPath("/");

response.addCookie(cookie);


response.setHeader("Pragma", "no-cache");

response.setHeader("Cache-Control", "no-cache");

response.setDateHeader("Expires", 0);

response.setContentType("image/jpeg");

ServletOutputStream output = null ;

try {

output = response.getOutputStream();

ImageIO.write(image, "jpeg", output) ;

output.flush();output.close();} 

catch (IOException e) {

}

}

/**画图片验证码**/

   public static String drawImage(BufferedImage bf){

    int width = 90 , height = 30 , codeCount = 4 , fontHeight = 20 , codeX = 16 , codeY = 20 , red = 0 , green = 0 , blue = 0 ;

    Graphics grap = bf.getGraphics();

    Random random = new Random();

    grap.setColor(Color.WHITE);

    grap.fillRect(0, 0, width, height);

    char[] chars = { '2', '3', '4', '5', '6','7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' ,'J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z',

'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' ,'j','k','m','n','p','q','r','s','t','v','w','x','y','z'};

    Font font = new Font("Fixedsys", Font.BOLD, fontHeight) ;

    grap.setFont(font);

    grap.setColor(Color.BLACK);

    grap.drawRect(0, 0, width - 1, height - 1 );

    for(int i = 1 ; i < 30 ; i ++ ){

     int x = random.nextInt(width);

            int y = random.nextInt(height);

            int xl = random.nextInt(15);

            int yl = random.nextInt(15);

            grap.drawLine(x, y, x + xl, y + yl);

    }

    StringBuilder sb = new StringBuilder() ;

    for(int j = 0 ; j < codeCount ; j ++ ){

int code = ThreadLocalRandom.current().nextInt(chars.length);

String rand = String.valueOf(chars[code]);

grap.setColor( new Color( random.nextInt(100) , random.nextInt(100) , random.nextInt(100) ) );

grap.drawString(rand, codeX * ( j + 1) , codeY );

sb.append(rand) ; 

    }

    grap.dispose();

    return sb.toString();

    }



/**
* 校验验证码
*/
@RequestMapping(value= "/checkCode", produces = "application/json;charset=UTF-8" , method = RequestMethod.POST)
@ResponseBody
public Boolean actionDoLogin(@RequestParam String authCode, HttpServletRequest request, HttpServletResponse response){

if (StringUtils.isBlank(authCode)) {

return false;

}

Cookie Vcookie = BaseUtil.getCookie(request, "vali");

String authCookie = (Vcookie!=null) ? Vcookie.getValue() : "" ;

boolean auth = BaseUtil.validate(authCookie, authCode.toUpperCase(),BaseUtil.VALICODE_SALT);

return auth;

}


public static boolean validate(String md5RandomCode,String inputRandomCode, String salt) {

if (StringUtil.isBlank(md5RandomCode)|| StringUtil.isBlank(inputRandomCode)) {

return false;

}

inputRandomCode = inputRandomCode.toUpperCase();

//对用户输入进来的验证码重新加密后 和 保存到cookie中的验证码对比

inputRandomCode = encrypt(inputRandomCode, salt);

return inputRandomCode.equals(md5RandomCode);

}


//其中BaseUtil.VALICODE_SALT的定义为 

 public static final String VALICODE_SALT = "treasureFinal@heyin~salt";

原创粉丝点击