76 lines
2.3 KiB
C#
76 lines
2.3 KiB
C#
|
|
using System.Security.Cryptography;
|
|||
|
|
using System.Text;
|
|||
|
|
|
|||
|
|
namespace Cowain.Base.Helpers;
|
|||
|
|
|
|||
|
|
public class DESHelper
|
|||
|
|
{
|
|||
|
|
|
|||
|
|
public static string Encrypt(string password, string key)
|
|||
|
|
{
|
|||
|
|
if (key.Length != 8)
|
|||
|
|
{
|
|||
|
|
return "";
|
|||
|
|
}
|
|||
|
|
if (string.IsNullOrEmpty(password))
|
|||
|
|
{
|
|||
|
|
return "";
|
|||
|
|
}
|
|||
|
|
using (DES des = DES.Create())
|
|||
|
|
{
|
|||
|
|
byte[] bytes = Encoding.Default.GetBytes(password);
|
|||
|
|
des.Key = Encoding.ASCII.GetBytes(key);
|
|||
|
|
des.IV = Encoding.ASCII.GetBytes(key);
|
|||
|
|
using (MemoryStream memoryStream = new MemoryStream())
|
|||
|
|
{
|
|||
|
|
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(), CryptoStreamMode.Write))
|
|||
|
|
{
|
|||
|
|
cryptoStream.Write(bytes, 0, bytes.Length);
|
|||
|
|
cryptoStream.FlushFinalBlock();
|
|||
|
|
StringBuilder stringBuilder = new StringBuilder();
|
|||
|
|
byte[] array = memoryStream.ToArray();
|
|||
|
|
foreach (byte b in array)
|
|||
|
|
{
|
|||
|
|
stringBuilder.AppendFormat("{0:X2}", b);
|
|||
|
|
}
|
|||
|
|
return stringBuilder.ToString();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static string Decrypt(string password, string key)
|
|||
|
|
{
|
|||
|
|
if (key.Length != 8)
|
|||
|
|
{
|
|||
|
|
return "";
|
|||
|
|
}
|
|||
|
|
if (string.IsNullOrEmpty(password))
|
|||
|
|
{
|
|||
|
|
return "";
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
using (DES des = DES.Create())
|
|||
|
|
{
|
|||
|
|
byte[] array = new byte[password.Length / 2];
|
|||
|
|
for (int i = 0; i < password.Length / 2; i++)
|
|||
|
|
{
|
|||
|
|
int num = Convert.ToInt32(password.Substring(i * 2, 2), 16);
|
|||
|
|
array[i] = (byte)num;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
des.Key = Encoding.ASCII.GetBytes(key);
|
|||
|
|
des.IV = Encoding.ASCII.GetBytes(key);
|
|||
|
|
using (MemoryStream memoryStream = new MemoryStream())
|
|||
|
|
{
|
|||
|
|
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(), CryptoStreamMode.Write))
|
|||
|
|
{
|
|||
|
|
cryptoStream.Write(array, 0, array.Length);
|
|||
|
|
cryptoStream.FlushFinalBlock();
|
|||
|
|
return Encoding.Default.GetString(memoryStream.ToArray());
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|