驗證身分證號及產生身分證號
驗證身分證號
public static bool IsTaiwanID(string id)
{
if (string.IsNullOrEmpty(id)) return false;
if (id.Length != 10) return false;
if (char.IsNumber(id[0])) return false;
if (id[1] != '1' && id[1] != '2') return false;
const string ABC = "10987654932210898765431320";
var sum = ABC[id[0] - (id[0] < 97 ? 65 : 97)]-48;
for (int i = 1; i < 8; i++)
sum += (id[i] - 48) * (9 - i);
sum += (id[8] - 48);
sum += (id[9] - 48);
return sum % 10 == 0;
}
產生身分證號
public static string RandomTaiwanID(
char? location = null,
bool? isFemale = null,
string numbers = null)
{
var tmp = new List<char>();
var buf = new byte[10];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(buf);
}
if (location.HasValue)
{
if (!char.IsLetter(location.Value))
throw new ArgumentException("location");
tmp.Add(location.Value);
}
else
{
tmp.Add((char)(65 + (buf[0] % 26)));
}
if (isFemale.HasValue)
tmp.Add(isFemale.Value ? '2' : '1');
else
tmp.Add((buf[1] & 1) == 1 ? '2' : '1');
if (!string.IsNullOrEmpty(numbers))
tmp.AddRange(numbers);
for (int i = 2; i < buf.Length && tmp.Count < 9; i++)
tmp.Add((char)(48 + (buf[i] % 10)));
if (tmp.Count > 9)
tmp.RemoveRange(9, tmp.Count - 9);
var id = new string(tmp.ToArray());
const string ABC = "10987654932210898765431320";
var sum = ABC[id[0] - (id[0] < 97 ? 65 : 97)] - 48;
for (int i = 1; i < 8; i++)
sum += (id[i] - 48) * (9 - i);
sum += (id[8] - 48);
var d = sum % 10;
if (d != 0)
d = 10 - d;
return id + (char)(d + 48);
}