Enterprise Library 2.0 Hands On Lab 翻譯(15):加密應用程序塊(二)
練習2: 使用哈希加密密碼
在本練習中將使用哈希加密密碼并存儲在XML文件中。
第一步
打BugSmak.sln項目,默認的安裝路徑應該為C:\Program Files\Microsoft Enterprise Library January 2006\labs\cs\Cryptography\exercises\ex02\begin,并編譯。
第二步 回顧應用程序
1.選擇Debug | Start Without Debugging菜單命令運行應用程序。
2.應用程序允許在一個XML文件中管理用戶名和密碼。添加一個新用戶Elmo,單擊New User按鈕,輸入用戶名Elmo,保留默認的密碼P@ssw0rd,并單擊OK按鈕。

3.單擊Save按鈕保存所作的改變到UserStore.config文件。
4.關閉應用程序。
5.在解決方案管理器中,打開UserStore.config文件,可以看到密碼是以明文的形式存在。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="userStore"
type="UserStore.Configuration.UserSettings, UserStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</configSections>
<userStore>
<users>
<add name="Elmo" password="P@ssw0rd" />
<add name="Zoe" password="P@ssw0rd" />
</users>
</userStore>
</configuration>
第三步 配置使用哈希加密
1.在解決方案管理器中選擇App.config文件,并選擇View | Open With…菜單命令,選擇Enterprise Library Configuration并單擊OK按鈕。
2.應用程序已經定義了兩個Configuration Sources,應用程序使用Enterprise Library的包裝類來管理UserStore.config的位置和內容。

3.在應用程序上單擊右鍵并選擇New | Cryptography Application Block菜單命令。

4.選擇Cryptography Application Block | Hash Providers節點,并單擊Action | New | HashAlgorithm Provider菜單命令。

5.Type Selector對話框將會顯示出來,選擇SHA1Managed并單擊OK按鈕。

6.選擇Cryptography Application Block | Hash Providers | SHA1Managed節點,并設置如下屬性。
Name = PasswordHasher
SaltEnabled = True

7.保存所有的配置。
第四步 使用Hash Provider
1.選擇項目UserStore,選擇Project | Add Reference …菜單命令,并添加如下程序集,它默認的安裝位置是C:\Program Files\Microsoft Enterprise Library January 2006\bin。
Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.dll
2.打開文件Security | HashHelper.cs,添加如下命名空間。
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;3.添加如下代碼到HashHelper類中。
class HashHelper
{
private HashHelper() { }
// TODO: Hash provider name must match app.config
private const string hashProvider = "PasswordHasher";



}4.把CreateHash方法修改為如下代碼。
public static string CreateHash(string plainText)
{
string hash = null;
// TODO: Hash the plain text
hash = Cryptographer.CreateHash(hashProvider, plainText);
return hash;
}5.選擇Debug | Start Without Debugging運行應用程序。
6.重新設置用戶Elmo和Zoe的密碼,選中用戶后,單擊Reset Password按鈕。

這樣將會用哈希密碼替換在UserStore.config中的明文密碼。
7.單擊保存按鈕保存所作的修改。
8.嘗試修改用戶Elmo的密碼,它將會去驗證已經存在的密碼。單擊Change Password按鈕,舊密碼為P@ssw0rd,隨便輸入一個新密碼,將會發現原來的密阿曼無法通過驗證,對于這個問題稍后將會解釋。
9.關閉應用程序。
10.打開UserStore.config文件,可以看到密碼已經不再是明文,而是加密的。
注意哈希加密不用于其他的情況,就算是兩個完全相同的密碼,由于“鹽”不同,加密后是完全不同的,所以不能簡單地用把明文哈希后和已經存在的哈希字符串進行比較,這就是為什么剛才驗證無法通過的原因。
11.在文件Security | HashHelper.cs中修改CompareHash方法的代碼如下。
public static bool CompareHash(string plainText, string hashedText)
{
bool compare = false;
// TODO: Compare plain text with hash
compare = Cryptographer.CompareHash(hashProvider, plainText, hashedText);
return compare;
}12.運行應用程序。
13.再次修改用戶的密碼,現在就可以修改成功了。
更多Enterprise Library的文章請參考《Enterprise Library系列文章》
Worktile,新一代簡單好用、體驗極致的團隊協同、項目管理工具,讓你和你的團隊隨時隨地一起工作。完全免費,現在就去了解一下吧。
https://worktile.com


浙公網安備 33010602011771號