我意识到这是一篇旧帖子,但我认为发布我的混淆整数 id 的技术可能会有所帮助
缺点:确实使用超过 8 个字符,仅适用于 3300 万以下的 id 值
优点:不需要密钥去混淆,URL/cookie 友好,每次生成不同的值,这使得破解更加困难,没有冲突,包括校验和功能,以消除随机/蛮力破解尝试(上述帖子未解决的一个问题是人们试图“抓取”您的网站。如果我看到一个以 id=123 结尾的 url,我知道我可以尝试 id=124 等...以获取更多数据,这就是为什么一些 XOR 示例可能不是一个好主意)
我建议稍微调整一下(我已经为我做过),因为我认为您不应该使用公开发布的混淆技术,但这是一个很好的起点。
编码愉快!
public static string ObfuscateId(int id)
{
try
{
string rtn;
int sid = id + 279;
int xm = sid * 3;
int xl = xm.ToString().Length + 10;
string sc = xl.ToString().Substring(1, 1);
string fc = xl.ToString().Substring(0, 1);
string csum = sid.ToString().Substring(sid.ToString().Length - 3);
rtn = Guid.NewGuid().ToString().Replace("-", "").ToLower();
rtn = sc + rtn.Substring(2, 26) + fc;
rtn = rtn.Remove(4, 3).Insert(4, csum);
rtn = rtn.Remove(xl, (xl - 10)).Insert(xl, xm.ToString());
rtn = rtn.Replace('1', 'g');
rtn = rtn.Replace('2', 'h');
rtn = rtn.Replace('3', 'i');
rtn = rtn.Replace('4', 'w');
rtn = rtn.Replace('5', 'y');
rtn = rtn.Replace('6', 'u');
rtn = rtn.Replace('7', 'z');
rtn = rtn.Replace('8', 'l');
rtn = rtn.Replace('9', 'v');
rtn = rtn.Replace('0', 'n');
rtn = rtn.Replace('c', 'j');
rtn = rtn.Replace('d', 'p');
rtn = rtn.Replace('f', 'q');
return rtn.ToUpper();
}
catch
{
return "ERROR BAD ID";
}
}
public static int DeObfuscateId(string obtxt)
{
try
{
string rtn;
int id;
rtn = obtxt.ToLower();
rtn = rtn.Replace('g', '1');
rtn = rtn.Replace('h', '2');
rtn = rtn.Replace('i', '3');
rtn = rtn.Replace('w', '4');
rtn = rtn.Replace('y', '5');
rtn = rtn.Replace('u', '6');
rtn = rtn.Replace('z', '7');
rtn = rtn.Replace('l', '8');
rtn = rtn.Replace('v', '9');
rtn = rtn.Replace('n', '0');
rtn = rtn.Replace('j', 'c');
rtn = rtn.Replace('p', 'd');
rtn = rtn.Replace('q', 'f');
string sc = rtn.Substring(0, 1);
string fc = rtn.Substring(rtn.Length - 1);
int xl = int.Parse(fc + sc);
int mv = int.Parse(rtn.Substring(xl, (xl - 10)));
int sid = mv / 3;
id = sid - 279;
string csum = sid.ToString().Substring(sid.ToString().Length - 3);
string xsum = rtn.Substring(4, 3);
if (csum!=xsum)
{
return -99999;
}
return id;
}
catch
{
return -99999;
}
}
}