我正在生成一个有6到10位数字的密码。
这是我的密码,随机密码为6-10位数,
val AB = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:<=>?@_!#%&()*+,-.~";
val rnd = new Random();
def randomPassword(): String = {
val len = rnd.nextInt(5) + 5
val sb = new StringBuilder(len);
for (i <- 0 to len)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}它工作得很好,但问题是,有时会给出所有的数字或字母。
每次我都要字母、数字和特殊字符的组合。有什么建议吗?
发布于 2014-05-17 08:37:03
首先生成所有字母的随机密码,然后根据需要用数字/特殊字符替换一些字母。
(顺便说一句,我不熟悉Scala,所以我将使用Java的语法,因为我不知道我是否在键入其他有效的东西。(对不起。)
// Split source string into letters, numbers, and specials
String AB = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String numbers = "0123456789";
String specials = ":<=>?@_!#%&()*+,-.~";
String randomPassword() {
StringBuilder sb = new StringBuilder();
int len = rnd.nextInt(5) + 5;
// Generate password with letters first. This part is the same as the original code.
for (int i = 0; i <= len; i++) {
sb.append(AB.charAt(rnd.nextInt(AB.length())));
}
// Generate an index to replace with a number
int numberIndex = rnd.nextInt(len);
// Generate an index to replace with a special character
int specialIndex;
do {
specialIndex = rnd.nextInt(len);
} while (specialIndex == numberIndex);
// Replace one letter with a number
sb.setCharAt(numberIndex, numbers.charAt(rnd.nextInt(numbers.length())));
// Replace one letter (or the number if you're unlucky) with a special character
sb.setCharAt(specialIndex, specials.charAt(rnd.nextInt(specials.length())));
}这是一个开始,有一个缺陷(只有一个数字+特殊字符),但它很容易修复。如果一个密码不符合您的标准,并且您保证得到一个在方法返回时有效的密码,那么这个解决方案也比生成全新的密码更有效。
发布于 2014-05-17 08:38:31
def randomPassword(): String = {
val len = rnd.nextInt(5) + 5
val sb = new StringBuilder(len);
for (i <- 0 to len)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
if(sb.toString is allString or allNum){
return randomPassword();
}
return sb.toString();
}发布于 2014-05-17 09:04:48
简单的解决方案imho将是(伪代码)
generate password
if no alphabet;
if not max length;
add an alphabet
else
change last letter with an alphabet
if no digit;
if not max length;
add an digit
else
change first letter with an digit
if no special;
if not max length;
add an special
else
change second letter with an special这绝不会减少熵,除非您已经有了最大长度密码。
https://stackoverflow.com/questions/23709261
复制相似问题