[ Windows Phone 8.1 / Windows 8 ] How To Get MD5 / SHA256 Hash Of File Stream Or String

Как получить хеш файла или строки

В Windows Phone Silverlight это делалось немного иначе, теперь же, нас постепенно ведут к единому стандарту:

using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage;
using Windows.Storage.Streams;

// ...

        public async Task<string> NewSHA256(StorageFile file)
        {
            IBuffer buffFile = await FileIO.ReadBufferAsync(file);
            HashAlgorithmProvider hashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
            IBuffer buffHash = hashProvider.HashData(buffFile);

            return CryptographicBuffer.EncodeToHexString(buffHash);
        }

Пример для строки и прочую справочную информацию, как всегда, смотрим на msdn.

HashAlgorithmNames, нам гарантирует получение и других хешей, аналогичным образом (md5, sha512 и т.д). При желании добавляем параметром функции название алгоритма.

Держим в голове, что при считывании в буфер слишком больших файлов мы можем столкнуться с проблемами.

 Решить данные вопросы можно, к примеру, так:

        public static async Task<string> GetHash(StorageFile file, string alg)
        {
            HashAlgorithmProvider hashProvider = HashAlgorithmProvider.OpenAlgorithm(alg);
            
            CryptographicHash cryptoHash = hashProvider.CreateHash();

            using (var stream = await file.OpenStreamForReadAsync())
            {
                int count;
                var buffer = new byte[4096];

                while ((count = stream.Read(buffer, 0, 4096)) > 0)
                {
                    cryptoHash.Append(buffer.AsBuffer(0, count));
                }
            }

            return CryptographicBuffer.EncodeToHexString(cryptoHash.GetValueAndReset());
        }

 

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *