日期:2014-05-20  浏览次数:21113 次

强密码的生成算法.

今天写了这个生成密码的程序,谁有更好算法,大家讨论一下.


/*
*   使用   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   );