111,098
社区成员




/// <summary>
/// 创建Key
/// </summary>
/// <returns></returns>
public static string GenerateKey()
{
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="pToEncrypt"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string MD5Encrypt(string pToEncrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
/// <summary>
/// MD5解密
/// </summary>
/// <param name="pToDecrypt"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string MD5Decrypt(string pToDecrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
//读取密码和key
string connectionstring = File.ReadAllText(Application.StartupPath + @"\ConnectionString", Encoding.Default);
string key = File.ReadAllText(Application.StartupPath + @"\key", Encoding.Default);
//使用key解密
connectionstring = DAL_HoLaSystem.DBControl.DES.MD5Decrypt(connectionstring, key);
加密的使用方法: //获取相应的key
string key = DAL_HoLaSystem.DBControl.DES.GenerateKey();
//MD5加密明码
connectionstring = DAL_HoLaSystem.DBControl.DES.MD5Encrypt(string.Format(@"DataBase={0};Server={1};uid={2};pwd={3}", txtDataName.Text.Trim(), txtServerName.Text.Trim(), txtUID.Text.Trim(), txtPWD.Text.Trim()), key);
//定义写入流
StreamWriter sw = new StreamWriter(Application.StartupPath + @"\ConnectionString");
StreamWriter sw2 = new StreamWriter(Application.StartupPath + @"\key");
//写入字符串
sw.Write(connectionstring);
sw2.Write(key);
//关闭流
sw2.Close();
sw.Close();