Code 1
Random m_rnd =NewRandom (); Public CharGetrandomchar () {intret = M_rnd. Next (122); while(Ret < -|| (Ret > $&& RET < $) || (Ret > -&& RET < the) ) {ret= M_rnd. Next (122); } return(Char) ret; } Public stringGetrandomstring (intlength) {StringBuilder SB=NewStringBuilder (length); for(inti =0; i < length; i++) {sb. Append (Getrandomchar ()); } returnsb. ToString (); }
Code 2-Support for custom character blending
//The main functions of the random string generator are as follows://1. Support Custom String length//2. Support for customizing whether it contains numbers//3. Support custom contains lowercase letters//4. Support to customize whether it contains uppercase letters//5. Support custom contains special symbols//6. Support Custom Character Set ///<summary> ///Generate random string///</summary> ///<param name= "Length" >the length of the target string</param> ///<param name= "Usenum" >Contains numbers, 1 = included, default is inclusive</param> ///<param name= "Uselow" >Contains lowercase letters, 1 = included, defaults to include</param> ///<param name= "Useupp" >Contains uppercase letters, 1 = included, defaults to include</param> ///<param name= "Usespe" >contains special characters, 1 = included, default = Not included</param> ///<param name= "Custom" >to include a custom character, directly enter the list of characters to include</param> ///<returns>random string of the specified length</returns> Public stringGetrnd (intLengthBOOLUsenum,BOOLUselow,BOOLUseupp,BOOLUsespe,stringCustom) { byte[] B =New byte[4]; NewSystem.Security.Cryptography.RNGCryptoServiceProvider (). GetBytes (b); Random R=NewRandom (Bitconverter.toint32 (b,0)); strings =NULL, str =Custom; if(Usenum = =true) {str + ="0123456789"; } if(Uselow = =true) {str + ="abcdefghijklmnopqrstuvwxyz"; } if(Useupp = =true) {str + ="abcdefghijklmnopqrstuvwxyz"; } if(Usespe = =true) {str + ="!\ "#$%&" () *+,-./:;<=>[email protected][\\]^_ ' {|} ~"; } for(inti =0; i < length; i++) {s+ = str. Substring (R.next (0Str. Length-1),1); } returns; }
This article is reproduced from http://www.cnblogs.com/phcis/archive/2011/01/12/1933632.html
C # generates passwords that meet specific requirements