Enterprise Library 2.0 — Cryptography Application Block

來源:互聯網
上載者:User

前言:

    本文包括如下內容:
1、Cryptography Application Block 的簡單介紹(參考了內建的英文文檔)
2、配置Cryptography Application Block(本文以配置Symmetric Encryption Provider為例,Hash Provider 的配置基本相似)
3、怎樣對一個資料進行加密?
4、資料解密
5、如何得到資料的Hash值
6、根據資料Hash值來判斷資料是否變化

第一部分:Crytography Application Block 簡介

    Crytography Application Block 提供了兩種加密方法: Hash 和 Symmetric ,二者的區別是,Hash密碼編譯演算法是不可以解密的,而Symmetric既可加密又可以解密。當然它也支援自訂的加密方法,Enterprise Library 2.0提供了對密碼編譯演算法的修改和擴充功能。

    一、什麼時候需要使用Cryptography Application Block?
   當我們的應用程式需要用到Hash 或 Symmetric 加密時,我們可以考慮使用它,我們可以使用微軟提供的密碼編譯演算法,也可以自己定義需要的密碼編譯演算法。當我們的資料只需要對其進行加密,並且不會用到解密方法時,我們可以使用Hash Provider(比如說我們對密碼進行加密就可採用此種方法),當資料既需要加密又需要解密的時候,我們可以使用Symmetric Encryption Provider(比如我們在頁面間通過Url傳遞一些敏感參數時可以考慮使用此種方法對資料進行加密)。

   二、Crytography Application Block 給我們開發人員帶來了什麼好處?

1、它協助我們開發人員很輕鬆的解決應用程式中的加密問題。
2、它可以協助我們統一整個企業的應用程式的統一性。
3、Crytography Application Block是可擴充的,我們可以用自己寫的密碼編譯演算法來對應用程式進行加密。

第二部分:Crytography Application Block 配置

    首先我們開啟Enterprise Library Configuration,它存在與你的Enterprise Library安裝目錄下的bin目錄中。當然在此之前我們需要先建好我們的項目,並添加App.Config檔案,我後面的例子都是在VS2005的Test Project 中進行的。
    選擇 File --> Open Application ,如下:

此時選擇我們剛建的項目中的App.Config檔案,

然後,按右鍵 Application --> New --> Crytography Application Block,

因為我們要配置的是Symmetric Encryption ,所以接下來我們選擇Symmetric Provider並右擊,如下:

此時建立一個Symmetric Algorithm Provider ,並選擇一種密碼編譯演算法,如:

之後出現 Cryptographic Key Wizard 的對話方塊,如下:

我們選擇Create a new Key,這時候就出現了讓我們輸入類似註冊碼之類的對話方塊(這一處輸入的十六進位數我還沒搞懂有什麼作用),我們點Generate,如下:

然後點 Next,選擇我們建立的Key File的儲存路徑,如下:

再Next一下,這時讓我們選擇加密的模式,如下:

加密模式有兩種,User mode 和 Machine mode
使用Machine mode的情況:
1、當你的應用程式運行在專門的伺服器上,並且這台伺服器上沒有其他的應用程式;
2、你的伺服器上同時運行了多個應用程式,你希望這些應用程式能夠共用一些敏感的資訊。
使用User mode的情況:
    如果你的應用程式運行在多程式的環境下,但你不希望你的應用程式中的敏感性資料受到其他應用程式的影響或被其他應用程式訪問;在這種情況下,每個應用程式的資源(例如:檔案、資料庫等)之間都是相互獨立,互不影響的。
注意:如果你選擇了DPAPI密碼編譯演算法,然後再使用machine mode的話,那麼加密後的資料只在當前的機器上有效,所以你必須為每台機器產生一個加密的資料。

然後點 Finish ,這時可以修改我們的 Cryptography Application Block 的配置名.

然後點File-->Save All,這樣我們就完成了一個Symmetric Provider 的配置。此時我們的設定檔就會增加如下內容,當然這些內容我們也可以手工去添加。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="securityCryptographyConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.Configuration.CryptographySettings, Microsoft.Practices.EnterpriseLibrary.Security.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
  </configSections>
  <securityCryptographyConfiguration>
    <symmetricCryptoProviders>
      <add algorithmType="System.Security.Cryptography.DESCryptoServiceProvider, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        protectedKeyFilename="E:\研究中\Enterprise Library 2\Enterprise Library 2\key.key"
        protectedKeyProtectionScope="CurrentUser" type="Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.SymmetricAlgorithmProvider, Microsoft.Practices.EnterpriseLibrary.Security.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
        name="MyCryptographyProvider" />
    </symmetricCryptoProviders>
  </securityCryptographyConfiguration>
</configuration>

第三部分:使用Cryptography Application Block
   這一部分介紹了使用Cryptography Application Block對資料進行加密與解密等操作。
1、加密與解密操作

[TestMethod]
        public void UseCryptography()
        {
            //加密
            string name = Cryptographer.EncryptSymmetric("MyCryptographyProvider", "SHY520");

            //解密
            string rname = Cryptographer.DecryptSymmetric("MyCryptographyProvider", name);

            Assert.AreEqual(rname,"SHY520");
        }

2、得到資料的Hash值,前提是我們要配置一個Hash Provider(具體的配置方法可以參考前面介紹的Symmetric Provider的配置方法),然後用如下方法得到Hash值,但是要注意,Hash值不可以解密。

[TestMethod]
        public void GetHashValues()
        {
            byte[] valueToHash = (new UnicodeEncoding()).GetBytes("password");
            byte[] generatedHash = Cryptographer.CreateHash("hashProvider", valueToHash);

            // Clear the byte array memory.
            Array.Clear(valueToHash, 0, valueToHash.Length);

            Assert.AreEqual("password",generatedHash);
        }

當然,上面這個測試方法是肯定通過不了的。這裡只是說明如何取得資料的Hash值。

3、通過比較一個資料和它已經產生的一個Hash值,來判斷資料是否發生改變。

    [TestMethod]
        public void CompareHashValue()
        {
            byte[] ovalue = (new UnicodeEncoding()).GetBytes("SHY520");
            //建立ovalue的Hash值
            byte[] generatedHash = Cryptographer.CreateHash("hashProvider", ovalue);
            //比較資料和它的Hash值,如果資料沒有改變則返回true,改變了就返回false
            bool result = Cryptographer.CompareHash("hashProvider", ovalue, generatedHash);
            //改變原來資料的值,再進行比較
            ovalue = (new UnicodeEncoding()).GetBytes("SHY521");
            bool result1 = Cryptographer.CompareHash("hashProvider", ovalue, generatedHash);

            Assert.AreEqual(false,result1);
            Assert.AreEqual(true, result);
        }

     Cryptography Application Block 中包含的內容也不是很多,但是它其中包含了很多常見的密碼編譯演算法,足以滿足我們項目中的要求,今天我們對Cryptography Application Block的介紹就到此為止,希望對初學者有所協助。

上一篇: Enterprise Library 2.0 -- Caching Application Block

補充:

加密Config檔案:
首先,添加對System.Configuration.dll的引用
然後添加下面的代碼:

Configuration config = null;
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection section = config.ConnectionStrings;

if (section.SectionInformation.IsProtected == false && section.ElementInformation.IsLocked == false)
{
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");

section.SectionInformation.ForceSave = true;

config.Save(ConfigurationSaveMode.Full);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.