转载URL短地址压缩算法⽂章转载
/// <summary>
/// ⽣成salt
/// </summary>
/// <returns></returns>
public static string GenerateSalt()
{
byte[] data = new byte[0x10];
new RNGCryptoServiceProvider().GetBytes(data);
return Convert.ToBase64String(data);
}
字符串长度压缩
public static string[] ShortUrl(string url)
{
//可以⾃定义⽣成MD5加密字符传前的混合KEY
string key = "anech";
//要使⽤⽣成URL的字符
string[] chars = new string[]{
"a" , "b" , "c" , "d" , "e" , "f" , "g" , "h" ,
"i" , "j" , "k" , "l" , "m" , "n" , "o" , "p" ,
"q" , "r" , "s" , "t" , "u" , "v" , "w" , "x" ,
"y" , "z" , "0" , "1" , "2" , "3" , "4" , "5" ,
"6" , "7" , "8" , "9" , "A" , "B" , "C" , "D" ,
"E" , "F" , "G" , "H" , "I" , "J" , "K" , "L" ,
"M" , "N" , "O" , "P" , "Q" , "R" , "S" , "T" ,
"U" , "V" , "W" , "X" , "Y" , "Z"
};
//对传⼊⽹址进⾏MD5加密
string hex = MD5(key + url);
string[] resUrl = new string[4];
for (int i = 0; i < 4; i++)
{
//把加密字符按照8位⼀组16进制与0x3FFFFFFF进⾏位与运算
int hexint = 0x3FFFFFFF & Convert.ToInt32("0x" + hex.Substring(i * 8, 8), 16);
string outChars = string.Empty;
for (int j = 0; j < 6; j++)
{
//把得到的值与0x0000003D进⾏位与运算,取得字符数组chars索引
int index = 0x0000003D & hexint;
//把取得的字符相加
outChars += chars[index];
//每次循环按位右移5位
hexint = hexint >> 5;
}
//把字符串存⼊对应索引的输出数组
resUrl[i] = outChars;
}
return resUrl;
}
public static string MD5(String input)
{
byte[] res = new MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(input));
return BitConverter.ToString(res).Replace("-", "");
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论