import java.util.*;
/**
* This will generate a random key of n length
*
* @author Shaun_B
* @version 2013-02-06
* @note This is a bit over-kill, the code could be condensed down
* quite a bit, but I'll leave you to figure out which bits
* could be made redundant, because I'm good like that.
*/
public class KeyGenerator
{
public static byte getChar( byte x )
{
// Our look-up table:
byte [] character =
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '#',
'$', '%', '^', '&', '*', '(', ')'
};
// Error checking, in case a number is out of range (shouldn't happen, but always
// best to be safe:
if (x<0 || x>45)
{
// Generates a random number between 0 and 45:
Random randomNum = new Random();
int rnd = randomNum.nextInt(46);
// Returns random value:
return (byte)character[(byte)rnd];
}
else
{
// Otherwise, we're okay:
return (byte)character[x];
}
}
public static void main (String [] a)
{
// Key length:
int lengthOfKey = 12;
// Temp variable for key:
String generatedKey = "";
// Generates a new instance of a random number or something:
Random randomNum = new Random();
// Generates the random key in this loop:
for(int i=0; i<lengthOfKey; i++)
{
// Gets random number between 0 and 45:
int random = randomNum.nextInt(46);
// Calls the getChar method above, concatenating it to the String above:
generatedKey=generatedKey + (char)(getChar((byte)random));
}
// Now we print it:
System.out.printf("The generated key is: %s\n",generatedKey);
}
}