有没有一种方法可以生成唯一的字母数字 key (12 位数字)以在 C# 的 URL 中使用?我有一组彼此唯一的字符串,但不能直接使用它们,因为它们可能会改变,所以 URL 会中断。我有几种方法 -
a) 使用数据库表本身的主键,它对应于具有上述字符串集的行,但这似乎是一个安全问题,因为它会暴露数据库结构。
b) 使用 Guid,但它又不依赖于数据。
我们将不胜感激。
最佳答案
简短回答:否。
你正在尝试的是不可能的。 您必须跟踪您已经创建的 ID。这就是数据库对递增的索引列所做的事情。 I also understand that URL shortening tools take new keys from a pool of generated unique ones .
综上所述,something like this DotNetFiddle might work其他一些答案也可能如此。
在 fiddle 中,我们对第一个示例中的主键进行哈希处理。由于只有完整哈希在计算上不可行,因为每个输入都不是唯一的,并且由于我们使用的是哈希的子字符串,因此不能保证唯一性,但可能接近。
这是 MSDN 对哈希唯一性的看法。
A cryptographic hash function has the property that it is computationally infeasible to find two distinct inputs that hash to the same value.
在第二个示例中,我们使用了时间,据我所知,递增时间保证是唯一的,所以如果您可以相信时间是准确的,这将有效。但是,如果您要依赖服务器时间等外部资源,那么也许您应该在数据库表或简单的平面文件中使用自动递增索引。
using System;
using System.Text;
using System.Security.Cryptography;
public class Program
{
public static void Main()
{
UseAHash();
UseTime();
}
public static void UseAHash()
{
var primaryKey = 123345;
HashAlgorithm algorithm = SHA1.Create();
var hash = algorithm.ComputeHash(Encoding.UTF8.GetBytes(primaryKey.ToString()));
StringBuilder sb = new StringBuilder();
for (var i = 0; i < 6; ++i)
{
sb.Append(hash[i].ToString("X2"));
}
Console.WriteLine(sb);
}
public static void UseTime()
{
StringBuilder builder = new StringBuilder();
// use universal to avoid daylight to standard time change.
var now = DateTime.Now.ToUniversalTime();
builder.Append(now.DayOfYear.ToString("D3"));
builder.Append(now.Hour.ToString("D2"));
builder.Append(now.Minute.ToString("D2"));
builder.Append(now.Second.ToString("D2"));
builder.Append(now.Millisecond.ToString("D3"));
Console.WriteLine("Length: " + builder.Length);
Console.WriteLine("Result: " + builder);
}
}
关于c# - 如何生成唯一的 12 位字母数字 key 以用于 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333800/