文件加密&字符加密的代码

///<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();
  }



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=497212

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值