原文:重新想象 Windows 8 Store Apps (31) - 加密解密: 哈希算法, 对称算法

[源码下载]

重新想象 Windows 8 Store Apps (31) - 加密解密: 哈希算法, 对称算法

作者:webabcd

介绍
重新想象 Windows 8 Store Apps 之 加密解密

  • hash 算法(MD5, SHA1, SHA256, SHA384, SHA512)
  • hmac 算法(MD5, SHA1, SHA256, SHA384, SHA512)
  • 本地数据的加密解密
  • 对称算法(AES, DES, 3DES, RC2, RC4)

示例
1、演示如何使用 hash 算法(MD5, SHA1, SHA256, SHA384, SHA512)
Crypto/Hash.xaml.cs

/*
* 演示如何使用 hash 算法(MD5, SHA1, SHA256, SHA384, SHA512)
*/ using System;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace XamlDemo.Crypto
{
public sealed partial class Hash : Page
{
public Hash()
{
this.InitializeComponent();
} private void btnDemo_Click(object sender, RoutedEventArgs e)
{
string plainText = "i am webabcd"; lblMsg.Text = "原文: " + plainText;
lblMsg.Text += Environment.NewLine;
lblMsg.Text += Environment.NewLine; string[] algorithmNames = { "MD5", "SHA1", "SHA256", "SHA384", "SHA512" }; foreach (var algorithmName in algorithmNames)
{
// 根据算法名称实例化一个哈希算法提供程序
HashAlgorithmProvider hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(algorithmName);
// hashAlgorithm.HashLength - 哈希后的值的长度,单位:字节 // 原文的二进制数据
IBuffer vector = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8); // 哈希二进制数据
IBuffer digest = hashAlgorithm.HashData(vector); lblMsg.Text += algorithmName + ": " + CryptographicBuffer.EncodeToHexString(digest);
lblMsg.Text += Environment.NewLine; // 创建一个可重用的 CryptographicHash 对象
CryptographicHash reusableHash = hashAlgorithm.CreateHash();
reusableHash.Append(CryptographicBuffer.ConvertStringToBinary("i ", BinaryStringEncoding.Utf8)); // 向 CryptographicHash 中追加需要哈希的二进制数据
reusableHash.Append(CryptographicBuffer.ConvertStringToBinary("am ", BinaryStringEncoding.Utf8)); // 向 CryptographicHash 中追加需要哈希的二进制数据
reusableHash.Append(CryptographicBuffer.ConvertStringToBinary("webabcd", BinaryStringEncoding.Utf8)); // 向 CryptographicHash 中追加需要哈希的二进制数据 // 获取哈希后的数据,然后清空 CryptographicHash 中的数据
digest = reusableHash.GetValueAndReset(); lblMsg.Text += algorithmName + ": " + CryptographicBuffer.EncodeToHexString(digest);
lblMsg.Text += Environment.NewLine;
lblMsg.Text += Environment.NewLine;
}
}
}
}

2、演示如何使用 hmac 算法(HMAC_MD5, HMAC_SHA1, HMAC_SHA256, HMAC_SHA384, HMAC_SHA512)
Crypto/Hmac.xaml.cs

