using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace W.PlatformCore
{
public abstract class DES_
{
private static DES mydes = new DESCryptoServiceProvider();
public static string _ks = "public DES_()";
public static string _sq = "728#$$%^TyguyshdsufhsfwofnhKJHJKHIYhfiusf98*(^%$^&&(*&()$##@%%$RHGJJHHJ";
private static byte[] GetLegalKS()
{
string sTemp = _ks;
mydes.GenerateKey();
byte[] bytTemp = mydes.Key;
int KeyLength = bytTemp.Length;
if (sTemp.Length > KeyLength)
sTemp = sTemp.Substring(0, KeyLength);
else if (sTemp.Length < KeyLength)
sTemp = sTemp.PadRight(KeyLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
private static byte[] GetLegalSQ()
{
string sTemp = _sq;
mydes.GenerateIV();
byte[] bytTemp = mydes.IV;
int IVLength = bytTemp.Length;
if (sTemp.Length > IVLength)
sTemp = sTemp.Substring(0, IVLength);
else if (sTemp.Length < IVLength)
sTemp = sTemp.PadRight(IVLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
public static string Encrypt(string Source)
{
try
{
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
MemoryStream ms = new MemoryStream();
mydes.Key = GetLegalKS();
mydes.IV = GetLegalSQ();
ICryptoTransform encrypto = mydes.CreateEncryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
cs.Write(bytIn, 0, bytIn.Length);
cs.FlushFinalBlock();
ms.Close();
byte[] bytOut = ms.ToArray();
return Convert.ToBase64String(bytOut);
}
catch (Exception ex)
{
throw new Exception("在文件加密的时候出现错误!错误提示: \n" + ex.Message);
}
}
public static string Decrypt(string Source)
{
try
{
byte[] bytIn = Convert.FromBase64String(Source);
MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
mydes.Key = GetLegalKS();
mydes.IV = GetLegalSQ();
ICryptoTransform encrypto = mydes.CreateDecryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
catch
{
throw new Exception("在文件解密的时候出现错误!错误提示: \n" + ex.Message);
}
return null;
}
}
}