我知道我可以在 c# 中轻松使用 MD5,我使用的代码如下:
using System.Security.Cryptography;
public static string MD5(string input)
{
MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
return s.ToString();
}
通常,MD5 字符串长度为 32 个字符,包含 0-9 和 af。我想知道,如果我使用 0-9 AZ az 和 _ 。- 等等,这将设置大约 64 个字符,并且 MD5 字符串将显着缩短。我将使用 MD5 字符串来识别某些内容并保存在数据库中。较短的字符串可以做同样的事情并且占用更少的空间,花费更少的时间来索引。
所以在这里,我的问题是,这里有没有人可以快速将 0-9a-f 字符串更改为 0-9A-Za-z._ 字符串
ps 我有一个基本的想法是将 MD5 字符串更改为 int(将非常大),然后转换为具有任何字符集的字符串。我可以成像它会变慢。
任何想法都有帮助。谢谢。
[编辑]
谢谢大家,最终我推出了自己的一个,我需要一个字符串,因为我也需要它作为 URL 的一部分。出于我不使用 Base64 的原因,因为我想要一个固定长度的字符串。
MD5 为 16 个字符,长度为 32,当我将其更改为 64 个字符时,长度变为 20。
这是我使用的更新功能。
public static string MD520(string input)
{
char[] chars = new char[] { '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', '-', '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' };
MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
byte m = 0;
int c = 0;
foreach (byte b in bs)
{
if (m == 2)
{
c = c * b;
for (byte i = 0; i < 4; i++)
{
int n = c % 64;
s.Append(chars[n]);
c = (c - n) / 64;
}
m = 0;
}
else
{
c = ((m > 0) ? c : 1) * b;
m++;
}
}
return s.ToString();
}