//------------------------------------以下为一些关键函数------------------------------
// 将字符串转换为byte数组
public byte[] strToByteAry(string str){
return Encoding.Default.GetBytes(str);
}
// c# dz通信证编码函数
public string passport_encrypt(string txt, string key){
byte[] randomNumber = new byte[1];
RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
Gen.GetBytes(randomNumber);
int rand = Convert.ToInt32(randomNumber[0]);
string encrypt_key = md5(rand.ToString());
byte[] txtAry = strToByteAry(txt);
byte[] encryAry = strToByteAry(encrypt_key);
int j = 0;
int ctr = 0;
byte[] tmp = new byte[2 * txtAry.Length];
for (int i = 0; i < txtAry.Length; i++)
{
ctr = ctr == encryAry.Length ? 0 : ctr;
tmp[j++] = encryAry[ctr];
tmp[j++] = xor(txtAry[i], encryAry[ctr++]);
}
return Convert.ToBase64String(passport_key(tmp, key));
}
// c# dz通行证解码函数
public string passport_decrypt(string txt, string key){
byte[] t = Convert.FromBase64String(txt);
byte[] btxt = passport_key(t, key);
byte[] btmp = new byte[btxt.Length];
int j = 0;
for (int i = 0; i < btxt.Length; i++, j++)
btmp[j] = xor(btxt[i], btxt[++i]);
return Encoding.Default.GetString(btmp);
}
// c# dz通行证密匙处理函数
public byte[] passport_key(byte[] btxt, string key){
key = md5(key);
byte[] keyAry = strToByteAry(key);
int ctr = 0;
byte[] tmp = new byte[btxt.Length];
for (int i = 0; i < btxt.Length; i++){
ctr = (ctr == keyAry.Length) ? 0 : ctr;
tmp[i] = xor(btxt[i], keyAry[ctr++]);
}
return tmp;
}
// 针对byte的异或
public byte xor(byte a, byte b){
return Convert.ToByte(a ^ b);
}
// 获取UNIX时间戳
public string time(){
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
DateTime dtNow = DateTime.Parse(DateTime.Now.ToString());
TimeSpan toNow = dtNow.Subtract(dtStart);
string timeStamp = toNow.Ticks.ToString();
timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
return timeStamp;
}
// md5加密
public string md5(string str){
MD5 md5Hasher = MD5.Create();
string re="";
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(str));
for (int i = 0; i < data.Length; i++)
re += data[i].ToString("x2");
return re;
}
}