package demo.day.web
import java.util.Random
/**
* @description: demo
* @author: nice
* @created: 2022/06/17 08:58
*/
public class demo2 {
private final static Integer num = 9
private final static Integer numSum = 60
/**
* 设置规则字符串
* */
private String setCode(String code,String number){
int start = num / 2
int end = num - start - 1
StringBuffer stringBuffer = new StringBuffer(code)
// 取前3个字符放第4位开始
stringBuffer.replace(3,start - 1,number.substring(0,start))
// 取后3个字符放末尾倒数第4位开始
StringBuffer stringBufferOne = new StringBuffer(stringBuffer.toString())
stringBufferOne.replace(stringBufferOne.length() - end - 1 ,stringBufferOne.length() - 3 ,number.substring(end))
return stringBufferOne.toString()
}
/**
* 验证规则字符串
* */
private boolean isCheck(String code){
int start = num / 2
int end = num - start
String num = code.substring(3,start + 3)
num += code.substring(code.length() - ( 3 + end),code.length() - 3)
int sum = 0
for (int i = 0
sum += getInt(num.substring(i,i+1))
}
return sum == numSum
}
private int getInt(String str){
try{
return Integer.parseInt(str)
}catch (Exception e){
return 0
}
}
/**
* 生成规则字符串
* */
private String getStringEncryption(int encryptionNumber){
if(encryptionNumber > 32 || encryptionNumber < 16){
throw new RuntimeException(" 只能填写16~32之间数字 ")
}
// 生成一个32位随机串
String code = getString(encryptionNumber)
// 生成6位数字且相加等于24
String number = getRandomNumber(num,numSum)
// 设置规则
String codeNew = setCode(code,number)
return codeNew
}
/**
* 获取随机数和等于sum
* */
private String getRandomNumber(int num,int sum){
// 随机数 * 9 不能小于等于 sum
if(num <= 0 || num * 9 <= sum){
return null
}
String str = ""
int yj = 0
int yjh = 0
int yjsy = sum
for(int i = 0
Integer random = getRandom()
if(yjsy > 9 * (num - i - 1)){
if(yjsy - 9 > 0){
str += "9"
yjh += 9
yjsy -= 9
yj += 9
continue
}
str += yjsy
continue
}
yj += random
if(yj <= sum){
str += random
}else if(yjh >= sum){
str += "0"
}else if(yjh <= sum){
str += (sum - yjh)
}
yjh += random
yjsy -= random
}
return str
}
/**
* 获取随机数 [0-9]
* */
private Integer getRandom(){
Random r = new Random()
return r.nextInt(10)
}
/**
* 获取随机字符串(字母与数字)
* */
private String getString(int n) {
Random r = new Random()
String code = ""
for(int i = 0
int type = r.nextInt(3)
switch(type) {
case 0://大写字母
char c0 = (char)(r.nextInt(26) + 65)
code += c0
break
case 1 ://小写字母
char c1 = (char)(r.nextInt(26) + 97)
code += c1
break
case 2://数字
int m = r.nextInt(10)
code += m
break
}
}
return code
}
public static void main(String[] args) {
demo2 s = new demo2()
String code = s.getStringEncryption(32)
System.out.println("输出加密的code = " + code);
boolean isTrue = s.isCheck(code);
System.out.println("验证加密的code = " + isTrue);
}
}