Tuesday, 6 January 2009

Simple password generator

Recently I've been working on a few projects so I hope to publish some outputs like Open Flash Chart library that allows publishing the charts using Java classes and custom JSON serializer.

Today I have something simple. The easy stuff I couldn't find out of the box so easily - password generator. There is my simple solution to this subject:


public class PasswordGenerator
{
private static char[] characters;

private static char[] special;

static
{
String chars = "abcdefghijklmnopqrstuvxyz";
characters = new char[chars.length()];
for( int i = 0; i < chars.length(); i++)
{
characters[i] = chars.charAt( i);
}
chars = "_@&*$-^#";
special = new char[chars.length()];
for( int i = 0; i < chars.length(); i++)
{
special[i] = chars.charAt( i);
}
}

public static String generate( int size)
{
StringBuilder builder = new StringBuilder();
for( int i = 0; i < size; i++)
{
double rand = Math.random();
if( rand < 0.6)
{
int charNum = (int)(Math.random() * (double)(characters.length - 1) * 2.0);

if( charNum >= characters.length)
{
builder.append( Character.toUpperCase( characters[charNum - characters.length]));
}
else
{
builder.append( characters[charNum]);
}
}
else if( rand < 0.8)
{
int number = (int)(Math.random() * 10.0);
builder.append( number);
}
else
{
int charNum = (int)(Math.random() * (double)(special.length - 1));

builder.append( special[charNum]);
}
}
return builder.toString();
}
}

No comments:

Post a Comment