我把数据库连接字符串加密存在XML里头,取出来的时候解密,而只要我代码一有修改,比如加行MessageBox("...");那么xml文件的内容就会被修改成我未加密的连接字符串(也就是真正使用的字符串),有点凌乱,先贴代码。
//////这是公共类的公共方法,每次就从这里取出连接字符串
public static string GetConStr()
{
DataSet ds = new DataSet();
ds.ReadXml(Application.StartupPath + "\\config.xml");
string uid = Solution(ds.Tables[0].Rows[0]["uid"].ToString());
string psw = Solution(ds.Tables[0].Rows[0]["password"].ToString());
string db = Solution(ds.Tables[0].Rows[0]["DataBase"].ToString());
string Server=Solution(ds.Tables[0].Rows[0]["Server"].ToString());
string s = "uid=" + uid + ";password="
+ psw + ";DataBase="
+db + ";Server="
+ Server;
// MessageBox.Show(ds.Tables[0].Rows[0]["uid"].ToString());
return s;
}
public static void SetConStr(string uid, string pwd, string db, string server)
{
DataSet ds = new DataSet();
ds.ReadXml(Application.StartupPath + "\\config.xml");
ds.Tables[0].Rows[0]["uid"] = Encoding(uid);
ds.Tables[0].Rows[0]["password"] = Encoding(pwd);
ds.Tables[0].Rows[0]["DataBase"] = Encoding(db);
ds.Tables[0].Rows[0]["Server"] = Encoding(server);
// MessageBox.Show(Encoding(uid));
ds.WriteXml(Application.StartupPath + "\\config.xml");
}
public static string Encoding(string str)
{
//加密方法:(字符串的每个字符的ASCII码+89)%128,之后得到的字符串再左移两位(abcde 转换成 cdeab)
string encodedstr = "";
char[] chars = new char[100];
int length = str.Length;
for (int i = 0; i < length; i++)
{
char ch = str[i];
int asc = (int)ch;
asc += 89;
asc %= 128;
chars[i] = (char)asc;
// encodedstr += (char)asc;
}
// chars = encodedstr.ToCharArray(0, length);
for (int i = 0; i < length; i++)
{
// chars[i] = str[(i + 2) % length];
encodedstr += chars[(i + 2) % length];
}