Tuesday, March 4, 2014

Generating Password Using SecureRandon class

Use of java.security.SecureRandom class



File 1: Passwordgenerator.java


import java.util.ArrayList;
import java.util.prefs.InvalidPreferencesFormatException;
import java.security.SecureRandom;
import java.text.ParseException;

public class Passwordgenerator {
private int length;

private boolean lowercaseIncluded;
private boolean numbersIncluded;
private boolean othersIncluded;
private boolean uppercaseIncluded;

private String password;
private String template;
static SecureRandom RANDOM = new SecureRandom();
Passwordgenerator() {

password = "";
template = "";

length = 8;

lowercaseIncluded = true;
uppercaseIncluded = true;
numbersIncluded = true;

othersIncluded = true;
generatePassword();
}
private boolean flagsOK() {
return lowercaseIncluded
|| uppercaseIncluded
|| numbersIncluded
|| othersIncluded;
}
private static char randomLowercase() {



char c =(char) (97 + (int) (RANDOM.nextDouble() * 26));
if(c=='l'){
return randomLowercase();
}
return c;
}
private static char randomUppercase() {

char c = (char) (65 + (int) (RANDOM.nextDouble() * 26));
if(c=='I'){
return randomUppercase();
}
return c;
}
private static char randomOther() {
char c =(char) (33 + (int) (RANDOM.nextDouble() * 15));
//if(c=='"'){
return '!';
//}
//return c;
}


/**
* @return a random character from '0' to '9'
*/
private static char randomNumber() {



return (char) (48 + (int) (RANDOM.nextDouble() * 10));
}

public void generatePassword() /* throws InvalidPreferencesFormatException, ParseException */ {
  // clear password if necessary
if (password.length() != 0) {
password = "";
}


if (template.length() > 0) {
length = template.length();
for (int i = 0; i < length; i++) {

switch (template.charAt(i)) {
case 'a' :
password += randomLowercase();
break;

case 'A' :
password += randomUppercase();
break;

case 'n' :
case 'N' :
password += randomNumber();
break;

case 'o' :
case 'O' :
password += randomOther();
break;

}
}
} else {

ArrayList flags = new ArrayList();
if (lowercaseIncluded) {
flags.add(new randomLowercase());
}
if (uppercaseIncluded) {
flags.add(new randomUppercase());
}
if (othersIncluded) {
flags.add(new randomOther());
}
if (numbersIncluded) {
flags.add(new randomNumber());
}

int flagLength = flags.size();



for (int i = 0; i < length; i++) {

               password += ((randomCharacter) flags.get( (int) (RANDOM.nextDouble() * flagLength)  ))
                       .execute();
}
}
}

/**
* @return the length of the generated password
*/
public int getLength() {
return length;
}

/**
* @return the generated password
*/
public String getPassword() {
return password;
}

/**
* @return password template
*/
public String getTemplate() {
return template;
}
/**
* @return lowercaseIncluded
*/
public boolean isLowercaseIncluded() {
return lowercaseIncluded;
}

/**
* @return numbersIncluded
*/
public boolean isNumbersIncluded() {
return numbersIncluded;
}

/**
* @return othersIncluded
*/
public boolean isOthersIncluded() {
return othersIncluded;
}

/**
* @return uppercaseIncluded
*/
public boolean isUppercaseIncluded() {
return uppercaseIncluded;
}

/**
* @param length, enforced to be a positive integer >= 3.
*/
public void setLength(int length) {
this.length = (length < 3) ? 3 : length;
}

/**
* @param b
*/
public void setLowercaseIncluded(boolean b) throws InvalidPreferencesFormatException {
lowercaseIncluded = b;

// did we turn off the last flag?  if so
// turn it back on and report error
if (b == false && !flagsOK()) {
lowercaseIncluded = true;
throw new InvalidPreferencesFormatException("At least one flag must be on to generate a password");
}
}

/**
* @param b
*/
public void setNumbersIncluded(boolean b) throws InvalidPreferencesFormatException {
numbersIncluded = b;


if (b == false && !flagsOK()) {
numbersIncluded = true;
throw new InvalidPreferencesFormatException("At least one flag must be on to generate a password");
}
}

/**
* @param b
*/
public void setOthersIncluded(boolean b) throws InvalidPreferencesFormatException {
othersIncluded = b;

// did we turn off the last flag?  if so
// turn it back on and report error
if (b == false && !flagsOK()) {
othersIncluded = true;
throw new InvalidPreferencesFormatException("At least one flag must be on to generate a password");
}
}

/**
* @param string
*/
public void setTemplate(String template) throws ParseException {
// make sure the template contains only legal characters
for (int i = 0; i < template.length(); i++) {
switch (template.charAt(i)) {
case 'a' :
case 'A' :
case 'n' :
case 'N' :
case 'o' :
case 'O' :
break;

default :
throw new ParseException("Password template contains an invalid character", i);
}
}
this.template = template;
}

/**
* Clears the password template,making generation rely on the flags.
*
*/
public void clearTemplate() {
template = "";
}

/**
* @param b
*/
public void setUppercaseIncluded(boolean b) throws InvalidPreferencesFormatException {
uppercaseIncluded = b;

// did we turn off the last flag?  if so
// turn it back on and report error
if (b == false && !flagsOK()) {
uppercaseIncluded = true;
throw new InvalidPreferencesFormatException("At least one flag must be on to generate a password");
}
}

/*--------------------------------------------------------
Wrapper classes and interface to mimic the array of
function references functionality required.
----------------------------------------------------------*/
private static class randomLowercase implements randomCharacter {
public char execute() {
return Passwordgenerator.randomLowercase();
}
}

private static class randomUppercase implements randomCharacter {
public char execute() {
return Passwordgenerator.randomUppercase();
}
}

private static class randomOther implements randomCharacter {
public char execute() {
return Passwordgenerator.randomOther();
}
}

private static class randomNumber implements randomCharacter {
public char execute() {
return Passwordgenerator.randomNumber();
}
}

private static interface randomCharacter {
char execute();
}

}




