Como Validar Chave de Acesso CT-e em C#

Validação de chaves de Conhecimento de Transporte Eletrônico (CT-e) em C#.

Introdução

Sistemas de gestão de transporte (TMS) em .NET requerem validação precisa de chaves CT-e.

O Algoritmo

Cálculo do dígito verificador via Módulo 11 sobre os 43 caracteres iniciais.

Implementação em Csharp

cte-generator.jscsharp
public static bool ValidateCteKey(string key)
{
    if (string.IsNullOrEmpty(key) || key.Length != 44 || !key.All(char.IsDigit)) return false;

    string baseKey = key.Substring(0, 43);
    int[] weights = { 2, 3, 4, 5, 6, 7, 8, 9 };
    int total = 0;
    int weightIndex = 0;

    for (int i = baseKey.Length - 1; i >= 0; i--)
    {
        total += (int)char.GetNumericValue(baseKey[i]) * weights[weightIndex];
        weightIndex = (weightIndex + 1) % 8;
    }

    int remainder = total % 11;
    int dv = (remainder < 2) ? 0 : 11 - remainder;
    return (int)char.GetNumericValue(key[43]) == dv;
}

Código otimizado para validação de chaves fiscais em C#, utilizando `char.GetNumericValue` e manipulação de strings.

Não quer escrever código?

Use nossa ferramenta online gratuita para processar CTE-GENERATOR instantaneamente. Perfeito para testes rápidos.

Usar Ferramenta de CTE-GENERATOR Online