Escrito em April 22nd, 2009 as 5:54 pm por Guilherme Bacellar

0 Comentários

Todos sabemos que CRC serve para verificar a integridade de algum tipo de conteúdo (normalmente arquivos), mas, como calcula-los?

Bom, neste artigo vamos ver como Calcular o CRC de Textos (ComputeStringCRC), Arrays (ComputeCRCFromByteArray) e Arquivos (ComputeCRCFromFile).

Os métodos aqui apresentados retornam um array de bytes como resultado do Cálculo do Hash. Se você desejar obter uma representação em Base64, consulte o arquivo sobre Base64 clicando Aqui.

Então, vamos lá!

C#

/// <summary>
/// Helper para Calculo de CRC
/// </summary>
public sealed class CRCHelper
{
    /// <summary>
    /// Calcula o CRC de um Arquivo
    /// </summary>
    /// <param name="filePath">Caminho do Arquivo</param>
    /// <returns></returns>
    public byte[] ComputeCRCFromFile(string filePath)
    {
        // Cria Objetos
        System.IO.FileStream fs;
        byte[] fileContent;

        // Verifica se o Arquivo não Existe
        if (! System.IO.File.Exists(filePath))
        {
            return null;
        }

        // Abre o Arquivo
        using (fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
        {
            // Inicializa o Array de Bytes com o Conteúdo do Arquivo
            fileContent = new byte[fs.Length];

            // Lê o Arquivo
            fs.Read(fileContent, 0, fileContent.Length);

            // Fecha o FileStream
            fs.Close();
        }

        // Computa o Hash e Retorna
        return this.ComputeCRCFromByteArray(fileContent);
    }

    /// <summary>
    /// Calcula o CRC de um Texto (String)
    /// </summary>
    /// <param name="textContent"></param>
    /// <returns></returns>
    public byte[] ComputeStringCRC(string textContent)
    {
        // Cria Objetos
        byte[] textArrayContent;

        // Converte o Texto em Array de Bytes
        textArrayContent = System.Text.Encoding.UTF8.GetBytes(textContent);

        // Computa o Hash e Retorna
        return this.ComputeCRCFromByteArray(textArrayContent);
    }

    /// <summary>
    /// Calcula o CRC de um Array de Bytes
    /// </summary>
    /// <param name="source">Array de Bytes a ser Calculado</param>
    /// <returns></returns>
    public byte[] ComputeCRCFromByteArray(byte[] source)
    {
        // Cria SHA512 para o Hash
        System.Security.Cryptography.SHA512 hashManager = System.Security.Cryptography.SHA512Managed.Create();

        // Computa o Hash e Retorna
        return hashManager.ComputeHash(source);
    }
}

VB.Net

''' <summary>
''' Helper para Calculo de CRC
''' </summary>
''' <remarks></remarks>
Public Class CRCHelper

    ''' <summary>
    ''' Calcula o CRC de um Array de Bytes
    ''' </summary>
    ''' <param name="source">Array de Bytes a ser Calculado</param>
    ''' <returns></returns>
    Public Function ComputeCRCFromByteArray(ByVal source As Byte()) As Byte()

        ' Cria SHA512 para o Hash
        Dim hashManager As System.Security.Cryptography.SHA512 = System.Security.Cryptography.SHA512Managed.Create()

        ' Computa o Hash e Retorna
        Return hashManager.ComputeHash(source)

    End Function

    ''' <summary>
    ''' Calcula o CRC de um Arquivo
    ''' </summary>
    ''' <param name="filePath">Caminho do Arquivo</param>
    ''' <returns></returns>
    Public Function ComputeCRCFromFile(ByVal filePath As String) As Byte()

    ' Cria Objetos
    Dim fs As System.IO.FileStream
    Dim fileContent As Byte()

    ' Verifica se o Arquivo não Existe
    If (Not System.IO.File.Exists(filePath)) Then
        Return Nothing
    End If

    ' Abre o Arquivo
    fs = New System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)
    Using (fs)

        ' Inicializa o Array de Bytes com o Conteúdo do Arquivo
        ReDim fileContent(fs.Length)

        ' Lê o Arquivo
        fs.Read(fileContent, 0, fileContent.Length)

        ' Fecha o FileStream
        fs.Close()

    End Using

    ' Computa o Hash e Retorna
    Return ComputeCRCFromByteArray(fileContent)

    End Function

    ''' <summary>
    ''' Calcula o CRC de um Texto (String)
    ''' </summary>
    ''' <param name="textContent"></param>
    ''' <returns></returns>
    Public Function ComputeStringCRC(ByVal textContent As String) As Byte()

        ' Cria Objetos
        Dim textArrayContent As Byte()

        ' Converte o Texto em Array de Bytes
        textArrayContent = System.Text.Encoding.UTF8.GetBytes(textContent)

        ' Computa o Hash e Retorna
        Return ComputeCRCFromByteArray(textArrayContent)

    End Function

End Class

Bom, espero que mais esse (Code Sharing) lhe seja útil.

Posts Relacionados:

  1. Compressão de (Compactar) Dados
  2. Converter um Array de Bytes para String e String para Array de Bytes
  3. Abrindo Arquivos de Texto e Lendo Todo o Conteúdo
  4. Abrindo Arquivos Texto e Lendo Linha a Linha
  5. Convertendo String Delimitada por Tamanho (Trancode) em Array
  6. Convertendo Caminhos Absolutos e URL’s Absolutas para Caminhos Relativos e URL’s Relativas
  7. Compressão de (Compactar) ViewState
, , , , ,

Be the first to start a conversation

Deixa uma Resposta

znjdb32s6g