生成強密碼


/*
* 使用 linux , unix 時,需要經常更改密碼。這個程序可以幫你生成強密碼 .
*
*等等,什麼是強密碼?
*
*現時基本上都是把字符分成四類:數字、小寫英文、大寫英文、符號,然後按照長度及組合
*複雜度來直接判斷強弱程度:單一,是弱密碼。 兩兩組合,是中密碼。 超過兩種組合,是強
*密碼。當然,這只是一個粗略的判定,密碼強度還跟密碼長度、使用者習慣等因素有關。想
*知道自己所選擇密碼的強度,可以直接在微軟的這個網站
*http://www.microsoft.com/china/athome/security/privacy/password_checker.mspx
*輸入自己的密碼,就可以知道密碼的強度了。
*
* 使用方法: 1, java Passwd  ( 可以生成一個 8 位的密碼.)
*           2, java Passwd n ( n>=5 , 可以生成一個 n 位的密碼 )
*
*/

public class Passwd {
 
 public static void main(String[] args){

  String[] pswdStr = {"qwertyuiopasdfghjklzxcvbnm" ,
       "QWERTYUIOPASDFGHJKLZXCVBNM" ,
       "0123456789" ,
       "~!@#$%^&*()[]//;',./{}|:/"<>?-_+=" ,
       };
  
  int pswdLen = 8 ; //設置密碼的默認長度
  String pswd = "" ; //密碼

  //根據傳入的參數,設置密碼長度
  if( args.length > 0 ){
   String lenStr = args[ 0 ] ;

   try{
    pswdLen = Integer.parseInt( lenStr ) ;
   }catch( Exception e ){
    System.out.println( "請輸入有效的密碼長度!" );
    System.exit( 0 ) ;
   }

   if( pswdLen < 5 ){
    System.out.println( "密碼長度必須大於 5 !" );
    System.exit( 0 ) ;    
   }
  }

  // chs 用於存放密碼的字符 .
  char[] chs = new char[ pswdLen ] ;
  
  //這個循環用於保證密碼包含四種字符.
  for( int i=0 ; i<pswdStr.length ; i++ ){
   
   int idx = ( int )( Math.random()*pswdStr[ i ].length() );
   chs[ i ] = pswdStr[ i ].charAt( idx ) ;

  }
  //這個循環用於保證密碼的長度.
  for( int i=pswdStr.length ; i<pswdLen ; i++ ){
   
   int arrIdx = ( int )( Math.random()*pswdStr.length );
   int strIdx = ( int )( Math.random()*pswdStr[ arrIdx ].length() );

   chs[ i ] = pswdStr[ arrIdx ].charAt( strIdx ) ;
  }

  // 打亂 chs 的順序
  for( int i=0 ; i<1000 ; i++ ){
   int idx1 = ( int )( Math.random()*chs.length );
   int idx2 = ( int )( Math.random()*chs.length );
   
   if( idx1 == idx2 ){
    continue ;
   }

   char tempChar = chs[ idx1 ] ;
   chs[ idx1 ] = chs[ idx2 ] ;
   chs[ idx2 ] = tempChar ;
  }
   
  pswd = new String( chs );
  System.out.println( pswd );
 }

 

發佈了27 篇原創文章 · 獲贊 0 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章