随机生成n位随机数(包含大写字母、小写字母、数字)
package com.java.weiju;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Random;
import org.apache.commons.lang.time.FastDateFormat;
public class BuildRandom {
private static final char[] BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
private static SecureRandom random = new SecureRandom();
public static String generateCode(int type, int length, String excludeString) {
StringBuffer verifyCode = new StringBuffer();
Random random = new Random();
switch (type) {
case 3:
length = length > 17 ? length : 17;
verifyCode.append(randomBase62(3) + FastDateFormat.getInstance("yyyyMMddhhmmss").format(new Date()) + randomBase62(length - 17));
break;
default:
break;
}
return verifyCode.toString();
}
public static String randomBase62(int length) {
byte[] randomBytes = new byte[length];
random.nextBytes(randomBytes);
return encodeBase62(randomBytes);
}
public static String encodeBase62(byte[] input) {
char[] chars = new char[input.length];
for (int i = 0; i < input.length; i++) {
chars[i] = BASE62[(input[i] & 0xFF) % BASE62.length];
}
return new String(chars);
}
public static void main(String[] args) {
System.out.println(new BuildRandom().generateCode(3, 10, null));
}
import java.security.SecureRandom;
import java.util.Date;
import java.util.Random;
import org.apache.commons.lang.time.FastDateFormat;
public class BuildRandom {
private static final char[] BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
private static SecureRandom random = new SecureRandom();
public static String generateCode(int type, int length, String excludeString) {
StringBuffer verifyCode = new StringBuffer();
Random random = new Random();
switch (type) {
case 3:
length = length > 17 ? length : 17;
verifyCode.append(randomBase62(3) + FastDateFormat.getInstance("yyyyMMddhhmmss").format(new Date()) + randomBase62(length - 17));
break;
default:
break;
}
return verifyCode.toString();
}
public static String randomBase62(int length) {
byte[] randomBytes = new byte[length];
random.nextBytes(randomBytes);
return encodeBase62(randomBytes);
}
public static String encodeBase62(byte[] input) {
char[] chars = new char[input.length];
for (int i = 0; i < input.length; i++) {
chars[i] = BASE62[(input[i] & 0xFF) % BASE62.length];
}
return new String(chars);
}
public static void main(String[] args) {
System.out.println(new BuildRandom().generateCode(3, 10, null));
}