需求描述
1)根据用户id生成唯一邀请码;
2)根据邀请码反推用户id;
主要步骤
1)设置邀请码位数len,自定义乱序字符串sourcecode,用户id;
注:乱序字符串增加其安全性;剔除sourcecode中的补位“0”和易混淆的“I,O”;
2)将用户id进行十六进制转换;
3)对转换后的字符串高位补零;
4)间隔插入随机字符;
代码实现
using System; namespace invitedCode { class Program { static void Main(string[] args) { int len = 10; //code偶数位 //自定义乱序字符串,‘0-9 A-Z’,剔除易混淆字符‘I,O’,剔除高位补‘0’ string sourcecode = "MWX89FCDG3J2RS1TUKLYZE5V67HQA4BNP"; int uid = 12345; //用户id string code = CreateCode(len,sourcecode, uid); string decode = Decode(code); Console.WriteLine(code); Console.WriteLine(decode); Console.ReadKey(); } private static string Decode(string code) { //提取用户id string str = ""; string uid = ""; for (int i = 0; i < code.Length; i += 2) { str += code.Substring(i, 1); } //剔除高位零 for (int i = 0; i < str.Length; i++) { if (!str.Substring(i, 1).Equals("0")) { str = str.Substring(i, str.Length - i); break; } } uid = Convert.ToInt32(str, 16).ToString(); return uid; } private static string CreateCode(int len, string sourcecode, int uid) { //十进制转十六进制 string hexid = Convert.ToString(uid,16); //高位补零 string str = ""; for (int i = len/2; i > hexid.Length; i--) { str += "0"; } str += hexid; //插入随机字符 Random ran = new Random(); for (int i = 1; i < str.Length+1; i += 2) { str = str.Insert(i, sourcecode.Substring(ran.Next(0, sourcecode.Length-1), 1)); } return str; } } }