Secret动态密码生成算法
2019-12-26 本文已影响0人
丨逐风者丨
import android.text.TextUtils;
import android.util.Log;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Created by ZengCS on 2018/1/19.
* E-mail:zcs@sxw.cn
* Add:成都市天府软件园E3-3F
*/
public class SxwDynamicPwdGenerator {
private static final String TAG = "SxwDynamicPwdGenerator";
private static final String PRIVATE_KEY = "cn.sxw.android.launcher";// 私钥
public static final int REFRESH_DELAY = 60;// 60秒刷一次
public static String getDynamicPwdString(String deviceId) {
List<String> strings = generateDynamicPwd(deviceId);
if (strings == null || strings.size() == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (String pwd : strings) {
sb.append(pwd);
}
return sb.toString();
}
public static List<String> generateDynamicPwd(String deviceId) {
List<String> mItems = new ArrayList<>();
String userSrc = MD5Util.getMd5(deviceId + "-" + getTime());
String pwdSrc = MD5Util.getMd5(deviceId + "-" + getTime() + "-" + PRIVATE_KEY);
Log.d(TAG, "generateDynamicPwd: userSrc = " + userSrc);
Log.d(TAG, "generateDynamicPwd: pwdSrc = " + pwdSrc);
if (TextUtils.isEmpty(pwdSrc)) {
return null;
}
mItems.clear();
for (int i = 0; i < 6; i++) {
int start = i * 5;
int end = 5 * (i + 1);
if (i == 4) {
end += 1;
}
if (i == 5) {
start += 1;
end += 2;
}
String tempPwd = pwdSrc.substring(start, end);
//log("十六进制:" + tempPwd);
BigInteger bigInteger = new BigInteger(tempPwd, 16);
//log("十进制:" + bigInteger);
String resultNumber = NumberUtil.bigIntegerToSingleNumber(bigInteger.toString());
//log("resultNumber = " + resultNumber);
mItems.add(resultNumber);
}
return mItems;
}
private static String getTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm", Locale.CHINA);
String src = dateFormat.format(new Date());
if (REFRESH_DELAY == 30) {
int currSecond = getCurrSecond();
if (currSecond < 30) {
src += "00";
} else {
src += "30";
}
} else {
src += "00";
}
return src;
}
public static int getCurrSecond() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.SECOND);
}
}
public class NumberUtil {
public static String bigIntegerToSingleNumber(String bigInteger) {
int result = 0;
for (int j = 0; j < bigInteger.length(); j++) {
String s = bigInteger.substring(j, j + 1);
result += Integer.parseInt(s);
}
if (String.valueOf(result).length() > 1) {
return bigIntegerToSingleNumber(String.valueOf(result));
}
return String.valueOf(result);
}
}