Java Password Generate generatePassword(int minLen, int maxLen, int noOfCAPSAlpha, int noOfDigits, int noOfSplChars)

Here you can find the source of generatePassword(int minLen, int maxLen, int noOfCAPSAlpha, int noOfDigits, int noOfSplChars)

Description

generate Password

License

Mozilla Public License

Declaration

public static char[] generatePassword(int minLen, int maxLen, int noOfCAPSAlpha, int noOfDigits,
            int noOfSplChars) 

Method Source Code


//package com.java2s;
//License from project: Mozilla Public License 

import java.util.Random;

public class Main {
    private static final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
    private static final String NUM = "0123456789";
    private static final String SPL_CHARS = "!@#$%^&*_=+-/";

    public static char[] generatePassword(int minLen, int maxLen, int noOfCAPSAlpha, int noOfDigits,
            int noOfSplChars) {
        if (minLen > maxLen)
            throw new IllegalArgumentException("Min. Length > Max. Length!");
        if ((noOfCAPSAlpha + noOfDigits + noOfSplChars) > minLen)
            throw new IllegalArgumentException(
                    "Min. Length should be atleast sum of (CAPS, DIGITS, SPL CHARS) Length!");
        Random rnd = new Random();
        int len = rnd.nextInt(maxLen - minLen + 1) + minLen;
        char[] pswd = new char[len];
        int index = 0;
        for (int i = 0; i < noOfCAPSAlpha; i++) {
            index = getNextIndex(rnd, len, pswd);
            pswd[index] = ALPHA_CAPS.charAt(rnd.nextInt(ALPHA_CAPS.length()));
        }//from www. jav a 2 s . co m
        for (int i = 0; i < noOfDigits; i++) {
            index = getNextIndex(rnd, len, pswd);
            pswd[index] = NUM.charAt(rnd.nextInt(NUM.length()));
        }
        for (int i = 0; i < noOfSplChars; i++) {
            index = getNextIndex(rnd, len, pswd);
            pswd[index] = SPL_CHARS.charAt(rnd.nextInt(SPL_CHARS.length()));
        }
        for (int i = 0; i < len; i++) {
            if (pswd[i] == 0) {
                pswd[i] = ALPHA.charAt(rnd.nextInt(ALPHA.length()));
            }
        }
        return pswd;
    }

    private static int getNextIndex(Random rnd, int len, char[] pswd) {
        int index = rnd.nextInt(len);
        while (pswd[index = rnd.nextInt(len)] != 0)
            ;
        return index;
    }
}

Related

  1. generatePassword(int lenght)
  2. generatePassword(int length)
  3. generatePassword(int length)
  4. generatePassword(int length, boolean special)
  5. generatePassword(int length, String combination)
  6. generateString(final String letters, int length)
  7. generateString(int length)
  8. generateString(int length)
  9. generateString(int length)