using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myshipping.Application { public class SuperShortLinkHelper { private readonly string _base62CharSet = "s9LFkgy5RovixI1aOf8UhdY3r4DMplQZJXPqebE0WSjBn7wVzmN2Gc6THCAKut"; private readonly int _codeLength = 6; private readonly int _powMax = 62; public SuperShortLinkHelper() { } /// /// 补充0的长度 /// private int ZeroLength { get { return MaxValue.ToString().Length; } } /// /// Code长度位数下能达到的最大值 /// public long MaxValue { get { var max = (long)Math.Pow(_powMax, _codeLength) - 1; return (long)Math.Pow(10, max.ToString().Length - 1) - 1; } } /// /// 【混淆加密】转短码 /// 1、根据自增主键id前面补0,如:00000123 /// 2、倒转32100000 /// 3、把倒转后的十进制转六十二进制(乱序后) /// public string Confuse(long id) { if (id > MaxValue) { throw new Exception($"转换值不能超过最大值{MaxValue}"); } var idChars = id.ToString() .PadLeft(ZeroLength, '0') .ToCharArray() .Reverse(); var confuseId = long.Parse(string.Join("", idChars)); var base62Str = Encode(confuseId); return base62Str.PadLeft(_codeLength, _base62CharSet.First()); } /// /// 十进制 -> 62进制 /// public string Encode(long value) { if (value < 0) throw new ArgumentOutOfRangeException("value", "value must be greater or equal to zero"); var sb = new StringBuilder(); do { sb.Insert(0, _base62CharSet[(int)(value % _powMax)]); value /= _powMax; } while (value > 0); return sb.ToString(); } } public class ShortLinkOptions { public const string SectionName = "ShortShareLink"; /// /// 短码长度 /// [Range(1, int.MaxValue)] public int CodeLength { get; set; } /// /// 62位加密秘钥 /// [Required] public string Secrect { get; set; } /// /// 缓存数量限制 /// public int? CacheCountLimit { get; set; } /// /// 生成默认数据 /// public static ShortLinkOptions GenDefault() { return new ShortLinkOptions() { CacheCountLimit = 10000 }; } } }