我正在创建一个MetroStyle应用程序,我想为我的字符串生成一个MD5代码。到目前为止,我已经用过这个:
public static string ComputeMD5(string str)
{
try
{
var alg = HashAlgorithmProvider.OpenAlgorithm("MD5");
IBuffer buff = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8);
var hashed = alg.HashData(buff);
var res = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, hashed);
return res;
}
catch (Exception ex)
{
return null;
}
}
但它会抛出System.ArgumentOutOfRangeException
类型的异常,并显示以下错误消息:
No mapping for the Unicode character exists in the target multi-byte code page. (Exception from HRESULT: 0x80070459)
我在这里做错了什么?
答案 0 :(得分:37)
行。我发现了如何做到这一点。这是最终的代码:
public static string ComputeMD5(string str)
{
var alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
IBuffer buff = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8);
var hashed = alg.HashData(buff);
var res = CryptographicBuffer.EncodeToHexString(hashed);
return res;
}