一、原理

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

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' };
}
View Code

相关文章:

  • 2021-11-05
  • 2021-10-19
  • 2022-02-16
  • 2021-10-30
  • 2021-12-03
猜你喜欢
  • 2021-10-19
  • 2021-10-19
  • 2021-07-14
  • 2022-12-23
  • 2021-12-22
  • 2021-11-01
相关资源
相似解决方案