/*
* 演示如何使用 hmac 算法(HMAC_MD5, HMAC_SHA1, HMAC_SHA256, HMAC_SHA384, HMAC_SHA512)
*
* 注:hmac 相当于带密钥的 hash,可以理解为将信息用密钥加密后再哈希
*/ using System;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace XamlDemo.Crypto
{
public sealed partial class Hmac : Page
{
public Hmac()
{
this.InitializeComponent();
} private void btnDemo_Click(object sender, RoutedEventArgs e)
{
string plainText = "i am webabcd"; lblMsg.Text = "原文: " + plainText;
lblMsg.Text += Environment.NewLine;
lblMsg.Text += Environment.NewLine; string[] algorithmNames = { "HMAC_MD5", "HMAC_SHA1", "HMAC_SHA256", "HMAC_SHA384", "HMAC_SHA512" }; foreach (var algorithmName in algorithmNames)
{
// 根据算法名称实例化一个 hmac 算法提供程序
MacAlgorithmProvider hmacAlgorithm = MacAlgorithmProvider.OpenAlgorithm(algorithmName);
// hmacAlgorithm.MacLength - hmac 后的值的长度,单位:字节 // 创建一个用于 hmac 算法的随机的 key
IBuffer key = CryptographicBuffer.GenerateRandom(hmacAlgorithm.MacLength); // 根据 key 生成 CryptographicKey 对象
CryptographicKey hmacKey = hmacAlgorithm.CreateKey(key); // 根据 hmacKey 签名指定的内容
IBuffer signature = CryptographicEngine.Sign(
hmacKey, // 签名时所用的 key
CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8) // 需要签名的内容
); lblMsg.Text += algorithmName + ": " + CryptographicBuffer.EncodeToHexString(signature) + " (key: " + CryptographicBuffer.EncodeToHexString(key) + ")";
lblMsg.Text += Environment.NewLine; // 验证签名
bool isAuthenticated = CryptographicEngine.VerifySignature(
hmacKey, // 签名时所用的 key
CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8), // 需要签名的内容
signature // 签名后的值
); lblMsg.Text += "isAuthenticated: " + isAuthenticated;
lblMsg.Text += Environment.NewLine;
lblMsg.Text += Environment.NewLine;
}
}
}
}

3、演示如何对本地数据进行加密和解密
Crypto/LocalCrypto.xaml.cs

/*
* 演示如何对本地数据进行加密和解密
*/ using System;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.DataProtection;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace XamlDemo.Crypto
{
public sealed partial class LocalCryptoString : Page
{
public LocalCryptoString()
{
this.InitializeComponent();
} private async void btnDemo_Click(object sender, RoutedEventArgs e)
{
string plainText = "i am webabcd"; lblMsg.Text = "原文: " + plainText;
lblMsg.Text += Environment.NewLine; // 实例化用于加密的 DataProtectionProvider - Local=user 用户级别的本地加解密;LOCAL=machine - 机器级别的本地加解密
DataProtectionProvider provider = new DataProtectionProvider("Local=user"); // "LOCAL=machine" // 原文的二进制数据
IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8); // 加密数据
IBuffer encrypted = await provider.ProtectAsync(buffer);
// provider.ProtectStreamAsync(); 加密 stream 类型的数据 // 加密后的结果
lblMsg.Text += "encrypted: " + CryptographicBuffer.EncodeToHexString(encrypted);
lblMsg.Text += Environment.NewLine; // 实例化用于解密的 DataProtectionProvider
DataProtectionProvider provider2 = new DataProtectionProvider(); // 解密数据
IBuffer decrypted = await provider2.UnprotectAsync(encrypted);
// provider2.UnprotectStreamAsync(); // 解密 stream 类型的数据 // 解密后的结果
lblMsg.Text += "decrypted: " + CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decrypted);
lblMsg.Text += Environment.NewLine;
} }
}

4、演示如何使用对称算法(AES, DES, 3DES, RC2, RC4)
Crypto/Symmetric.xaml.cs

