技术开发 频道

Enterprise Library 2.0:加密应用程序块(一)

【IT168技术文档】

练习1:加解密字符串
通过本练习将学习通过加密来保护信息,在这里创建一个类似于IM的聊天应用程序,加密通信过程中的信息。

第一步
BugSmak.sln项目,默认的安装路径应该为C:\Program Files\Microsoft Enterprise Library January 2006\labs\cs\Cryptography\exercises\ex01\begin,并编译。

第二步 回顾应用程序

1在解决方案管理器选中Chat.cs文件,选择View | Code菜单命令。Chat窗体用来接收和发送信息,上面的灰色TextBox用来显示聊天信息,底部白色的TextBox用来发送新的消息。

2选择Debug | Start Without Debugging命令运行应用程序,聊天窗口将被打开,分别叫做SamToby,消息可以在这两个窗口之间传递,在Toby的消息文本框中输入一些字符,并单击Send按钮,在Sam窗体中作重复做一次。可以看到交流信息显示在了聊天窗体中。还有一个控制台应用程序显示,它用来监视聊天的过程,所有的消息都将在这里显示。


3关闭所有窗体并关闭应用程序。

第三步 添加加解密

1.选择Project | Add Reference单命令,添加对如下程序集的引用,它默认的安装位置应该在C:\Program Files\Microsoft Enterprise Library January 2006\bin目录下。Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.dll
2.打开Chat.cs文件,添加如下命名空间:

using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;

3Chat类中添加如下代码:

public partial class Chat : Form{ // TODO: Configuration symmetric algorithm provider name private const string symmProvider = "ChatProvider"; // }

 

4.修改SendMessage方法,使用Cryptographer加密消息。

private void SendMessage(string message){ // TODO: Encrypt message string encrypted = Cryptographer.EncryptSymmetric(symmProvider, message); // Fire SendingMessage Event if (this.SendingMessage != null) this.SendingMessage(new MessageEventArgs(this._name, encrypted)); }

5.修改MessageReceived方法,使用Cryptographer解密消息。

private void MessageReceived(MessageEventArgs args){ string message = args.Message; // TODO: Decrypt message string plainText = Cryptographer.DecryptSymmetric(symmProvider, message); this.txtMessages.AppendText( args.Sender + " says: " + plainText + Environment.NewLine); }

 第四步 企业库配置工具
1
.在项目CustomerManagement中添加一个应用程序配置文件App.config,单击CustomerManagement项目,选择Project| Add New Item…菜单命令,在弹出的对话框中选择Application configuration file保留名称为App.config

2使用Enterprise Library配置工具配置应用程序,可以通过开始菜单打开该配置工具,选择所有程序| Microsoft patterns and practices | Enterprise Library | Enterprise Library Configuration并打开App.config文件。或者直接在Visual Studio中使用该工具打开配置文件。
3.在解决方案管理器中选中App.config文件,在View菜单或者在右键菜单中选择Open With…,将打开OpenWith对话框,单击Add按钮。


4.Add Program对话框中,设置Program name指向EntLibConfig.exe文件,默认的路径为C:\Program Files\Microsoft Enterprise Library January 2006\bin设置Friendly nameEnterprise Library Configuration,单击OK按钮。

Visual Studio会把配置文件(App.config)作为一个命令行参数传递给EntLibConfig.exe
5.在Open With对话框中,选中Enterprise Library Configuration并单击OK按钮。

 

 

 

 

 

 

 

 

 

0
相关文章