天天看點

微軟企業庫5.0學習-Security.Cryptography子產品

一、微軟企業庫加密應用子產品提供了兩種加密:

1、Hash providers :離散加密,即資料加密後無法解密

2、Symmetric Cryptography Providers:密鑰(對稱)加密法,即資料加密後可解密還原

注:企業庫不支援非對稱加密方式。

二、使用說明

1.使用靜态類Cryptographer

using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;

//Hash加密
string encrypted = Cryptographer.CreateHash("MD5CryptoServiceProvider", "plainText");
//對稱加密
string encrypted = Cryptographer.EncryptSymmetric("RC2CryptoServiceProvider", "plainText");      
2.使用企業庫容器EnterpriseLibraryContainer擷取CryptographyManager抽象類實作執行個體      
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;      
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;      
using Microsoft.Practices.ServiceLocation;      
//Hash加密
CryptographyManager crypt = EnterpriseLibraryContainer.Current.GetInstance<CryptographyManager>();
string encrypted = crypt.CreateHash("MD5CryptoServiceProvider", "plainText");      

三、設計視圖

四、實作IHashProvider或ISymmetricCryptoProvider接口的自定義加、解密方法

參考企業庫幫助手冊 加密子產品部分的Extending and Modifying the Cryptography Application Block節

注意:

1.須增加類屬性[Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationElementType(typeof(CustomHashProviderData))],配置工具方可識别自定義加解密類

2.必須存在一帶參System.Collections.Specialized.NameValueCollection attributes的構造函數,參數可從配置檔案中擷取指定的配置屬性,如下

public MyHashProvider(NameValueCollection attributes)

{

}

參考MSDN The Cryptography Application Block