/*
* 演示如何使用对称算法(AES, DES, 3DES, RC2, RC4)
*/ using System;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace XamlDemo.Crypto
{
public sealed partial class Symmetric : Page
{
public Symmetric()
{
this.InitializeComponent();
} private void btnDemo_Click(object sender, RoutedEventArgs e)
{
// 本示例的原文为 16 个字节,是为了正常演示无填充时的加密
// 什么是填充:比如 aes 要求数据长度必须是 16 的倍数,如果不是则需要通过指定的填充模式来补全数据
string plainText = ""; lblMsg.Text = "原文: " + plainText;
lblMsg.Text += Environment.NewLine;
lblMsg.Text += Environment.NewLine; string[] algorithmNames = { "AES_CBC", "AES_ECB", "AES_CBC_PKCS7", "AES_ECB_PKCS7", "DES_CBC", "DES_ECB", "3DES_CBC", "3DES_ECB", "3DES_CBC_PKCS7", "3DES_ECB_PKCS7", "RC2_CBC", "RC2_ECB", "RC4" }; foreach (var algorithmName in algorithmNames)
{
uint keySize = ;
if (algorithmName.StartsWith("AES")) // AES 算法密钥长度 128 位
keySize = ;
else if (algorithmName.StartsWith("DES")) // DES 算法密钥长度 64 位(56 位的密钥加上 8 位奇偶校验位)
keySize = ;
else if (algorithmName.StartsWith("3DES")) // 3DES 算法密钥长度 192 位(3 重 DES)
keySize = ;
else if (algorithmName.StartsWith("RC2")) // RC2 算法密钥长度可变
keySize = ;
else if (algorithmName.StartsWith("RC4")) // RC4 算法密钥长度可变
keySize = ; IBuffer buffer; // 原文
IBuffer encrypted; // 加密后
IBuffer decrypted; // 解密后
IBuffer iv = null; // 向量(CBC 模式) // 根据算法名称实例化一个对称算法提供程序
SymmetricKeyAlgorithmProvider symmetricAlgorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName); // 创建一个随机密钥 key
IBuffer key = CryptographicBuffer.GenerateRandom(keySize / ); // 根据 key 生成 CryptographicKey 对象
CryptographicKey cryptoKey = symmetricAlgorithm.CreateSymmetricKey(key); // 如果是 CBC 模式则随机生成一个向量
if (algorithmName.Contains("CBC"))
iv = CryptographicBuffer.GenerateRandom(symmetricAlgorithm.BlockLength); // 将需要加密的数据转换为 IBuffer 类型
buffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8); try
{
// 加密数据
encrypted = CryptographicEngine.Encrypt(cryptoKey, buffer, iv);
}
catch (Exception ex)
{
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewLine;
return;
} // 加密后的结果
lblMsg.Text += algorithmName + " encrypted: " + CryptographicBuffer.EncodeToHexString(encrypted);
lblMsg.Text += Environment.NewLine; CryptographicKey cryptoKey2 = symmetricAlgorithm.CreateSymmetricKey(key);
try
{
// 解密数据
decrypted = Windows.Security.Cryptography.Core.CryptographicEngine.Decrypt(cryptoKey2, encrypted, iv);
}
catch (Exception ex)
{
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewLine;
return;
} // 解密后的结果
lblMsg.Text += algorithmName + " decrypted: " + CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decrypted);
lblMsg.Text += Environment.NewLine;
lblMsg.Text += Environment.NewLine;
}
}
}
}

OK
[源码下载]

