不安全,给你两个加密解密函数
/// <summary>
/// DES加密,密钥为8位字符
/// </summary>
/// <param name="strEncrypt">需要加密的字符串</param>
/// <param name="strKey">8位的密钥</param>
/// <returns></returns>
public static string DesEncrypt(string strEncrypt, string strKey)
{
if (string.IsNullOrEmpty(strEncrypt)) return null;
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(strEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(strKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(strKey);
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();
}
catch
{
return null;
}
}
/// <summary>
/// DES解密,密钥为8为字符
/// </summary>
/// <param name="strDecrypt">需要加密的字符串</param>
/// <param name="strKey">8位的密钥</param>
/// <returns></returns>
public static string DesDecrypt(string strDecrypt, string strKey)
{
if (string.IsNullOrEmpty(strDecrypt)) return null;
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[strDecrypt.Length / 2];
for (int x = 0; x < strDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(strDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(strKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(strKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
catch
{
return null;
}
}
}
使用方法,先把连接字符串加密
string strConnEnc = DesEncrypt(strConn,'abcd1234');
然后 strConnEnc 就是加密过的了,可以写在配置文件web.config里头或别的地方
使用的时候
DesDecrypt(strConnEnc,'abcd1234')
调出来结果就是连接字符串了,可以用来连接数据库了
温馨提示:答案为网友推荐,仅供参考