字元加密&檔案加密的代碼

來源:互聯網
上載者:User
加密  

///<summary>檔案加密類 使用DES加密檔案流</summary>
///<param>desKey: DES的密鑰;desIV: DES向量</param>

class encrypfile{
        public byte[] desKey;
        public byte[] desIV;

        public encrypfile(byte[] inputKey,byte[] inputIV){
            desKey=inputKey;
            desIV=inputIV;

        }

        ///<summary>加密主方法</summary>
        ///<param>inName:被加密檔案名稱;outName: 加密後檔案名稱</param>
        public void begintoencry(string inName,string outName){
            FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);

            byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
            long rdlen = 0;              //This is the total number of bytes written.
            long totlen = fin.Length;    //This is the total length of the input file.
            int len;                     //This is the number of bytes to be written at a time.
            DES des = new DESCryptoServiceProvider();
            CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

            while(rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                encStream.Write(bin, 0, len);
                rdlen = rdlen + len;
            }

                encStream.Close();
                fout.Close();
                fin.Close();
            }
    }


加密字元流
  //pToEncrypt為需要加密字串,sKey為密鑰
  public string Encrypt(string pToEncrypt, string sKey)
  {
   DESCryptoServiceProvider des = new DESCryptoServiceProvider();
   //把字串放到byte數組中
   byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);

   //建立加密對象的密鑰和向量
   des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
   des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
   MemoryStream ms = new MemoryStream();
   CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(),CryptoStreamMode.Write);

   cs.Write(inputByteArray, 0, inputByteArray.Length);
   cs.FlushFinalBlock();
   StringBuilder ret = new StringBuilder();
   foreach(byte b in ms.ToArray())
   {
    ret.AppendFormat("{0:X2}", b);
   }
   return ret.ToString();
  }




相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。