萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

中國居民身份證號碼驗證算法完整實現 (C#):15/18 位校驗、地址碼、出生日期、校驗碼全流程

前言:身份證校驗不只是正則匹配

中國居民身份證號碼遵循 **GB 11643-1999** 標準,包含地址碼(6)、出生日期(8/6)、順序碼(3)、校驗碼(1)。單純正則無法校驗日期合法性、校驗碼算法、地址碼有效性。本文提供生產級 `IDCardValidator` 類,涵蓋 15/18 位全流程驗證、異常處理、擴展方法、單元測試用例。

核心算法規範 (18 位)

  1. 結構:`[6位地址碼][8位出生日期 YYYYMMDD][3位順序碼][1位校驗碼]`
  2. 校驗碼計算 (ISO 7064:1983.MOD 11-2):
    
       權重因子 Wi = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2] (前17位)
       校驗碼映射 Y = [1,0,X,9,8,7,6,5,4,3,2] (模11餘數 0-10 對應)
       S = Σ(前17位數字 × Wi[i])
       Y = S % 11
       校驗碼 = Y[Y]
       
  3. 地址碼:前 6 位對應《中華人民共和國行政區劃代碼》,需維護最新代碼表或調用公安接口。
  4. 出生日期:第 7-14 位,需驗證合法日期 (含閏年)。

