Want more features on Pastebin? Sign Up, it's FREE!

Random Key Generator in Java

By: Shaun_B on Feb 6th, 2013  |  syntax: Java  |  size: 2.01 KB  |  views: 25  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import java.util.*;
  2. /**
  3.  * This will generate a random key of n length
  4.  *
  5.  * @author      Shaun_B
  6.  * @version     2013-02-06
  7.  * @note        This is a bit over-kill, the code could be condensed down
  8.  *              quite a bit, but I'll leave you to figure out which bits
  9.  *              could be made redundant, because I'm good like that.
  10.  */
  11. public class KeyGenerator
  12. {
  13.     public static byte getChar( byte x )
  14.     {
  15.         // Our look-up table:
  16.         byte [] character =
  17.         {
  18.             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  19.             'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  20.             '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '#',
  21.             '$', '%', '^', '&', '*', '(', ')'
  22.         };
  23.         // Error checking, in case a number is out of range (shouldn't happen, but always
  24.         // best to be safe:
  25.         if (x<0 || x>45)
  26.         {
  27.             // Generates a random number between 0 and 45:
  28.             Random randomNum = new Random();
  29.             int rnd = randomNum.nextInt(46);
  30.             // Returns random value:
  31.             return (byte)character[(byte)rnd];
  32.         }
  33.         else
  34.         {
  35.             // Otherwise, we're okay:
  36.             return (byte)character[x];
  37.         }
  38.     }
  39.     public static void main (String [] a)
  40.     {
  41.         // Key length:
  42.         int lengthOfKey = 12;
  43.         // Temp variable for key:
  44.         String generatedKey = "";
  45.         // Generates a new instance of a random number or something:
  46.         Random randomNum = new Random();
  47.         // Generates the random key in this loop:
  48.         for(int i=0; i<lengthOfKey; i++)
  49.         {
  50.             // Gets random number between 0 and 45:
  51.             int random = randomNum.nextInt(46);
  52.             // Calls the getChar method above, concatenating it to the String above:
  53.             generatedKey=generatedKey + (char)(getChar((byte)random));
  54.         }
  55.         // Now we print it:
  56.         System.out.printf("The generated key is: %s\n",generatedKey);
  57.     }
  58. }
clone this paste RAW Paste Data