字符串加密
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Infrastructure.Util
{
public class Encrypt
{
private static string cstring = "server=localhost;UserName=root;Password=root;Database=changtu_new";
public static string GetEncryption()
{
Random r = new Random();
return Encryption(cstring,r);
}
public static string GetDecrypt(string str)
{
return Decrypt(str);
}
public static bool isRight(string str)
{
return Decrypt(str) == cstring;
}
//加密字符串函数
static public string Encryption(string str, Random R)
{
/* 加密算法 最长可加密255个字符 */
string md1, md2, pwd = "";
string[] str_t = new string[255];
int l1, l2;
for (int i = 0; i < str.Length; i++)
{
l1 = R.Next(0, 256);
md1 = l1.ToString("X");
if (md1.Length == 1) { md1 = "0" + md1; }
str_t[i] = str.Substring(i, 1);
System.Text.ASCIIEncoding AsciiEncoding = new System.Text.ASCIIEncoding();
l2 = (int)AsciiEncoding.GetBytes(str_t[i])[0];
md2 = (l1 ^ l2).ToString("X");
if (md2.Length == 1) { md2 = "0" + md2; }
pwd = pwd + md1 + md2;
}
return pwd;
}
//解密字符串函数
static public string Decrypt(string str)
{
/* 解密算法 */
string pwd = "";
int xl;
if (str.Length % 4 == 0)
{
xl = str.Length / 4;
string md1, md2;
int l1, l2;
for (int i = 0; i < xl; i++)
{
md1 = str.Substring(i * 4, 2);
md2 = str.Substring(i * 4 + 2, 2);
l1 = int.Parse(md1, System.Globalization.NumberStyles.AllowHexSpecifier);
l2 = int.Parse(md2, System.Globalization.NumberStyles.AllowHexSpecifier);
System.Text.ASCIIEncoding AsciiEncoding = new System.Text.ASCIIEncoding();
byte[] byteArray = new byte[] { (byte)(l1 ^ l2) };
md1 = AsciiEncoding.GetString(byteArray);
pwd = pwd + md1;
}
}
return pwd;
}
}
}