Christian
Christian

Reputation: 194

Calculate the MD5 hash from an online image

I need to calculate the MD5 hash of an online image

For a locally saved image, I tried this code and it works as expected:

public static string GetHashFromFile(string fileName, HashAlgorithm algorithm)
{
    HashAlgorithm MD5 = new MD5CryptoServiceProvider();
    using (var stream = new BufferedStream(File.OpenRead(fileName), 100000))
    {
        return BitConverter.ToString(MD5.ComputeHash(stream)).Replace("-", string.Empty);
    }
}

How can I get the BufferedStream of an online file?

Upvotes: 1

Views: 1372

Answers (1)

user10216583
user10216583

Reputation:

Use the WebClient class to download the data from a given address. Use the downloaded bytes array to create a MemoryStream object to be the source stream of the BufferedStream object.

You have two ways to download:

1. The Synchronize Way

static string GetHashFromUrl(string url)
{
    using (var wc = new WebClient())
    {
        var bytes = wc.DownloadData(url);

        using (var md5 = new MD5CryptoServiceProvider())
        using (var ms = new MemoryStream(bytes))
        using (var bs = new BufferedStream(ms, 100_000))
            return BitConverter.ToString(md5.ComputeHash(bs)).Replace("-", string.Empty);
    }
}

... and a caller:

void TheCaller()
{
    try
    {
        var hash = GetHashFromUrl(url);
        //...
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }            
}

2. The Asynchronous Way

static async Task<string> GetHashFromUrlAsync(string url)
{
    using (var wc = new WebClient())
    using (var md5 = new MD5CryptoServiceProvider())
    {
        byte[] bytes = await wc.DownloadDataTaskAsync(url);
                
        using (var ms = new MemoryStream(bytes))
        using (var bs = new BufferedStream(ms, 100_000))
            return BitConverter.ToString(md5.ComputeHash(bs)).Replace("-", string.Empty);
    }
}

... and an async caller:

async void TheCaller()
{
    try
    {
        var hash = await Task.Run(() => GetHashFromUrlAsync(url));
        //...
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }            
}

Both functions return the FA544EB95534BA35AE9D6EA0B3889934 hash for this photo which it's address is assigned to the url variable in the callers.

Upvotes: 1

Related Questions