01: /*
02: * Copyright 2001-2007 Geert Bevin <gbevin[remove] at uwyn dot com>
03: * Distributed under the terms of either:
04: * - the common development and distribution license (CDDL), v1.0; or
05: * - the GNU Lesser General Public License, v2.1 or later
06: * $Id: PasswordGenerator.java 3634 2007-01-08 21:42:24Z gbevin $
07: */
08: package com.uwyn.rife.tools;
09:
10: import java.util.Random;
11:
12: public abstract class PasswordGenerator {
13: public static final int DIGITS_ONLY = 0;
14: public static final int LETTERS_ONLY = 1;
15: public static final int MIXED = 2;
16:
17: private static final String LETTERS = "qwertyuiopzxcvbnmasdfghjklAZERTYUIOPMLKJHGFDSQWXCVBN";
18: private static final int LETTERS_LENGTH = LETTERS.length();
19: private static final String NUMBERS = "1357924680";
20: private static final int NUMBERS_LENGTH = NUMBERS.length();
21:
22: public static String get(int length) {
23: return get(new Random(System.currentTimeMillis()), length,
24: MIXED);
25: }
26:
27: public static String get(int length, int type) {
28: return get(new Random(System.currentTimeMillis()), length, type);
29: }
30:
31: public static String get(Random random, int length, int type) {
32: if (length <= 0)
33: throw new IllegalArgumentException(
34: "length has to be bigger zero");
35: if (type != DIGITS_ONLY && type != LETTERS_ONLY
36: && type != MIXED)
37: throw new IllegalArgumentException("invalid type");
38:
39: StringBuilder generated_password = new StringBuilder("");
40: boolean type_selector = false;
41:
42: for (int i = 0; i < length; i++) {
43: type_selector = random.nextBoolean();
44:
45: // characters
46: if (LETTERS_ONLY == type || type != DIGITS_ONLY
47: && type_selector) {
48: char c = LETTERS
49: .charAt((int) ((double) LETTERS_LENGTH * random
50: .nextDouble()));
51: if (random.nextDouble() > 0.5D) {
52: c = Character.toUpperCase(c);
53: }
54: generated_password.append(c);
55: }
56: // digits
57: else {
58: generated_password.append(NUMBERS
59: .charAt((int) ((double) NUMBERS_LENGTH * random
60: .nextDouble())));
61: }
62: }
63:
64: return generated_password.toString();
65: }
66: }
|