实现类
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;
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