好吧,我在 MySQL 的 ASP Core 数据库中有用户,基本上这些用户将通过印在其中的二维码链接到物理卡,基本上除了由 ASP Core 生成的
Id
之外,我也想创建自己的ID,以便每当物理卡需要失效或丢失时,我可以重新生成物理卡中的编码ID,目前我的格式是[32个随机生成的字母数字字符]。[unix时间戳],我的代码如下
public static string GenerateSecureUniqueId()
{
return $"{GenerateRandomString(32)}.{GenerateDateTimeHash(DateTime.Now)}";
}
private const string AlphanumericChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public static string GenerateRandomString(int length)
{
var sb = new StringBuilder(length);
for (int i = 0; i < length; i++)
{
int index = Random.Next(AlphanumericChars.Length);
sb.Append(AlphanumericChars[index]);
}
return sb.ToString();
}
private static long ConvertToUnixTimestamp(DateTime dateTime)
{
return ((DateTimeOffset)dateTime).ToUnixTimeMilliseconds();
}
public static string GenerateDateTimeHash(DateTime dateTime)
{
byte[] dateTimeBytes = BitConverter.GetBytes(ConvertToUnixTimestamp(dateTime));
return ByteArrayToHexString(dateTimeBytes);
}
现在我的问题是,这样可以避免碰撞吗?我还想问是否可以进一步缩短这个长度,以便二维码更容易打印在身份证上。我只是想补充一点,我有大约 50 万多个用户,这个 ID 生成器函数不仅会在用户上使用,还会与其他表(例如聊天、元数据等)一起使用,所以我需要它能够安全地防止冲突。
在GenerateRandomString中您可以添加对生成的Id的验证。检查数据库中生成的 ID 是否存在。如果存在,则生成下一个。