完整實現代碼 (C# 現代寫法)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

public static class IDCardValidator
{
    // 校驗碼映射表 (索引 = 模11餘數)
    private static readonly char[] CheckCodes = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
    // 權重因子
    private static readonly int[] Weights = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
    // 簡易地址碼前綴集合 (實際應接入完整行政區劃庫)
    private static readonly HashSet ValidAddressPrefixes = new()
    {
        "11","12","13","14","15","21","22","23","31","32","33","34","35","36","37","41","42","43","44","45","46",
        "50","51","52","53","54","61","62","63","64","65","71","81","82","91" // 省級代碼
        // 實際應包含完整 6 位地市區代碼,此處簡化為省級前綴驗證
    };

    /// 
    /// 統一驗證入口,自動識別 15/18 位
    /// 
    public static ValidationResult Validate(string idCard)
    {
        if (string.IsNullOrWhiteSpace(idCard))
            return ValidationResult.Fail("身份證號不能為空");

        idCard = idCard.Trim().ToUpper(); // 統一大寫 X

        return idCard.Length switch
        {
            18 => Validate18(idCard),
            15 => Validate15(idCard),
            _ => ValidationResult.Fail($"長度錯誤:{idCard.Length} 位,應為 15 或 18 位")
        };
    }

    /// 
    /// 18 位身份證完整驗證
    /// 
    public static ValidationResult Validate18(string id)
    {
        // 1. 格式:前17位數字,第18位數字或X
        if (!Regex.IsMatch(id, @"^\d{17}[\dX]$"))
            return ValidationResult.Fail("格式錯誤:前17位必須為數字,第18位為數字或X");

        // 2. 地址碼 (簡化版:省級前綴)
        string addrPrefix = id.Substring(0, 2);
        if (!ValidAddressPrefixes.Contains(addrPrefix))
            return ValidationResult.Fail($"地址碼無效:{addrPrefix} 不在合法省級代碼範圍");

        // 3. 出生日期
        if (!DateTime.TryParseExact(id.Substring(6, 8), "yyyyMMdd", null, System.Globalization.DateTimeStyles.None, out DateTime birth))
            return ValidationResult.Fail($"出生日期非法:{id.Substring(6, 8)}");

        // 合理性:年齡 0-120 歲
        int age = DateTime.Today.Year - birth.Year;
        if (birth > DateTime.Today.AddYears(-age)) age--;
        if (age < 0 || age > 120)
            return ValidationResult.Fail($"年齡不合理:{age} 歲");

        // 4. 校驗碼
        int sum = 0;
        for (int i = 0; i < 17; i++)
            sum += (id[i] - '0') * Weights[i];

        char expectedCheck = CheckCodes[sum % 11];
        char actualCheck = id[17];
        if (expectedCheck != actualCheck)
            return ValidationResult.Fail($"校驗碼錯誤:期望 {expectedCheck},實際 {actualCheck}");

        return ValidationResult.Success(new IDCardInfo
        {
            Number = id,
            AddressCode = id.Substring(0, 6),
            BirthDate = birth,
            Gender = (id[16] - '0') % 2 == 1 ? Gender.Male : Female, // 第17位奇男偶女
            CheckCode = actualCheck
        });
    }

    /// 
    /// 15 位身份證驗證 (舊版,無校驗碼,年份 2 位)
    /// 
    public static ValidationResult Validate15(string id)
    {
        if (!Regex.IsMatch(id, @"^\d{15}$"))
            return ValidationResult.Fail("格式錯誤:15位必須全為數字");

        string addrPrefix = id.Substring(0, 2);
        if (!ValidAddressPrefixes.Contains(addrPrefix))
            return ValidationResult.Fail($"地址碼無效:{addrPrefix}");

        // 15位年份為2位,補全為 19XX
        string birthStr = "19" + id.Substring(6, 6);
        if (!DateTime.TryParseExact(birthStr, "yyyyMMdd", null, System.Globalization.DateTimeStyles.None, out DateTime birth))
            return ValidationResult.Fail($"出生日期非法:{birthStr}");

        int age = DateTime.Today.Year - birth.Year;
        if (birth > DateTime.Today.AddYears(-age)) age--;
        if (age < 0 || age > 120)
            return ValidationResult.Fail($"年齡不合理:{age} 歲");

        return ValidationResult.Success(new IDCardInfo
        {
            Number = id,
            AddressCode = id.Substring(0, 6),
            BirthDate = birth,
            Gender = (id[14] - '0') % 2 == 1 ? Gender.Male : Female, // 第15位奇男偶女
            CheckCode = null
        });
    }

    /// 
    /// 15 位升級 18 位 (補全年份 + 計算校驗碼)
    /// 
    public static string Upgrade15To18(string id15)
    {
        var result = Validate15(id15);
        if (!result.IsValid) throw new ArgumentException(result.ErrorMessage);

        string base17 = "19" + id15.Substring(0, 17); // 實際前17位 = 19 + 原15位前17? 修正:
        // 正確邏輯:15位 = 6地址 + 6出生(YYMMDD) + 3順序
        // 18位 = 6地址 + 8出生(YYYYMMDD) + 3順序 + 1校驗
        string base17Correct = id15.Substring(0, 6) + "19" + id15.Substring(6, 6) + id15.Substring(12, 3);
        
        int sum = 0;
        for (int i = 0; i < 17; i++)
            sum += (base17Correct[i] - '0') * Weights[i];
        
        char check = CheckCodes[sum % 11];
        return base17Correct + check;
    }
}

// 輔助類型
public readonly record struct ValidationResult
{
    public bool IsValid { get; init; }
    public string ErrorMessage { get; init; }
    public IDCardInfo Info { get; init; }

    public static ValidationResult Success(IDCardInfo info) => new() { IsValid = true, Info = info };
    public static ValidationResult Fail(string msg) => new() { IsValid = false, ErrorMessage = msg };
}

public readonly record struct IDCardInfo
{
    public string Number { get; init; }
    public string AddressCode { get; init; }
    public DateTime BirthDate { get; init; }
    public Gender Gender { get; init; }
    public char? CheckCode { get; init; }
}

public enum Gender { Male, Female }

單元測試用例 (xUnit)


public class IDCardValidatorTests
{
    [Theory]
    [InlineData("11010519900307853X", true)]  // 有效 18 位
    [InlineData("110105199003078531", false)] // 校驗碼錯
    [InlineData("11010519900307853", false)]  // 長度錯
    [InlineData("110105202501011234", false)] // 未來出生日期
    [InlineData("99010519900307853X", false)] // 非法地址碼
    [InlineData("110105900307853", true)]     // 有效 15 位
    [InlineData("11010590030785", false)]     // 15位長度錯
    public void Validate_VariousInputs_ReturnsExpected(string id, bool expectedValid)
    {
        var result = IDCardValidator.Validate(id);
        Assert.Equal(expectedValid, result.IsValid);
    }

    [Fact]
    public void Upgrade15To18_ProducesValid18()
    {
        string id15 = "110105900307853";
        string id18 = IDCardValidator.Upgrade15To18(id15);
        Assert.True(IDCardValidator.Validate(id18).IsValid);
    }
}

生產環境擴展建議

  1. 地址碼庫:接入民政部最新《行政區劃代碼》Excel/數據庫,定期更新,支持精確到街道級驗證。
  2. 性能優化:熱路徑用 `Span` 避免 `Substring` 分配,預編譯 Regex (`RegexOptions.Compiled`),`ValidationResult` 用 `struct` 避免裝箱。
  3. 異步遠程校驗:高安全場景調用公安/運營商實名認證 API (OCR + 活體檢測),本地算法僅做首輪攔截。
  4. 隱私保護:日誌脫敏 `IDCardMasker.Mask(id)` → `110105********853X`,存儲加密 (AES-256-GCM)。

結語

身份證驗證看似簡單,實則涉及編碼標準、日期曆法、校驗算法、行政區劃維護、隱私合規多重維度。封裝為 `Validate` + `Upgrade15To18` 統一入口,配合 `ValidationResult` 模式返回豐富信息,能滿足從註冊表單攔截到實名認證核心鏈路的全鏈路需求。

copyright © 萬盛學電腦網 all rights reserved