简体   繁体   English

从网上图片计算MD5 hash

[英]Calculate the MD5 hash from an online image

I need to calculate the MD5 hash of an online image我需要计算一个在线图像的MD5 hash

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?如何获取在线文件的 BufferedStream?

Use the WebClient class to download the data from a given address.使用WebClient class 从给定地址下载数据。 Use the downloaded bytes array to create a MemoryStream object to be the source stream of the BufferedStream object.使用下载的字节数组创建一个MemoryStream object 作为BufferedStream object 的源 stream。

You have two ways to download:您有两种下载方式:

1. The Synchronize Way 1.同步方式

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 2.异步方式

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调用者:

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.这两个函数都为这张照片返回FA544EB95534BA35AE9D6EA0B3889934 hash,它的地址分配给调用者中的url变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM