Friday, April 1, 2011

Generate dynamic password in java with varying length

1:  package test; 
2: import java.util.Random;
3: /**
4: * @author SALPE NEELESH
5: *
6: */
7: public class TestClass {
8: private static final char[] alphaNumericChars = { 'A', 'B', 'C', 'D', 'E',
9: 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
10: 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e',
11: 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
12: 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
13: '5', '6', '7', '8', '9' };
14: private static final int MIN_LENGTH = 8;
15: private static final int MAX_LENGTH = 11;
16: public static synchronized String generatePassword() {
17: Random random = new Random();
18: int lengthOfpassword = MIN_LENGTH
19: + random.nextInt((MAX_LENGTH - MIN_LENGTH) + 1);
20: StringBuffer sb = new StringBuffer();
21: for (int i = 0; i < lengthOfpassword; i++) {
22: sb.append(alphaNumericChars[random
23: .nextInt(alphaNumericChars.length)]);
24: }
25: return sb.toString();
26: }
27: public static void main(String[] args) {
28: for (int i = 0; i < 10; i++) {
29: generatePassword();
30: }
31: }
32: }

No comments: