/// <summary> /// 将数值字符串加密为短字符串 /// </summary> public static class NumberToShortString { /// <summary> /// 共62个字符 /// </summary> private static readonly string Keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; /// <summary> /// 将数值字符串加密为短字符串(7位数字转4位字符) /// </summary> /// <param name="numberStr"></param> /// <returns></returns> static string IntToEnode62(string numberStr) { var iNumber = long.Parse(numberStr); var result = ""; do { var m = iNumber % 62; result = Keys[(int)m] + result; iNumber = (iNumber - m) / 62; } while (iNumber > 0); return result.PadLeft(4, '0'); } /// <summary> /// 将加密后短字符串转换为原数值(4位字符转7位数字) /// </summary> /// <param name="shortStr"></param> /// <returns></returns> static long Encode62ToInt(string shortStr) { long num = 0; for (var i = 0; i < shortStr.Length; i++) { var n = shortStr.Length - i - 1; num += Convert.ToInt64(Keys.IndexOf(shortStr[i]) * Math.Pow(62, n)); } var temp = num.ToString().PadLeft(7, '0'); long.TryParse(temp, out num); return num; } /// <summary> /// 将加密后短字符串转换为原数值字符串 /// </summary> /// <param name="shortStr">密后短字符串</param> /// <returns>原数值字符串</returns> public static string StrToNumber(string shortStr) { var id = ""; for (var i = shortStr.Length - 4; i > -4; i = i - 4) //从最后往前以4字节为一组读取字符 { var offset = i < 0 ? 0 : i; var len = i < 0 ? shortStr.Length % 4 : 4; var str = Encode62ToInt(shortStr.Substring(offset, len)).ToString(); if (offset > 0) { //若不是第一组,则不足7位补0 str = str.PadLeft(7, '0'); } id = str + id; } return id; } /// <summary> /// 将数值字符串加密为短字符串 /// </summary> /// <param name="numberStr">原数值字符串,数值范围在[-9223372036854775808,9223372036854775807]</param> /// <returns>数字或字母加密短字符结果</returns> public static string NumberToStr(string numberStr) { long iNumber = 0l; if (!long.TryParse(numberStr, out iNumber)) { throw new Exception("数值字符串不在有效范围内!数值范围在[-9223372036854775808,9223372036854775807]"); } var result = ""; for (var i = numberStr.Length - 7; i > -7; i -= 7) { var offset1 = (i < 0) ? 0 : i; var offset2 = i + 7; var num = IntToEnode62(numberStr.Substring(offset1, offset2 - offset1)); result = num + result; } return result; } }