Хранимый файл Azure имеет другую контрольную сумму MD5, чем локальный файл (это тот же файл).

Я использую службу can для загрузки файлов в службу хранилища Azure, поэтому я хочу проверить целостность файла с помощью контрольной суммы MD5, поэтому сначала я получаю контрольную сумму из функции.

public static string GetMD5HashFromFile(Stream stream)
{
    using (var md5 = MD5.Create())
    {
        return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", string.Empty);
    }
}

для тестового файла, который я использую, я получаю: 1dffc245282f4e0a45a9584fe90f12f2, и я получил тот же результат, когда использую онлайн-инструмент, такой как это.

Затем я загружаю файл в Azure и получаю его из своего кода следующим образом: (Чтобы не включать проверки, предположим, что файл и каталоги существуют.)

public bool CompareCheckSum(string fileName, string checksum)
{
    this.storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("MyConnectionString"));
    this.fileClient = this.storageAccount.CreateCloudFileClient();
    this.shareReference = this.fileClient.GetShareReference(CloudStorageFileShareSettings.StorageFileShareName);
    this.rootDir = this.shareReference.GetRootDirectoryReference();
    this.directoryReference = this.rootDir.GetDirectoryReference("MyDirectory");
    this.fileReference = this.directoryReference.GetFileReference(fileName);

    Stream stream = new MemoryStream();
    this.fileReference.DownloadToStream(stream);
    string azureFileCheckSum = GetMD5HashFromFile(stream);

    return azureFileCheckSum.ToLower() == checksum.ToLower();
}

Я также попытался получить контрольную сумму, используя другой процесс, например:

public bool CompareCheckSum(string fileName, string checksum)
{
    this.storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("MyConnectionString"));
    this.fileClient = this.storageAccount.CreateCloudFileClient();
    this.shareReference = this.fileClient.GetShareReference(CloudStorageFileShareSettings.StorageFileShareName);
    this.rootDir = this.shareReference.GetRootDirectoryReference();
    this.directoryReference = 
    this.rootDir.GetDirectoryReference("MyDirectory");
    this.fileReference = this.directoryReference.GetFileReference(fileName);

    this.fileReference.FetchAttributes();
    string azureFileCheckSum = this.fileReference.Metadata["md5B64"];

    return azureFileCheckSum.ToLower() == checksum.ToLower();  
}

Наконец, для azureFileCheckSum я получаю: d41d8cd98f00b204e9800998ecf8427e не уверен, что я делаю что-то неправильно или что-то изменилось, когда я загружаю файл на ftp...


person Leonardo Raygoza    schedule 04.08.2017    source источник


Ответы (1)


Прежде чем вызывать md5.ComputeHash(stream), вам нужно сбросить позицию потока в начало.

stream.Position = 0;

Конечно, это не удастся с NotSupportedException, если тип потока не поддерживает поиск, но в вашем случае это должно работать.

person Matt Johnson-Pint    schedule 04.08.2017
comment
Совет для профессионалов: d41d8cd98f00b204e9800998ecf8427e — это хэш MD5 из нулевых байтов, поэтому его легко обнаружить. - person Matt Johnson-Pint; 05.08.2017