日期:2014-05-18  浏览次数:21295 次

解密base64加密编码,部分中文乱码问题
public static string DecompressGZip(string unCompressedString)
  {
  ---unCompressedString 是压缩加密后的64编码
  System.Text.StringBuilder uncompressedString = new System.Text.StringBuilder();
  byte[] writeData = new byte[4096];
  //将string字符串解码(转换为等效的8位无符号整数数组)
  byte[] bytData = System.Convert.FromBase64String(sunCompressedString);
   
  int totalLength = 0;
  int size = 0;
  //解压缩基础流来创建zip流对象
  Stream s = new GZipStream(new MemoryStream(bytData), CompressionMode.Decompress);
  while (true)
  {
  size = s.Read(writeData, 0, writeData.Length);//从当前流读取字节序列
  if (size > 0)
  {
  totalLength += size;
  //追加字符串到uncompressedString的结尾处
  uncompressedString.Append(System.Text.Encoding.UTF8.GetString(writeData, 0, size));
  说明:循环期间每次循环的最后一个字如果是中文,那么这个中文在转换后就是乱码,中间的汉字没发现问题 }
  else
  {
  break;
  }
  }
  s.Close();//关闭流
  return uncompressedString.ToString();//返回字符串
  }


监狱以上问题,请高手帮忙解决,谢谢~!

------解决方案--------------------
检查unCompressedString是否是utf8编码
------解决方案--------------------
unCompressedString 这个字符串是怎么生成的?
------解决方案--------------------
这样写吧,原来是中文字符被截断所以乱码了
C# code
public static string DecompressGZip(string unCompressedString)
{
    System.Text.StringBuilder uncompressedString = new System.Text.StringBuilder();
    byte[] writeData = new byte[4096];
    //将string字符串解码(转换为等效的8位无符号整数数组)
    byte[] bytData = System.Convert.FromBase64String(sunCompressedString);

    int totalLength = 0;
    int size = 0;
    //解压缩基础流来创建zip流对象
    Stream s = new GZipStream(new MemoryStream(bytData), CompressionMode.Decompress);
    using (var ms = new MemoryStream())
    {
        var len = 0;
        while ((len = s.Read(writeData, 0, writeData.Length)) > 0)
        {
            ms.Write(writeData, 0, len);
        }
        uncompressedString.Append(Encoding.UTF8.GetString(ms.ToArray()));
    }
    s.Close();//关闭流
    return uncompressedString.ToString();//返回字符串
}

------解决方案--------------------
4楼代码这个位置打错了,多了个 s
byte[] bytData = System.Convert.FromBase64String(unCompressedString);

------解决方案--------------------
using (var ms = new MemoryStream())
改成
using (MemoryStream ms = new MemoryStream())
------解决方案--------------------
var len = 0;
该成
int len = 0;