生成必须包含字母,数字和特殊字符(6-10位)的随机字符串

时间:2014-05-17 08:34:00

标签: java scala random playframework passwords

我正在生成一个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();
    }

它工作正常,但问题是 有时它会提供所有数字或字母

我希望每次都能使用字母和数字以及特殊字符的组合。有什么建议吗?

7 个答案:

答案 0 :(得分:1)

首先生成所有字母的随机密码,然后根据需要用数字/特殊字符替换一些字母。

(顺便说一下,我不熟悉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())));
}

这是一个开始,并且有一个缺陷(只有一个数字+特殊字符),但它很容易修复。如果不满足您的标准,此解决方案也比生成全新密码更有效,并且您可以保证获得在方法返回时有效的密码。

答案 1 :(得分:1)

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();
    }

答案 2 :(得分:1)

简单的解决方案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

除非您已经拥有最大长度密码,否则永远不会减少熵。

答案 3 :(得分:1)

使用不可变数据结构比scala更惯用。以下代码有效。

  protected def nextChar(): Char = Random.nextPrintableChar()

  def randomString(length: Int = 10): String = {
    (0 until length).map(_ => nextChar()).mkString
  }

编辑: 为了确保字符串中始终存在数字,特殊字符和字母,我将分别生成每个字母类别,然后以函数方式随机连接它们或简单地使用Random.shuffle(characterList).mkString = D.

答案 4 :(得分:1)

这是解决该问题的惯用方法,它提供了更好的API。

object password {
  import scala.util.Random
  import scala.collection.immutable.Stream


  private def gen = Random.alphanumeric

  def get(len: Int): String = {    
    def build(acc: String, s: Stream[Char]): String = {
      if (s.isEmpty) acc
      else build(acc + s.head, s.tail)
    }

    build("", gen take len)
  }
}

让我们生成一些密码

1 to 25 foreach { _ => println(password get 8) }

您会看到类似的东西

YBk2UrOV
GD4eLexS
l8yxAkp9
ooQnaRpd
NgHAruB8
pMXpi4ad

注意:此解决方案可以进行几轮优化。例如。 @tailrecStringBuilder

答案 5 :(得分:0)

你可以应用while循环的原理。

  1. 将附加的密码存储到变量中。
  2. 使用while循环检查它是否包含数字和/或符号,如果不包含,则再次重新生成密码并将其存储到变量中。
  3. 当while循环自动中断时,返回变量。

答案 6 :(得分:-2)

你可以尝试这个,它适合我。

$length = 45;
$chars = array_merge(range(0,9), range('a','z'), range('A','Z'));
shuffle($chars);
$password = implode(array_slice($chars, 0, $length));

echo "This is the password: ".$password;

输出示例:

This is the password: wmU7KaZoOCIf4qn2tz5E06jiQgHvhR9dyBxrFYAePcDWk
相关问题