首页 > 开发 > 综合 > 正文

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

2024-07-21 02:24:34
字体:
来源:转载
供稿:网友
 

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



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表