Cryptography Application Block

1. 功能简介

2. 如何配置和使用?

3. 设计实现及如何拓展?

4. 代码下载


1. 功能简介

Cryptography Application Block 主要实现了两个算法:Encryption algorithms和Hashing algorithms,其中Encryption algorithms就是我们通常意义上的加密算法,Hashing算法提供的是这样一种场景:用户提供一个带价密的文本,通过hash算法生成一个hash值,然后检查该hash值是否出自某个字符串(Checking whether a hash matches some text)。同样该block提供了自定义provider的功能。


2. 如何进行配置和简单使用?

2.1 新建一个c# console application,添加配置文件App.config,添加程序集引用如下图:

Cryptography Application Block

打开EntLibConfig.exe,打开上面的app.config。添加加密的application block,开始配置:

Cryptography Application Block

添加一个hash provider。

Cryptography Application Block

Cryptography Application Block

添加加密算法。

Cryptography Application Block

Cryptography Application Block

Cryptography Application Block

Cryptography Application Block

Cryptography Application Block

注意下面选择Machine Mode(The LocalMachine value means that that any code running on the machine has access to the protected key)。

Cryptography Application Block

配置加密程序块的默认hash和加密程序的provider:

Cryptography Application Block

Cryptography Application Block

配置完成,下面是一个简单的使用示例:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography; using Microsoft.Practices; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; namespace CryptographyBlockTest { class Program { static void Main(string[] args) { CryptographyManager crypto = EnterpriseLibraryContainer.Current.GetInstance<CryptographyManager>(); string encrypted = crypto.EncryptSymmetric("CryptoProvider", "test"); Console.WriteLine(encrypted); string decrypted = crypto.DecryptSymmetric("CryptoProvider", encrypted); Console.WriteLine(decrypted); HashTest(); Console.ReadKey(); } public static void HashTest() { CryptographyManager crypto = EnterpriseLibraryContainer.Current.GetInstance<CryptographyManager>(); byte[] valueToHash = (new UnicodeEncoding()).GetBytes("password"); byte[] generatedHash = crypto.CreateHash("MD5Cng", valueToHash); // generatedHash contains a hash value for a previously hashed string. byte[] stringToCompare = (new UnicodeEncoding()).GetBytes("password"); bool comparisonSucceeded = crypto.CompareHash("MD5Cng", stringToCompare, generatedHash); Console.WriteLine(comparisonSucceeded); // true } } }


3. 设计实现及如何拓展?

Cryptography Application Block


4. 代码下载

下载


本博客均是本人在学习过程中的总结,其中难免存在不足之处,欢迎指正。