重新想象 Windows 8 Store Apps (31) - 加密解密: 哈希算法, 对称算法的更多相关文章

  1. 重新想象 Windows 8 Store Apps (32) - 加密解密: 非对称算法, 数据转换的辅助类

    原文:重新想象 Windows 8 Store Apps (32) - 加密解密: 非对称算法, 数据转换的辅助类 [源码下载] 重新想象 Windows 8 Store Apps (32) - 加密 ...

  2. 重新想象 Windows 8 Store Apps 系列文章索引

    [源码下载][重新想象 Windows 8.1 Store Apps 系列文章] 重新想象 Windows 8 Store Apps 系列文章索引 作者:webabcd 1.重新想象 Windows ...

  3. 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo

    [源码下载] 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo 作者:webabcd 介绍重新想象 Wind ...

  4. 重新想象 Windows 8 Store Apps (35) - 通知: Toast 详解

    [源码下载] 重新想象 Windows 8 Store Apps (35) - 通知: Toast 详解 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 通知 Toa ...

  5. 重新想象 Windows 8 Store Apps (36) - 通知: Tile 详解

    [源码下载] 重新想象 Windows 8 Store Apps (36) - 通知: Tile 详解 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 通知 Tile ...

  6. 重新想象 Windows 8 Store Apps (37) - 契约: Settings Contract

    [源码下载] 重新想象 Windows 8 Store Apps (37) - 契约: Settings Contract 作者:webabcd 介绍重新想象 Windows 8 Store Apps ...

  7. 重新想象 Windows 8 Store Apps (38) - 契约: Search Contract

    [源码下载] 重新想象 Windows 8 Store Apps (38) - 契约: Search Contract 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 ...

  8. 重新想象 Windows 8 Store Apps (39) - 契约: Share Contract

    [源码下载] 重新想象 Windows 8 Store Apps (39) - 契约: Share Contract 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之  ...

  9. 重新想象 Windows 8 Store Apps (40) - 剪切板: 复制/粘贴文本, html, 图片, 文件

    [源码下载] 重新想象 Windows 8 Store Apps (40) - 剪切板: 复制/粘贴文本, html, 图片, 文件 作者:webabcd 介绍重新想象 Windows 8 Store ...

随机推荐

  1. 【菜鸟看框架】——EF怎样自己主动生成实体

    引言 在上一篇博客中给大家介绍了一些关于EF框架的基本知识.让大家对实体架构算是有了一个入门的认识,当然知识 这一篇博客是不能非常清楚的理解实体架构的内涵的.我们须要在实践中自己去不断的研究和探索当中 ...

  2. IP Editor IP控件(对比一下封装IP控件)

    HWND hIpEdit; void __fastcall TForm2::FormCreate(TObject *Sender) { hIpEdit = CreateWindow(WC_IPADDR ...

  3. junit测试时,出现java.lang.IllegalStateException: Failed to load ApplicationContext

    课程设计要求进行junit测试,我是在已经做好的ssh项目上做的测试,测试类代码如下 package com.zhang.web.services; import static org.junit.A ...

  4. Ubuntu 问题解决汇总

    汇总一些ubuntu相关的问题 1.Ubuntu支持安装多媒体播放插件(新系统安装后必备) ubuntu-restricted-extras package allows users to insta ...

  5. Caché Monitor 2.03发布,Caché的SQL开发工具 - 开源中国社区

    Caché Monitor 2.03发布,Caché的SQL开发工具 - 开源中国社区 Caché Monitor 2.03发布,Caché的SQL开发工具

  6. ubuntu12.04安装深度音乐播放器和深度影音

    昨天折腾了一天,想要安装深度播放器和深度影音都未成功,老是出现依赖关系不满足这个错误.网上解决办法有非常多,可是都没能有效的解决这个问题.今天突然想起来之前换过软件源,是不是这个原因而导致了依赖关系不 ...

  7. 什么是Spring?Spring是什么?

    Spring概述: Spring是一个开源框架,是为了解决企业应用程序开发复杂性而开发的. 从简单性.可測试性和松耦合的角度而言,不论什么java应用都能够从Spring中受益. 简而言之,Sprin ...

  8. Replace - with an en dash character (–, –) ?

    这个安卓开发过程中eclipse的提示,新浪网友给出这个解决方法:http://blog.sina.com.cn/s/blog_5ea8670101015dgk.html  太笨了. 看看stacko ...

  9. Python数据结构-序列

    shopList=['apple','orange','pen'] print(shopList) print(]) print(]) print(:])) print(])) 运行结果: ['app ...

  10. Catch Up 朋友小聚 - 地道英语 - BBC Learning English BBC英语教学 - 爱思英语网

    Catch Up 朋友小聚 - 地道英语 - BBC Learning English BBC英语教学 - 爱思英语网 Catch Up 朋友小聚 分享到: 新浪微博 QQ空间 腾讯微博 微信 更多 ...