using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using log4net;
using log4net.Config;
using System.Security.Cryptography;
using System.IO.Compression;
namespace Common
{
///
/// DES加密解密
///
public class DESHelper
{
#region des加密
///
/// DES加密
///
/// 需要加密的
/// 密匙
///
public string DesEncrypt(string input)
{
AesCryptoServiceProvider des = new AesCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(input);
des.Key = ASCIIEncoding.ASCII.GetBytes("lizxlylwkdqzymyzsqblt666");
des.IV = ASCIIEncoding.ASCII.GetBytes("txwl888txwl20201");
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
byte[] message = ms.ToArray();
string returnStr = "";
if (message != null)
{
for (int i = 0; i < message.Length; i++)
{
returnStr += message[i].ToString("X2");
}
}
return returnStr;
}
#endregion
#region des解密 判断请求是否过期
///
/// 解密
///
///
///
public string DesDecrypt(string input)
{
try
{
byte[] inputBytes = HexStringToByteArray(input);
//byte[] inputBytes = Convert.FromBase64String(input);
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = ASCIIEncoding.ASCII.GetBytes("lizxlylwkdqzymyzsqblt666");
aesAlg.IV = ASCIIEncoding.ASCII.GetBytes("txwl888txwl20201");
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream(inputBytes))
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srEncrypt = new StreamReader(csEncrypt))
{
return srEncrypt.ReadToEnd();
}
}
}
}
}
catch (Exception e)
{
return "";
}
}
///
/// 将指定的16进制字符串转换为byte数组
///
/// 16进制字符串(如:“7F 2C 4A”或“7F2C4A”都可以)
/// 16进制字符串对应的byte数组
public static byte[] HexStringToByteArray(string s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}
public bool IsMtoken(string timeStamp)
{
var time = ConvertStringToDateTime(timeStamp);
if (DateTime.Now > time.AddMinutes(1))
return false;
else
return true;
}
///
/// 时间戳转为C#格式时间
///
///
///
private DateTime ConvertStringToDateTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
#endregion
#region GZip压缩
///
/// GZip压缩
///
///
///
public byte[] Compress(byte[] rawData)
{
MemoryStream ms = new MemoryStream();
GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
compressedzipStream.Write(rawData, 0, rawData.Length);
compressedzipStream.Close();
return ms.ToArray();
}
#endregion
}
}