熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

字符串加密解密類

2022-06-13   來源: .NET編程 

   using System;

    using SystemText;

    using SystemSecurityCryptography;

    using SystemIO;

  

  

  

    //默認密鑰向量

    private static byte[] Keys = { x x x x x xAB xCD xEF };

    /// <summary>

   /// DES加密字符串

   /// </summary>

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

   /// <param name=encryptKey>加密密鑰要求為位</param>

   /// <returns>加密成功返回加密後的字符串失敗返回源串</returns>

   public static string EncryptDES(string encryptString string encryptKey)

   {

       try

       {

           byte[] rgbKey = EncodingUTFGetBytes(encryptKeySubstring( ));

           byte[] rgbIV = Keys;

           byte[] inputByteArray = EncodingUTFGetBytes(encryptString);

           DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();

           MemoryStream mStream = new MemoryStream();

           CryptoStream cStream = new CryptoStream(mStream dCSPCreateEncryptor(rgbKey rgbIV) CryptoStreamModeWrite);

           cStreamWrite(inputByteArray inputByteArrayLength);

           cStreamFlushFinalBlock();

           return ConvertToBaseString(mStreamToArray());

       }

       catch

       {

           return encryptString;

       }

   }

  

   /// <summary>

   /// DES解密字符串

   /// </summary>

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

   /// <param name=decryptKey>解密密鑰要求為和加密密鑰相同</param>

   /// <returns>解密成功返回解密後的字符串失敗返源串</returns>

   public static string DecryptDES(string decryptString string decryptKey)

   {

       try

       {

           byte[] rgbKey = EncodingUTFGetBytes(decryptKey);

           byte[] rgbIV = Keys;

           byte[] inputByteArray = ConvertFromBaseString(decryptString);

           DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();

           MemoryStream mStream = new MemoryStream();

           CryptoStream cStream = new CryptoStream(mStream DCSPCreateDecryptor(rgbKey rgbIV) CryptoStreamModeWrite);

           cStreamWrite(inputByteArray inputByteArrayLength);

           cStreamFlushFinalBlock();

           return EncodingUTFGetString(mStreamToArray());

       }

       catch

       {

           return decryptString;

       }

   }

  使用方法為

  //獲取頁面字符串

  var strSource = RequestForms[xxx]value;

  //加密

  var strResult = EncryptDES(strSource);

  //解密

  var strRevert = DecryptDES(strResult );


From:http://tw.wingwit.com/Article/program/net/201311/13685.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.