java - 编写密码生成器

时间:2018-06-08 20:25:32

标签: java passwords

我正在尝试用Java编写密码生成器,我确切地知道我想要实现这一目标的方式。我遇到的问题是我不确定如何实现我的目标。

我想使用for循环来搜索字符串,抓取一个随机字符,并将该字符存储在程序的内存中。然后,我想重复此过程,直到字符串包含用户指定的字符数,并将结果字符串打印到终端。

我怎样才能以简单明了的方式做到这一点?

尝试1:

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
/**
 * Write a description of class PasswordGenerator here.
 *
 * @author C.G.Stewart
 * @version 06/06/18
 */
public class PasswordGenerator
{
    private String input;
    private int i;
    private String newPass;
    /**
     * Constructor for objects of class Password
     */
    public PasswordGenerator()
    {
        // initialise instance variables
        input = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        ArrayList<String> Password = new ArrayList<String>();
        Scanner pass = new Scanner(System.in);
    }

    /**
     * This method generates a random alphanumeric string to be used as the new 
     * password
     */
    public void generatePassword()
    {
        Random rnd = new Random();
        for(i=1; i<=20; i++)
        {
            Math.random();
            System.out.println(input.charAt(i));
        }
        //newPass = System.out.println(input.charAt(i));
    }

    /**
     * This method takes the previously generated random alphanumeric string,
     * and outputs it to the screen. 
     */
    public void newPassword()
    {
        System.out.println(newPass);
    }
}

尝试2:

import java.util.Scanner;
import java.util.Random;
/**
 * Write a description of class Password here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Password
{
    // instance variables - replace the example below with your own
    private String index;

    /**
     * Constructor for objects of class Password
     */
    public Password()
    {
        // initialise instance variables
        index="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Scanner pass = new Scanner(System.in);
    }

    //Returns a random alphanumeric string of an inputted length
    public void printPassword()
    {
        for(int i=10; i<=20; i++)
        {
            while(i<=20)
            {
                Random rand = new Random();
                char letter;

                letter = index.charAt(i);
            }
            System.out.println(i);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

有多种方法可以做到,其中一些是:

可能性1:

public class PasswordGenerator {

       private static SecureRandom random = new SecureRandom();

        /** different dictionaries used */
        private static final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
        private static final String NUMERIC = "0123456789";
        private static final String SPECIAL_CHARS = "!@#$%^&*_=+-/";

        /**
         * Method will generate random string based on the parameters
         * 
         * @param len
         *            the length of the random string
         * @param dic
         *            the dictionary used to generate the password
         * @return the random password
         */
        public static String generatePassword(int len, String dic) {
        String result = "";
        for (int i = 0; i < len; i++) {
            int index = random.nextInt(dic.length());
            result += dic.charAt(index);
        }
        return result;
        }

取自:How to generate a random password in Java

可能性2: Random.ints

可能性3:

public final class RandomStringGenerator extends Object


 // Generates a 20 code point string, using only the letters a-z
 RandomStringGenerator generator = new RandomStringGenerator.Builder()
     .withinRange('a', 'z').build();
 String randomLetters = generator.generate(20);

 // Using Apache Commons RNG for randomness
 UniformRandomProvider rng = RandomSource.create(...);
 // Generates a 20 code point string, using only the letters a-z
 RandomStringGenerator generator = new RandomStringGenerator.Builder()
     .withinRange('a', 'z')
     .usingRandom(rng::nextInt) // uses Java 8 syntax
     .build();
 String randomLetters = generator.generate(20);

取自:Class RandomStringGenerator

答案 1 :(得分:0)

如果您只是想从字符串中抓取一个随机字符,为什么还需要使用for循环来搜索字符串?

为什么不直接生成一个随机整数并将其用作字符串索引?

类似的东西:

String str, password = ""; 

for (int i=0; i<passwordLength; i++){
    Random rand = new Random();
    int index = rand.nextInt(str.length());
    password += str.charAt(index);
}

答案 2 :(得分:0)

其他答案的一些提示:

慢速:

  • 不要在循环中使用string += "something",请使用StringBuilder

不安全:

  • 请勿使用Random,请使用SecureRandom

代码:

private static final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
private static final String NUMERIC = "0123456789";
private static final String SPECIAL_CHARS = "!@#$%^&*_=+-/";

private static final SecureRandom random = new SecureRandom();
private static final char[] dic = (ALPHA_CAPS + ALPHA + NUMERIC + SPECIAL_CHARS).toCharArray();

public static String generatePassword(int len) { 

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < len; i++) {
        sb.append(dic[random.nextInt(dic.length)]);
    }
    return sb.toString();
}