日期:2014-05-17  浏览次数:20462 次

急!!!!对文件流解密时出现字节丢失,提示“不正确的数据”,CryptoStream encStream,有哪位高手帮忙解决一下,谢谢!!
/// <summary> 
  /// 对文件加密采用算法 
  /// </summary> 
  /// <param name="sy">创建一个公钥和一个私钥 </param> 
  private void PasswordToByte(SymmetricAlgorithm sy)
  {
  byte[] b = new byte[8];
  byte[] c = new byte[8];
  Encoding ascii = Encoding.ASCII;
  byte[] EncodeByte = ascii.GetBytes("zhongguo");
  byte[] EncodeByte2 = ascii.GetBytes("zhongguo");

  ToPassByte(b, EncodeByte);
  ToPassByte(c, EncodeByte2);

  sy.Key = b;
  sy.IV = c;
  }

  /// <summary> 
  /// 
  /// </summary> 
  /// <param name="Destination">字节数 </param> 
  /// <param name="Source">编码字符数组 </param> 
  public void ToPassByte(byte[] Destination, byte[] Source)
  {
  if (Destination.Length >= Source.Length)
  {
  for (int i = 0; i < Source.Length; i++)
  {
  Destination[i] = Source[i];
  }
  }
  else
  {
  for (int i = 0; i < Destination.Length; i++)
  {
  Destination[i] = Source[i];
  }
  }
  }

  /// <summary> 
  /// 将一个文件加密并生成一个新文件 
  /// </summary> 
  /// <param name="inName">需要加密文件的全路径 </param> 
  /// <param name="outName">输出加密文件的全路径 </param> 
  public byte[] EncryptData(String inName, String outName)
  {
  //创建输入流和输出流 
  FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
  MemoryStream fout = new MemoryStream();
  fout.SetLength(0);

  //读写的缓存区 
  byte[] bin = new byte[1000]; //加密的临时存储区 
  long rdlen = 0; //初始化写出流的长度 
  long totlen = fin.Length; //输入流的长度 
  int len; //某一个时间段完成的写出流长度 

  //给key和iv赋值 
  PasswordToByte(des);
  //创建加密器 
  ICryptoTransform transform = des.CreateEncryptor(des.Key, des.IV);
  //使用加密器和输出流,创建一个加密输出流 
  CryptoStream encStream = new CryptoStream(fout, transform, CryptoStreamMode.Write);

  //循环读出输入流到内存中,然后加密流将一段内存加密后写到输出流 
  while (rdlen < totlen)
  {
  len = fin.Read(bin, 0, 1000);
  encStream.Write(bin, 0, len);
  rdlen = rdlen + len;
  }

  byte[] fdata = fout.ToArray(); //将加密流fout储存到数组fdata中
  //关闭流
  encStream.Close();
  fin.Close();  
  fout.Close();

  return fdata;
  }



  /// <summary> 
  ///解密&nb