class MYDES
{
public static string Encrypt(string source, string _DESKey)
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(source);
byte[] k = ASCIIEncoding.ASCII.GetBytes(_DESKey);
byte[] result = null;
StringBuilder sb = new StringBuilder();
string encrypt = "";
using (DES des = new DESCryptoServiceProvider() { Key = k, IV = k })
{
using (MemoryStream outStream = new MemoryStream())
{
using (CryptoStream encStream = new CryptoStream(outStream, des.CreateEncryptor(), CryptoStreamMode.Write))
{
encStream.Write(inputByteArray, 0, inputByteArray.Length);
encStream.Close();
result = outStream.ToArray();
foreach (byte b in outStream.ToArray())
{
sb.AppendFormat("{0:X2}", b);
}
encrypt = sb.ToString();
}
}
}
return MYDES.byteToHexStr(result);
}
public static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
public static string byteToHexStr(byte[] bytes)
{
string returnStr = ""; if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
public static string Decrypt(string source, string sKey)
{
try
{
byte[] s = MYDES.strToToHexByte(source);
byte[] k = ASCIIEncoding.ASCII.GetBytes(sKey);
byte[] result = null;
using (DES des = new DESCryptoServiceProvider() { Key = k, IV = k })
using (MemoryStream inStream = new MemoryStream(s))
{
using (CryptoStream encStream = new CryptoStream(inStream, des.CreateDecryptor(), CryptoStreamMode.Read))
{
List byteList = new List();
int i;
while ((i = encStream.ReadByte()) != -1)
{
byteList.Add((byte)i);
}
result = byteList.ToArray();
}
}
string str = Encoding.UTF8.GetString(result);
return str;
}
catch (Exception e) { return e.ToString(); }
}
}
近期评论