后端用Gzip加密字符串,然后我这边解压不了,原因就是编码的格式不对,然后就稍微修改了一下,改的真好,这不得好好炫耀一番!真佩服我自己😋😊!!
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
/// <summary>
/// 压缩和解压
/// </summary>
internal class ZipUtils
{
public enum ZipType
{
Base64,
ISO_8859_1,
}
private ZipType _zipType;
private ZipUtils(ZipType zipType)
{
_zipType = zipType;
}
public readonly static ZipUtils GZip1 = new ZipUtils(ZipType.Base64);
public readonly static ZipUtils GZip2 = new ZipUtils(ZipType.ISO_8859_1);
/// <summary>
/// 压缩字符串
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public string CompressString(string input)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
var outputStream = CompressString(inputBytes);
return _zipType switch
{
ZipType.Base64 => Convert.ToBase64String(outputStream.ToArray()),
ZipType.ISO_8859_1 => Encoding.GetEncoding("ISO-8859-1").GetString(outputStream.ToArray()),
_ => Convert.ToBase64String(outputStream.ToArray()),
};
}
/// <summary>
/// 解压字符串
/// </summary>
/// <param name="compressedInput"></param>
/// <returns></returns>
public string DecompressString(string compressedInput)
{
byte[] compressedBytes = _zipType switch
{
ZipType.Base64 => Convert.FromBase64String(compressedInput.ToString()),
ZipType.ISO_8859_1 => Encoding.GetEncoding("ISO-8859-1").GetBytes(compressedInput.ToString()),
_ => Convert.FromBase64String(compressedInput.ToString()),
};
MemoryStream outputStream = DecompressString(compressedBytes);
return Encoding.UTF8.GetString(outputStream.ToArray());
}
private MemoryStream CompressString(byte[] inputBytes)
{
//byte[] inputBytes = Encoding.UTF8.GetBytes(input);
using (MemoryStream outputStream = new MemoryStream())
{
using (GZipStream gzipStream = new GZipStream(outputStream, CompressionMode.Compress))
{
gzipStream.Write(inputBytes, 0, inputBytes.Length);
}
return outputStream;
}
}
private MemoryStream DecompressString(byte[] compressedBytes)
{
//byte[] compressedBytes = Convert.FromBase64String(compressedInput.ToString());
using (MemoryStream inputStream = new MemoryStream(compressedBytes))
{
using (GZipStream gzipStream = new GZipStream(inputStream, CompressionMode.Decompress))
{
using (MemoryStream outputStream = new MemoryStream())
{
gzipStream.CopyTo(outputStream);
return outputStream;
//return Encoding.UTF8.GetString(outputStream.ToArray());
}
}
}
}
}
参考网站: