JavaUtil_04_验证码生成器

时间:2024-04-23 00:50:16

一、原理

验证码其实就是随机串。原理上可分为两种:

1.简单的验证码

直接通过字母和数字的ASCII码生成。本文采用的验证码就是这种。

2.复杂的验证码

通过一个随机串,一个指定串(如accesskey),和当前时间来进行验证码的生成,期间还经过SHA1加密。如网易云信的短信验证码生成器:

CheckSumBuilder.java

package com.ray.im.util;

import java.security.MessageDigest;

/**@desc  : 验证码生成工具
*
* @author: shirayner
* @date : 2017年9月26日 下午4:28:15
*/
public class CheckSumBuilder {
// 1.计算并获取CheckSum
public static String getCheckSum(String appSecret, String nonce, String curTime) {
return encode("sha1", appSecret + nonce + curTime);
} // 2.计算并获取md5值
public static String getMD5(String requestBody) {
return encode("md5", requestBody);
} // 3.根据加密方式进行加密
private static String encode(String algorithm, String value) {
if (value == null) {
return null;
}
try {
MessageDigest messageDigest
= MessageDigest.getInstance(algorithm);
messageDigest.update(value.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}

二、代码

1.CheckSumBuilder—验证码生成器

package com.ray.sms.aliyun.util;

import java.util.Random;

/**@desc  : 验证码工具类
*
* @author: shirayner
* @date : 2017年11月7日 上午10:07:46
*/
public class CheckSumBuilder { /**
* @desc :1.随机产生字符串
*
* @param length 字符串长度
* @param type 类型 (0: 仅数字; 2:仅字符; 别的数字:数字和字符)
* @return
* String 随机串
*/
public static String getRandomStr(int length, int type){
String str = "";
int beginChar = 'a';
int endChar = 'z'; // 只有数字
if (type == 0){
beginChar = 'z' + 1;
endChar = 'z' + 10;
}
// 只有小写字母
else if (type == 2){
beginChar = 'a';
endChar = 'z';
}
// 有数字和字母
else{
beginChar = 'a';
endChar = 'z' + 10;
} // 生成随机类
Random random = new Random();
for (int i = 0; i < length; i++){
int tmp = (beginChar + random.nextInt(endChar - beginChar));
// 大于'z'的是数字
if (tmp > 'z'){
tmp = '0' + (tmp - 'z');
}
str += (char) tmp;
} return str;
} /**
* @desc :2.获取6位数字验证码
*
* @return
* String 6位数字验证码
*/
public static String getCheckSum() {
return getRandomStr(6, 0);
} }

2.CheckSumBuilderTest—测试类

package com.ray.sms.aliyun.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test; /**@desc :
*
* @author: shirayner
* @date : 2017年11月7日 上午9:50:33
*/
public class CheckSumBuilderTest {
private static final Logger logger = LogManager.getLogger(CheckSumBuilderTest.class); @Test
public void testGetCheckSum() {
int len=100000;
String checkSum=null; for(int i=0;i<len;i++) {
checkSum= CheckSumBuilder.getCheckSum();
logger.info("checkSum:"+checkSum);
} } }

三、参考资料

1.http://bbs.****.net/topics/391946551

2.网易云服务器端API文档  (请参见   API checksum校验   这一部分)