using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace NFine.Code
{
public class DBConnection
{
public static bool Encrypt { get; set; }
public DBConnection(bool encrypt)
{
Encrypt = encrypt;
}
public static string connectionString
{
get
{
string connection = FromMd5( System.Configuration.ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
if (Encrypt == true)
{
return DESEncrypt.Decrypt(connection);
}
else
{
return connection;
}
}
}
#region 字符串加解密
///
/// MD5加密
///
///
///
public static string ToMd5(string str)
{
return Encrypts(str, "&%#@?,:*_");
}
///
/// MD5解密
///
///
///
public static string FromMd5(string str)
{
return str;
//return Decrypt(str, "&%#@?,:*_");
}
///
/// 加密
///
///
///
///
private static String Encrypts(String strText, String strEncrKey)
{
Byte[] byKey = { };
Byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV),
CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception ex)
{
return ex.Message;
}
}
///
/// 解密
///
///
///
///
private static String Decrypt(String strText, String sDecrKey)
{
Byte[] byKey = { };
Byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
Byte[] inputByteArray = new byte[strText.Length];
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV),
CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception ex)
{
return ex.Message;
}
}
#endregion
}
}