Thanhtu150
Thanhtu150

Reputation: 91

How to hash file (MD5, SHA..v.v..) in UWP

I'm coding an Universal App, how can I hash a file with md5 or SHA algorithm ?

I searched, found this: system.security.cryptography, but it's not available in my project.

I'm using Visual Studio 2015.

Upvotes: 2

Views: 1485

Answers (2)

user1544428
user1544428

Reputation: 150

I'm going to throw this in, just because it is UWP... and if you use storageFolder.GetFileAsync to get to the file, the method will have to return an Async Task or a void. Forgive me if this isn't perfect, I'm more familiar with asp.net. But this does return a valid MD5 Hash on a file that was created in the LocalState folder:

private async Task<string> GetMD5Hash()
    {
        StorageFolder localFolder = ApplicationData.Current.LocalFolder;
        var storageFolder = localFolder; // await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);
        var file = await storageFolder.GetFileAsync("signature.png");

        byte[] computedHash = new MD5CryptoServiceProvider().ComputeHash(File.ReadAllBytes(file.Path));
        var sBuilder = new StringBuilder();
        foreach (byte b in computedHash)
        {
            sBuilder.Append(b.ToString("x2").ToLower());
        }
        string result = sBuilder.ToString();
        return result;
    }

Upvotes: 0

Grace Feng
Grace Feng

Reputation: 16652

In UWP, it is Windows.Security.Cryptography namespace and Windows.Security.Cryptography.Core namespace.

In the CryptographicBuffer class there is sample showing how to use this class.

Here is my demo about getting MD5 hash:

private string strAlgNameUsed;

public string GetMD5Hash(String strMsg)
{
    string strAlgName = HashAlgorithmNames.Md5;
    IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(strMsg, BinaryStringEncoding.Utf8);

    HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);
    strAlgNameUsed = objAlgProv.AlgorithmName;

    IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);

    if (buffHash.Length != objAlgProv.HashLength)
    {
        throw new Exception("There was an error creating the hash");
    }

    string hex = CryptographicBuffer.EncodeToHexString(buffHash);

    return hex;
}

Upvotes: 8

Related Questions