giovedì 22 novembre 2012

Java generare random password

Metodo statico di utilità

public static String generateRandomPassword(int lunghezza){
  char[] caratteri={'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','è','ì','ò','ù','é','\'','&','(',')','?','!','/'};
  char[] maiuscole={'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'};
         char[] numeri={'0','1','2','3','4','5','6','7','8','9'};
  int lunghezzaChar=caratteri.length;
  int lunghezzaMaiuscole=maiuscole.length;
  int lunghezzaNumeri=numeri.length;
  StringBuffer sb=new StringBuffer();
  List<String> composizionePwd=new LinkedList<String>();
  for(int i=0;i<lunghezza;i++){
   int x = (int)(Math.random() * 10);
   if(x<=3){
    composizionePwd.add("C");
   }
   else if(x>3 && x<=6){
    composizionePwd.add("M");
   }
   else
   {
    composizionePwd.add("N");
   }
  }
  for(int i=0;i<lunghezza;i++){
   int elementoArray=0;
   if(composizionePwd.get(i).equals("M")){
    elementoArray= (int)(Math.random()*lunghezzaMaiuscole);
    sb.append(maiuscole[elementoArray]);
   }
   else if(composizionePwd.get(i).equals("C"))
   {
    elementoArray=(int)(Math.random()*lunghezzaChar);
    sb.append(caratteri[elementoArray]);
   }
   else
   {
    elementoArray=(int)(Math.random()*lunghezzaNumeri);
    sb.append(numeri[elementoArray]);
   }
  }
  return sb.toString();
 }



Nessun commento:

Posta un commento