File 2: Test.java


import java.security.SecureRandom;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Random;

public class Test {

/**
* @param args
*/
static String pwd;
public static void main(String[] args) {

String userName="mankar.m0(@gmail.com";
    try {
        boolean flag;
        String[] templets =
        { "aaAnanaA", "aaannnAnaA", "aanAnnnaA", "aAAnnAaaA", "aaAnaaAA","aaAnnnaA", "aaananAnaA", "aanAnnnaa", "aAAanAaan", "aaAnaaAn"  };
       
        System.out.println("Uniq ID "+new java.security.SecureRandom().nextLong());

        System.out.println("Uniq ID twwwwwo   "+new java.util.Random().nextLong());
       
        System.out.println("Math.random value of "+(Math.random()));
       
        System.out.println("SecureRandom value of "+new java.security.SecureRandom().nextDouble());
        Passwordgenerator passGen = new Passwordgenerator();
        SecureRandom RANDOM = new SecureRandom();
        //SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
       
        //passGen.setTemplate(templets[sr.nextInt(20)]);
       
        passGen.setTemplate(templets[(int)(RANDOM.nextDouble()*4)]);
       
        do {
        passGen.generatePassword();
        pwd = passGen.getPassword();
        flag = usernameCheck(userName, pwd);
        //flag will be true is the password is not correct
        } while (flag);

    } catch (ParseException e) {
   
    }catch(Exception e ){

    }
    System.out.println("Manish   "+pwd.length()+"  "+pwd);
   
    Test t1 = new Test();
    t1.generateId(10);
}

private static boolean  usernameCheck(String uname, String pwd) {
return (
(pwd.toLowerCase()).matches(".*" + (uname.toLowerCase()) + ".*"));
}

protected  String generateId( final int number )
{
 Random rand = new Random( number );

 //SecureRandom rand = new SecureRandom();

  StringBuffer id = new StringBuffer();
  String[] scrambled = new String[3];
  StringBuffer nonrandom = scrambleNumber( number );
  scrambled[0] = extractChar( scrambleNumber( rand.nextInt() ) );
  scrambled[1] = extractChar( scrambleNumber( rand.nextInt() ) );
  String first = nonrandom.substring( 0, 1 );
  String rest = nonrandom.substring( 1 );
  id.append( first );
  id.append( scrambled[0] );
  id.append( rest );
  id.append( scrambled[1] );
  System.out.println(id);
  return id.toString();
}

protected String extractChar( StringBuffer random )
{
  if ( random.length() > 3 ) {
    return random.substring( 3, 4 );
  }
  return random.substring( 0, 1 );
}
/**
 * <p>
 *
 * </p>
 * @param number the number
 * @return StringBuffer
 */
private StringBuffer scrambleNumber( final int number )
{
  int abs = Math.abs( number );
  int divisor = 27;
  int mod = abs % divisor;
  int div = abs / divisor;
  if ( div == 0 ) {
    return new StringBuffer( scrambleDigit( mod ) );
  } else {
    return scrambleNumber( div ).append( scrambleDigit( mod ) );
  }
}

private String scrambleDigit( final int digit )
{
  HashMap map = new HashMap();
  map.put( "0", "D" );
  map.put( "1", "N" );
  map.put( "2", "C" );
  map.put( "3", "K" );
  map.put( "4", "A" );
  map.put( "5", "M" );
  map.put( "7", "G" );
  map.put( "8", "X" );
  map.put( "9", "L" );
  map.put( "10", "H" );
  map.put( "11", "W" );
  map.put( "12", "4" );
  map.put( "13", "Y" );
  map.put( "14", "Q" );
  map.put( "15", "5" );
  map.put( "16", "J" );
  map.put( "17", "3" );
  map.put( "18", "E" );
  map.put( "19", "8" );
  map.put( "20", "V" );
  map.put( "21", "6" );
  map.put( "22", "T" );
  map.put( "23", "P" );
  map.put( "24", "B" );
  map.put( "25", "9" );
  map.put( "26", "F" );

  String key = digit + "";

  if(map.containsKey( key ))
  {
    return (String)map.get( key );
  }
  else
  {
    return "";
  }
}
}




No comments:

Post a Comment