Monday, October 13, 2008

Random Password Generator

A lot of places we need to create and apply Random Password upon granting a resource or creation of OIM user via code. Here is a code that would generate one and will also allow you to specify the length of random password.

================================
RandomPasswordGenerator.java
================================

import java.util.Random;

public class RandomPasswordGenerator {

public static int DEFAULT_PASSWORD_LENGTH=8;
public static char[] Special_Character = {'!','@','#','$','%','^','&','*','(',')' };
public static char getSpecialCharacter(){
Random rand = new Random();
int randInt = rand.nextInt(10);
return Special_Character[randInt];
}

public static String getPassword(int n) {
if(n <=8 ){
n=DEFAULT_PASSWORD_LENGTH;
}
char[] pw = new char[n];
int c = 'A';
int r1 = 0;
int i=0;
String tempString = new String();
while(i< n){
r1 = (int)(Math.random() * 4);
l1: switch(r1) {
case 0: c = '0' + (int)(Math.random() * 10); break l1;
case 1: c = 'a' + (int)(Math.random() * 26); break l1;
case 2: c = 'A' + (int)(Math.random() * 26); break l1;
case 3: c = getSpecialCharacter(); break;
}

char c1 = (char)c;
boolean isExisting = false;
l2: for(int j=0; j < i; j++){
if(c1 == pw[j]){
isExisting = true;
break l2;
}
}
if(!isExisting){
pw[i] = (char)c;
i++;
}

}
return new String(pw);
}
public static void main(String args[]){
System.out.println(RandomPasswordGenerator.getPassword(8));
}
}

===============================
Output would be something like:
===============================
&3FVZfxb

No comments: