C#加密算法汇总

 

//方法一:   

002   

003     //须添加对System.Web的引用    

004   

005      using System.Web.Security;    

006        

007   

008     /// <summary>    

009   

010     /// SHA1加密字符串    

011   

012     /// </summary>    

013   

014     /// <param name="source">源字符串</param>    

015   

016     /// <returns>加密后的字符串</returns>    

017   

018     public string SHA1(string source)    

019      {    

020   

021        return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1");    

022   

023     }    

024   

025         

026   

027     /// <summary>    

028   

029    /// MD5加密字符串   

030    /// </summary>    

031    /// <param name="source">源字符串</param>    

032     /// <returns>加密后的字符串</returns>    

033    public string MD5(string source)    

034     {    

035       return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");;    

036      }  

037   

038    

039 //方法二(可逆加密解密):   

040   

041    using System.Security.Cryptography;    

042   

043          

044          

045     public string Encode(string data)    

046   

047      {    

048   

049        byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);    

050   

051         byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);    

052   

053   

054          DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();    

055   

056          int i = cryptoProvider.KeySize;    

057   

058         MemoryStream ms = new MemoryStream();    

059   

060          CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);    

061          

062   

063          StreamWriter sw = new StreamWriter(cst);    

064   

065         sw.Write(data);    

066   

067        sw.Flush();    

068   

069        cst.FlushFinalBlock();    

070        

071        sw.Flush();    

072   

073        return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);    

074   

075           

076    }    

077           

078   

079     public string Decode(string data)    

080      {    

081          byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);    

082   

083         byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);    

084          

085   

086         byte[] byEnc;    

087   

088         try  

089   

090         {    

091              byEnc = Convert.FromBase64String(data);    

092          }    

093          catch  

094          {    

095              return null;    

096   

097         }    

098           

099          DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();    

100   

101          MemoryStream ms = new MemoryStream(byEnc);    

102   

103          CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);    

104   

105          StreamReader sr = new StreamReader(cst);    

106   

107          return sr.ReadToEnd();    

108      }  

109   

110   

111   

112   

113  //方法三(MD5不可逆):   

114   

115     using System.Security.Cryptography;    

116   

117          

118     

119           

120     //MD5不可逆加密    

121          

122   

123      //32位加密          

124   

125     public string GetMD5_32(string s, string _input_charset)    

126   

127      {    

128   

129         MD5 md5 = new MD5CryptoServiceProvider();    

130   

131          byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));    

132   

133          StringBuilder sb = new StringBuilder(32);    

134   

135          for (int i = 0; i < t.Length; i++)     

136        {    

137             sb.Append(t[i].ToString("x").PadLeft(2, '0'));    

138         }    

139          return sb.ToString();    

140     }    

141           

142     //16位加密    

143   

144      public static string GetMd5_16(string ConvertString)    

145   

146      {    

147   

148          MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();    

149   

150          string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);    

151   

152         t2 = t2.Replace("-", "");    

153   

154          return t2;    

155      }  

156   

157   

158  //方法四(对称加密):   

159   

160      using System.IO;    

161   

162      using System.Security.Cryptography;    

163     

164   

165           

166   

167      private SymmetricAlgorithm mobjCryptoService;    

168   

169      private string Key;    

170   

171     /// <summary>       

172   

173     /// 对称加密类的构造函数       

174      /// </summary>       

175     public SymmetricMethod()    

176   

177      {    

178   

179          mobjCryptoService = new RijndaelManaged();    

180   

181         Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";    

182      }    

183   

184   

185      /// <summary>       

186   

187      /// 获得密钥       

188   

189     /// </summary>       

190   

191     /// <returns>密钥</returns>       

192   

193      private byte[] GetLegalKey()    

194   

195      {    

196   

197          string sTemp = Key;    

198   

199         mobjCryptoService.GenerateKey();    

200   

201          byte[] bytTemp = mobjCryptoService.Key;    

202   

203          int KeyLength = bytTemp.Length;    

204   

205          if (sTemp.Length > KeyLength)    

206   

207              sTemp = sTemp.Substring(0, KeyLength);    

208   

209          else if (sTemp.Length < KeyLength)    

210   

211              sTemp = sTemp.PadRight(KeyLength, ' ');    

212   

213          return ASCIIEncoding.ASCII.GetBytes(sTemp);    

214   

215      }    

216   

217      /// <summary>       

218   

219      /// 获得初始向量IV       

220   

221      /// </summary>       

222   

223      /// <returns>初试向量IV</returns>       

224   

225      private byte[] GetLegalIV()    

226   

227      {    

228   

229          string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";    

230   

231          mobjCryptoService.GenerateIV();    

232   

233          byte[] bytTemp = mobjCryptoService.IV;    

234   

235          int IVLength = bytTemp.Length;    

236   

237          if (sTemp.Length > IVLength)    

238   

239              sTemp = sTemp.Substring(0, IVLength);    

240   

241          else if (sTemp.Length < IVLength)    

242   

243              sTemp = sTemp.PadRight(IVLength, ' ');    

244   

245          return ASCIIEncoding.ASCII.GetBytes(sTemp);    

246   

247      }    

248   

249     /// <summary>       

250   

251      /// 加密方法       

252   

253      /// </summary>       

254   

255      /// <param name="Source">待加密的串</param>       

256   

257      /// <returns>经过加密的串</returns>       

258   

259      public string Encrypto(string Source)    

260   

261      {    

262   

263          byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);    

264   

265          MemoryStream ms = new MemoryStream();    

266   

267          mobjCryptoService.Key = GetLegalKey();    

268   

269          mobjCryptoService.IV = GetLegalIV();    

270   

271          ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();    

272   

273          CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);    

274   

275         cs.Write(bytIn, 0, bytIn.Length);    

276   

277         cs.FlushFinalBlock();    

278   

279          ms.Close();    

280   

281          byte[] bytOut = ms.ToArray();    

282   

283          return Convert.ToBase64String(bytOut);    

284   

285      }    

286   

287     /// <summary>       

288   

289      /// 解密方法       

290   

291      /// </summary>       

292   

293      /// <param name="Source">待解密的串</param>       

294   

295      /// <returns>经过解密的串</returns>       

296   

297      public string Decrypto(string Source)    

298   

299      {    

300   

301          byte[] bytIn = Convert.FromBase64String(Source);    

302   

303          MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);    

304   

305          mobjCryptoService.Key = GetLegalKey();    

306   

307          mobjCryptoService.IV = GetLegalIV();    

308   

309          ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();    

310   

311          CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);    

312   

313          StreamReader sr = new StreamReader(cs);    

314   

315          return sr.ReadToEnd();    

316   

317      }  

318   

319 // 方法五:   

320   

321      using System.IO;    

322   

323      using System.Security.Cryptography;    

324   

325      using System.Text;    

326   

327              

328   

329           

330   

331      //默认密钥向量    

332   

333      private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };    

334   

335      /// <summary>    

336   

337      /// DES加密字符串    

338   

339      /// </summary>    

340   

341      /// <param name="encryptString">待加密的字符串</param>    

342   

343      /// <param name="encryptKey">加密密钥,要求为8位</param>    

344   

345      /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>    

346   

347      public static string EncryptDES(string encryptString, string encryptKey)    

348   

349      {    

350   

351          try  

352   

353          {    

354   

355              byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));    

356   

357              byte[] rgbIV = Keys;    

358   

359              byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);    

360   

361             DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();    

362               

363             MemoryStream mStream = new MemoryStream();    

364   

365              CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);    

366   

367              cStream.Write(inputByteArray, 0, inputByteArray.Length);    

368   

369              cStream.FlushFinalBlock();    

370   

371              return Convert.ToBase64String(mStream.ToArray());    

372   

373          }    

374   

375          catch  

376   

377          {    

378   

379              return encryptString;    

380   

381         }    

382   

383     }    

384   

385   

386   

387      /// <summary>    

388   

389      /// DES解密字符串    

390   

391      /// </summary>    

392   

393      /// <param name="decryptString">待解密的字符串</param>    

394   

395      /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>    

396   

397      /// <returns>解密成功返回解密后的字符串,失败返源串</returns>    

398   

399      public static string DecryptDES(string decryptString, string decryptKey)    

400   

401      {    

402   

403          try  

404   

405          {    

406   

407              byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);    

408   

409              byte[] rgbIV = Keys;    

410   

411              byte[] inputByteArray = Convert.FromBase64String(decryptString);    

412   

413              DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();    

414   

415              MemoryStream mStream = new MemoryStream();    

416   

417              CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);    

418   

419              cStream.Write(inputByteArray, 0, inputByteArray.Length);    

420   

421              cStream.FlushFinalBlock();    

422   

423              return Encoding.UTF8.GetString(mStream.ToArray());    

424   

425          }    

426   

427          catch  

428   

429         {    

430   

431             return decryptString;    

432   

433         }    

434      }  

435   

436 // 方法六(文件加密):   

437   

438      using System.IO;    

439   

440      using System.Security.Cryptography;    

441   

442      using System.Text;   

443           

444   

445   

446           

447   

448     //加密文件    

449   

450      private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)    

451   

452      {    

453   

454          //Create the file streams to handle the input and output files.    

455   

456         FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);    

457   

458          FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);    

459   

460          fout.SetLength(0);    

461   

462           

463   

464          //Create variables to help with read and write.    

465   

466          byte[] bin = new byte[100]; //This is intermediate storage for the encryption.    

467   

468          long rdlen = 0;              //This is the total number of bytes written.    

469   

470          long totlen = fin.Length;    //This is the total length of the input file.    

471   

472          int len;                     //This is the number of bytes to be written at a time.    

473   

474           

475   

476          DES des = new DESCryptoServiceProvider();    

477   

478          CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);    

479   

480           

481   

482          //Read from the input file, then encrypt and write to the output file.    

483   

484          while (rdlen < totlen)    

485   

486          {    

487   

488              len = fin.Read(bin, 0, 100);    

489   

490              encStream.Write(bin, 0, len);    

491   

492              rdlen = rdlen + len;    

493   

494          }    

495   

496           

497   

498          encStream.Close();    

499   

500          fout.Close();    

501   

502          fin.Close();    

503   

504      }    

505   

506           

507   

508      //解密文件    

509   

510      private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV)    

511   

512      {    

513   

514          //Create the file streams to handle the input and output files.    

515   

516          FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);    

517   

518          FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);    

519   

520          fout.SetLength(0);    

521   

522           

523   

524          //Create variables to help with read and write.    

525   

526          byte[] bin = new byte[100]; //This is intermediate storage for the encryption.    

527   

528          long rdlen = 0;              //This is the total number of bytes written.    

529   

530          long totlen = fin.Length;    //This is the total length of the input file.    

531   

532          int len;                     //This is the number of bytes to be written at a time.    

533   

534           

535   

536          DES des = new DESCryptoServiceProvider();    

537   

538          CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);    

539   

540           

541   

542          //Read from the input file, then encrypt and write to the output file.    

543   

544          while (rdlen < totlen)    

545   

546          {    

547   

548             len = fin.Read(bin, 0, 100);    

549   

550              encStream.Write(bin, 0, len);    

551   

552              rdlen = rdlen + len;    

553   

554          }    

555   

556           

557   

558          encStream.Close();    

559   

560          fout.Close();    

561   

562          fin.Close();    

563   

564      }  

565   

566    

567   

568   

569  using System;   

570   

571  using System.Security.Cryptography;//这个是处理文字编码的前提   

572   

573  using System.Text;   

574   

575  using System.IO;   

576   

577   

578 /// <summary>   

579   

580  /// DES加密方法   

581   

582  /// </summary>   

583   

584  /// <param name="strPlain">明文</param>   

585   

586  /// <param name="strDESKey">密钥</param>   

587   

588  /// <param name="strDESIV">向量</param>   

589   

590  /// <returns>密文</returns>   

591   

592  public string DESEncrypt(string strPlain,string strDESKey,string strDESIV)   

593   

594  {   

595   

596   //把密钥转换成字节数组   

597   

598   byte[] bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey);   

599   

600   //把向量转换成字节数组   

601   

602   byte[] bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV);   

603   

604   //声明1个新的DES对象   

605   

606   DESCryptoServiceProvider desEncrypt=new DESCryptoServiceProvider();   

607   

608   //开辟一块内存流   

609   

610   MemoryStream msEncrypt=new MemoryStream();   

611   

612   //把内存流对象包装成加密流对象   

613   

614   CryptoStream csEncrypt=new CryptoStream(msEncrypt,desEncrypt.CreateEncryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Write);   

615   

616   //把加密流对象包装成写入流对象   

617   

618   StreamWriter swEncrypt=new StreamWriter(csEncrypt);   

619   

620   //写入流对象写入明文   

621   

622   swEncrypt.WriteLine(strPlain);   

623   

624   //写入流关闭   

625   

626   swEncrypt.Close();   

627   

628   //加密流关闭   

629   

630   csEncrypt.Close();   

631   

632   //把内存流转换成字节数组,内存流现在已经是密文了   

633   

634   byte[] bytesCipher=msEncrypt.ToArray();   

635   

636   //内存流关闭   

637   

638   msEncrypt.Close();   

639   

640   //把密文字节数组转换为字符串,并返回   

641   

642   return UnicodeEncoding.Unicode.GetString(bytesCipher);   

643   

644  }   

645   

646       

647   

648       

649   

650          

651   

652  /// <summary>   

653   

654  /// DES解密方法   

655   

656  /// </summary>   

657   

658  /// <param name="strCipher">密文</param>   

659   

660  /// <param name="strDESKey">密钥</param>   

661   

662  /// <param name="strDESIV">向量</param>   

663   

664  /// <returns>明文</returns>   

665   

666  public string DESDecrypt(string strCipher,string strDESKey,string strDESIV)   

667   

668  {   

669   

670   //把密钥转换成字节数组   

671   

672   byte[] bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey);   

673   

674   //把向量转换成字节数组   

675   

676   byte[] bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV);   

677   

678   //把密文转换成字节数组   

679   

680   byte[] bytesCipher=UnicodeEncoding.Unicode.GetBytes(strCipher);   

681   

682   //声明1个新的DES对象   

683   

684   DESCryptoServiceProvider desDecrypt=new DESCryptoServiceProvider();   

685   

686   //开辟一块内存流,并存放密文字节数组   

687   

688   MemoryStream msDecrypt=new MemoryStream(bytesCipher);   

689   

690   //把内存流对象包装成解密流对象   

691   

692   CryptoStream csDecrypt=new CryptoStream(msDecrypt,desDecrypt.CreateDecryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Read);   

693   

694   //把解密流对象包装成读出流对象   

695   

696   StreamReader srDecrypt=new StreamReader(csDecrypt);   

697   

698   //明文=读出流的读出内容   

699   

700   string strPlainText=srDecrypt.ReadLine();   

701   

702   //读出流关闭   

703   

704   srDecrypt.Close();   

705   

706   //解密流关闭   

707   

708   csDecrypt.Close();   

709   

710   //内存流关闭   

711   

712   msDecrypt.Close();   

713   

714   //返回明文   

715   

716   return strPlainText;   

717   

718  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值