Java实现验证码生成工具类-CheckSumBuilder

向右看齐 2023-02-21 06:35 90阅读 0赞

Java实现验证码生成工具类-CheckSumBuilder

  • 背景
  • 代码实现
  • 单元测试

背景

一版在Web系统登录、表单提交及资源下载等关键功能为了防止黑客遍历破解都会用到验证码功能,下面就来了解一下Java如何简单实现验证码的生成。

代码实现

CheckSumBuilder.java

  1. package com.utils;
  2. import java.security.MessageDigest;
  3. /** * 功能说明:验证码生成工具类 * 修改说明: * @author zheng * @date 2020年6月29日 下午1:33:26 * @version 0.1 */
  4. public class CheckSumBuilder {
  5. /** * 功能说明:计算并获取CheckSum * 修改说明: * @author zheng * @date 2020年6月29日 下午1:33:49 * @param appSecret 密码 * @param nonce 随机串 * @param curTime 当前时间戳 * @return 返回生成的验证码 */
  6. public static String getCheckSum(String appSecret, String nonce, String curTime) {
  7. return encode("sha1", appSecret + nonce + curTime);
  8. }
  9. /** * 功能说明:对参数进行MD5加密 * 修改说明: * @author zheng * @date 2020年6月29日 下午1:34:49 * @param requestBody 要加密的内容 * @return 返回MD5加密后的字符串 */
  10. public static String getMD5(String requestBody) {
  11. return encode("md5", requestBody);
  12. }
  13. /** * 功能说明:使用指定加密算法对字符串进行加密 * 修改说明: * @author zheng * @date 2020年6月29日 下午1:35:45 * @param algorithm 加密算法 * @param value 要加密的字符串 * @return 返回加密后的字符串 */
  14. private static String encode(String algorithm, String value) {
  15. if (value == null) {
  16. return null;
  17. }
  18. try {
  19. MessageDigest messageDigest
  20. = MessageDigest.getInstance(algorithm);
  21. messageDigest.update(value.getBytes());
  22. return getFormattedText(messageDigest.digest());
  23. } catch (Exception e) {
  24. throw new RuntimeException(e);
  25. }
  26. }
  27. /** * 功能说明:把字节数组格式化为16进制字符串 * 修改说明: * @author zheng * @date 2020年6月29日 下午1:37:10 * @param bytes 字节数组 * @return 返回格式化后的字符串 */
  28. private static String getFormattedText(byte[] bytes) {
  29. int len = bytes.length;
  30. StringBuilder buf = new StringBuilder(len * 2);
  31. for (int j = 0; j < len; j++) {
  32. buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
  33. buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
  34. }
  35. return buf.toString();
  36. }
  37. private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  38. }

单元测试

CheckSumBuilderTest.java

  1. package com.utils;
  2. import java.util.Date;
  3. import java.util.Random;
  4. import org.junit.Test;
  5. /** * 功能说明:CheckSumBuilder单元测试类 * 修改说明: * @author zheng * @date 2020年6月29日 下午1:54:27 * @version 0.1 */
  6. public class CheckSumBuilderTest {
  7. /** * 功能说明:验证码生成单元测试方法 * 修改说明: * @author zheng * @date 2020年6月29日 下午1:49:32 */
  8. @Test
  9. public void testGetCheckSum() {
  10. Random r = new Random();
  11. Date now = new Date();
  12. String appSecret = "zheng123";
  13. String nonce = "" + r.nextLong();
  14. String curTime = "" + now.getTime();
  15. String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
  16. System.out.println("checkSum = [" + checkSum.substring(0, 5) + "]");
  17. }
  18. }

发表评论

表情:
评论列表 (有 0 条评论,90人围观)

还没有评论,来说两句吧...

相关阅读