Files
g.hnyhua.cn/Mtxfw.Utility/Security.cs
2026-02-07 15:48:27 +08:00

138 lines
4.4 KiB
C#

using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace Mtxfw.Utility
{
public class Security
{
static int key = 20200608;
/// <summary>
/// 解密
/// </summary>
/// <param name="decryptString"></param>
/// <returns></returns>
public static string DecryptString(string decryptString)
{
if (decryptString != "")
{
string str = "解密字符失败!";
try
{
SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create("TripleDES");
algorithm.Mode = CipherMode.ECB;
algorithm.Key = Encoding.UTF8.GetBytes(splitStringLen("encrypt52ttxfw", 0x18, '0'));
algorithm.Padding = PaddingMode.PKCS7;
ICryptoTransform transform = algorithm.CreateDecryptor();
byte[] buffer = Convert.FromBase64String(decryptString);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write);
try
{
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
str = Encoding.UTF8.GetString(stream.ToArray());
}
catch (Exception exception)
{
str = exception.ToString();
}
finally
{
stream.Close();
stream2.Close();
stream.Dispose();
stream2.Dispose();
transform.Dispose();
algorithm.Clear();
}
}
catch (Exception exception2)
{
str = decryptString;
}
return str;
}
else
{
return decryptString;
}
}
/// <summary>
/// 加密
/// </summary>
/// <param name="encryptValue"></param>
/// <returns></returns>
public static string EncryptString(string encryptValue)
{
if (encryptValue != "")
{
string str = "加密出错!";
SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create("TripleDES");
algorithm.Mode = CipherMode.ECB;
algorithm.Key = Encoding.UTF8.GetBytes(splitStringLen("encrypt52ttxfw", 0x18, '0'));
algorithm.Padding = PaddingMode.PKCS7;
ICryptoTransform transform = algorithm.CreateEncryptor();
byte[] bytes = Encoding.UTF8.GetBytes(encryptValue);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write);
try
{
stream2.Write(bytes, 0, bytes.Length);
stream2.FlushFinalBlock();
str = Convert.ToBase64String(stream.ToArray());
}
catch (Exception exception)
{
str = exception.ToString();
}
finally
{
stream2.Close();
stream2.Dispose();
stream.Close();
stream.Dispose();
algorithm.Clear();
transform.Dispose();
}
return Convert.ToBase64String(stream.ToArray());
}
else
{
return encryptValue;
}
}
private static string splitStringLen(string s, int len, char b)
{
if (string.IsNullOrEmpty(s))
{
return "";
}
if (s.Length >= len)
{
return s.Substring(0, len);
}
return s.PadRight(len, b);
}
// 加密算法可以公开
public static int encrypt(int plainText)
{
return plainText ^ key;
}
// 解密算法也可以公开
public static int decrypt(int cipherText)
{
return cipherText ^ key;
}
}
}