我正在编写通用应用程序,如何使用 md5
或 SHA
算法对文件进行哈希处理?
我搜索了一下,发现了这个:system.security.cryptography
,但它在我的项目中不可用。
我使用的是 Visual Studio 2015。
在 UWP 中,它是 Windows.Security.Cryptography namespace和 Windows.Security.Cryptography.Core namespace .
在CryptographicBuffer class有示例显示如何使用此类。
这是我关于获取 MD5 哈希的演示:
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;
}
我是一名优秀的程序员,十分优秀!