您的位置:首页 > 其它

win10应用 UWP 使用MD5算法

2016-06-02 00:00 316 查看
windows有自带的算法来计算MD5
原本在WPF是

private string get_MD5(string str)
{            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] temp;
StringBuilder strb = new StringBuilder();
temp = md5.ComputeHash(Encoding.Unicode.GetBytes(str));
md5.Clear();
for (int i = 0; i < temp.Length; i++)
{                strb.Append(temp[i].ToString("X").PadLeft(2 , '0'));
}
return strb.ToString().ToLower();
}

进行MD5,可是UWP没有System.Security.Cryptography.MD5CryptoServiceProvider

在msdn是

Windows.Security.Cryptography.Core.CryptographicHash

来作为MD5的类
这个类只有两个方法:Append,GetValueAndReset
不知道微软是怎么要这样做

弄了好久才知道要怎么去md5

下面代码演示了三段不同字符串,经过MD5之后得到值
不过之前需要

using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;

代码

public void ce()
{
//可以选择MD5 Sha1 Sha256 Sha384 Sha512
string strAlgName = HashAlgorithmNames.Md5;

// 创建一个 HashAlgorithmProvider 对象
HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);

// 创建一个可重用的CryptographicHash对象
CryptographicHash objHash = objAlgProv.CreateHash();

string strMsg1 = "这是一段待加密的字符串";
IBuffer buffMsg1 = CryptographicBuffer.ConvertStringToBinary(strMsg1 , BinaryStringEncoding.Utf16BE);
objHash.Append(buffMsg1);
IBuffer buffHash1 = objHash.GetValueAndReset();
string strHash1 = CryptographicBuffer.EncodeToBase64String(buffHash1);

string strMsg2 = "和前面一串不相同的字符串";
IBuffer buffMsg2 = CryptographicBuffer.ConvertStringToBinary(strMsg2 , BinaryStringEncoding.Utf16BE);
objHash.Append(buffMsg2);
IBuffer buffHash2 = objHash.GetValueAndReset();
string strHash2 = CryptographicBuffer.EncodeToBase64String(buffHash2);

string strMsg3 = "每个都不相同";
IBuffer buffMsg3 = CryptographicBuffer.ConvertStringToBinary(strMsg3 , BinaryStringEncoding.Utf16BE);
objHash.Append(buffMsg3);
IBuffer buffHash3 = objHash.GetValueAndReset();
string strHash3 = CryptographicBuffer.EncodeToBase64String(buffHash3);

_reminder.Append(strMsg1 + "\r\n");
_reminder.Append(strHash1 + "\r\n");
_reminder.Append(strMsg2 + "\r\n");
_reminder.Append(strHash2 + "\r\n");
_reminder.Append(strMsg3 + "\r\n");
_reminder.Append(strHash3 + "\r\n");
}

_reminder
是一个
StringBuilder
用于展示
这个MD5结果有英文字符和数字特殊字符

上面代码其实也可以改为
Sha1 Sha256 Sha384 Sha512
只要在第一句的MD5改为你要的

参考文献:https://msdn.microsoft.com/zh-cn/library/windows/apps/xaml/windows.security.cryptography.core.cryptographichash.aspx

判断ctrl按下

private void reminderkeydown(object sender , KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Control)
{
_ctrl = true;
}
if (_ctrl)
{
xreminder.Text = "ctrl+" + e.Key.ToString();
}
else
{
xreminder.Text =  e.Key.ToString();
}
}
private bool _ctrl;

private void reminderkeyup(object sender , KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Control)
{
_ctrl = false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: