我写的加密解密代码,效率方面想改进,各位朋友帮忙看看
看到的朋友也请顶一下,希望高手看到指点下。下面说下代码原理。加密原理是取得每个字符的ascii码,然后ascii码在144以下的,用两个字母表示,ascii码在64000下面的,用三个字母表示,更大的用3开头,四个字母表示,超过四个字母的暂时不考虑
我的代码使用目的就是网站上ajax提交数据,还有客户端与服务器提交数据提供一个相对的数据安全。至于javascript,如果大家支持,我过段时间会把代码回复到此贴里。
public static string s52s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz3";
//网站提交数据专用
public static string s52e(string n)
{
//"ABCDEFGHIJKL MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789"
int nl = n.Length;
List<char> t = new List<char>();
int a, x;
for (x = 0; x < nl; x++)
{
a = (int)n;
if (a < 144)
{
t.Add(s52s);
t.Add(s52s);
}
else if (a < 64000)
{
t.Add(s52s);
t.Add(s52s[(a / 40) % 40 + 12]);
t.Add(s52s);
}
else
{
t.Add('3');
t.Add(s52s);
t.Add(s52s[(a / 1600) % 40 + 12]);
t.Add(s52s[(a / 40) % 40 + 12]);
t.Add(s52s);
}
}
return "3" + new string(t.ToArray());
}
public static string s52d(string n)
{
if (!n.StartsWith("3")) return "";
int nl = n.Length;
List<char> t = new List<char>();
int a, x = 1, c;
while (x < nl)
{
a = s52s.IndexOf(n);
x++;
if (a < 12)
{
c = a * 12 + s52s.IndexOf(n);
}
else if (a < 52)
{
c = (a - 12) * 1600 + (s52s.IndexOf(n) - 12) * 40;
x++;
c += s52s.IndexOf(n) - 12;
}
else
{
x++;
a = s52s.IndexOf(n);
x++;
c = (a - 12) * 64000 + (s52s.IndexOf(n) - 12) * 1600;
x++;
c += (s52s.IndexOf(n) - 12) * 40;
x++;
c += s52s.IndexOf(n) - 12;
}
t.Add((char)c);
x++;
}
return new string(t.ToArray());
} 其中s52s是加密后的字符,不可以重复,改变顺序或字母可以影响加密结果,相当于一个52位长的密码。 改进了一下,速度快了一倍多,15000字加密再解密不用1毫秒
//网站提交数据专用
public static string s52s = "8ABC7DLO5MN6Z9EFGdeJfghijkHIVrstuvwWSTUXYabclmnopqKPQRxyz01234";
static bool s52t = true;
static int N, N2;
static int[] s52r = new int;
static void s52f()
{
N = s52s.Length;
N2 = N * N;
for (var x = 0; x < s52s.Length; x++)
{
s52r[(int)s52s] = x;
}
s52t = false;
}
public static string s52e(string n)
{
if (s52t) s52f();
int l = n.Length, a, x = 0;
List<char> t = new List<char>(l * 3);
for (; x < l; x++)
{
a = (int)n;
if (a < N2)
{
t.Add(s52s);
t.Add(s52s);
}
else
{
t.Add(s52s);
t.Add(s52s[(a / N) % N]);
t.Add(s52s);
}
}
string s = new string(t.ToArray());
return s.Length.ToString().Length + s.Length.ToString() + s;
}
public static string s52d(string n)
{
if (s52t) s52f();
int c;
if (!int.TryParse(n.ToString(), out c)) return "";
if (!int.TryParse(n.Substring(1, c), out c)) return "";
int x = c.ToString().Length + 1;
if (n.Length != c + x) return "";
int nl = n.Length, a;
List<char> t = new List<char>(nl * 3);
for (; x < nl; x++)
{
a = s52r[(int)n];
x++;
if (a < 5)
{
c = a * N + s52r[(int)n];
}
else
{
c = (a - 5) * N2 + s52r[(int)n] * N;
x++;
c += s52r[(int)n];
}
t.Add((char)c);
}
return new string(t.ToArray());
}
页:
[1]