您好,欢迎访问三七文档
当前位置:首页 > IT计算机/网络 > 电子商务 > 一个C#写的加解密算法的类
一个加解密算法的类,如下:CodeusingSystem;usingSystem.IO;usingSystem.Security.Cryptography;usingSystem.Text;namespaceSurvIT.Business.UserPrivilege{///summary///SymmtricCrypto////summarypublicclassRijndaelCrypto{privateSymmetricAlgorithm_objCryptoService;privatestring_strKey=Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7;privatestring_strIV=E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk;///summary///Conctructor////summarypublicRijndaelCrypto(stringkey,stringIV){_objCryptoService=newRijndaelManaged();_objCryptoService=newTripleDESCryptoServiceProvider();_strKey=key;_strIV=IV;}publicRijndaelCrypto(){_objCryptoService=newRijndaelManaged();_objCryptoService=newTripleDESCryptoServiceProvider();}///summary///Getthekey////summary///returnskey/returnsprivatebyte[]GetLegalKey(){stringsTemp=_strKey;_objCryptoService.GenerateKey();byte[]bytTemp=_objCryptoService.Key;intKeyLength=bytTemp.Length;if(sTemp.LengthKeyLength)sTemp=sTemp.Substring(0,KeyLength);elseif(sTemp.LengthKeyLength)sTemp=sTemp.PadRight(KeyLength,'');returnASCIIEncoding.ASCII.GetBytes(sTemp);}///summary///InitializeIV////summary///returnsInitializeIV/returnsprivatebyte[]GetLegalIV(){_objCryptoService.GenerateIV();byte[]bytTemp=_objCryptoService.IV;intIVLength=bytTemp.Length;if(_strIV.LengthIVLength)_strIV=_strIV.Substring(0,IVLength);elseif(_strIV.LengthIVLength)_strIV=_strIV.PadRight(IVLength,'');returnASCIIEncoding.ASCII.GetBytes(_strIV);}///summary///Encrypto////summary///paramname=SourceThesourcestringneedtoencrypto/param///returnsThestringaftercrypto/returnspublicstringEncrypto(stringSource){byte[]bytIn=UTF8Encoding.UTF8.GetBytes(Source);MemoryStreamms=newMemoryStream();_objCryptoService.Key=GetLegalKey();_objCryptoService.IV=GetLegalIV();ICryptoTransformencrypto=_objCryptoService.CreateEncryptor();using(CryptoStreamcs=newCryptoStream(ms,encrypto,CryptoStreamMode.Write)){cs.Write(bytIn,0,bytIn.Length);cs.FlushFinalBlock();ms.Close();byte[]bytOut=ms.ToArray();stringstrRet=Convert.ToBase64String(bytOut);cs.Clear();returnstrRet;}}///summary///Decrypto////summary///paramname=SourceThesrouceneedtodecrypto/param///returnsTheresultstringafterdecrypto/returnspublicstringDecrypto(stringSource){byte[]bytIn=Convert.FromBase64String(Source);using(MemoryStreamms=newMemoryStream(bytIn,0,bytIn.Length)){_objCryptoService.Key=GetLegalKey();_objCryptoService.IV=GetLegalIV();ICryptoTransformencrypto=_objCryptoService.CreateDecryptor();CryptoStreamcs=newCryptoStream(ms,encrypto,CryptoStreamMode.Read);StreamReadersr=newStreamReader(cs);stringstrRet=sr.ReadToEnd();cs.Clear();returnstrRet;}}}}用法如下:CodepublicstaticstringEncryptoPassword(stringpwd){RijndaelCryptorijndael=newRijndaelCrypto();returnrijndael.Encrypto(pwd);}publicstaticstringDecryptoPassword(stringCryptoPwd){RijndaelCryptorijndael=newRijndaelCrypto();returnrijndael.Decrypto(CryptoPwd);}
本文标题:一个C#写的加解密算法的类
链接地址:https://www.777doc.com/doc-4707359 .html