Java-一种全数字短信验证码的实现方式(随机数哈希值+时间戳)

实现类

import java.security.SecureRandom;

public class Util {

    public static String getRandomVerificationCode(int expectLength){
        if(expectLength <= 0) {
            System.out.println("The input parameters [expectLength] do not meet the requirements");
            return "";
        }

        //取随机数
        SecureRandom sr = new SecureRandom();
        String random = sr.nextInt(1000000)+"";

        //获取随机数的哈希值
        int rdHash = random.hashCode();

        //获取时间戳
        long timeStamp = System.currentTimeMillis();

        //随机数的哈希值和时间戳进行异或
        long result = rdHash ^ timeStamp;

        //取模,根据传入的expectLength值确定长度。例如:4位则为10000,6位则为1000000
        long vcCode = (long) (result % Math.pow(10,expectLength));

        //若出现负数,进行取反
        vcCode = vcCode < 0 ? -vcCode : vcCode;

        //若结果不满足期望的位数,再通过随机数进行后补齐
        StringBuilder rtCode = new StringBuilder(vcCode+"");
        if(rtCode.length() < expectLength){
            int n = expectLength - rtCode.length();
            for (int i=0 ; i< n ; i++){
                rtCode.append(sr.nextInt(10));
            }
        }

        return rtCode.toString();
    }
}

测试方法

public static void main(String args[]) {  
      System.out.println("VerificationCode:" + getRandomVerificationCode(6));
}

执行结果

VerificationCode:303485
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值