| 网站首页 | VB.Net实例分析 | .Net技术文摘 | 下载中心 | VB.Net书籍笔记 | .Net源码 | VBS脚本与组件调用 | Windows2008技术文摘 | 给我们留言 | 
最新公告:

  没有公告

您现在的位置: 乐博网 >> VB.Net实例分析 >> 加密压缩编程 >> 实例分析正文
最新推荐 更多内容
[图文]储存加密的数据库连接字符串到注册表的实例
储存加密的数据库连接字符串到注册表的实例
作者:obviex    来源:obviex的博客     更新时间:2009-10-14

储存加密的数据库连接字符串到注册表的实例

分别介绍了asp.net1.1和asp.net2.0模式下的使用方法

How To: Store an Encrypted Connection String in the Registry in ASP.NET 1.1

J.D. Meier, Alex Mackman, Michael Dunner, and Srinath Vasireddy
Microsoft Corporation

Published: November 2002

Last Revised: January 2006

Applies to:

  • .NET Framework 1.1

See the "patterns & practices Security Guidance for Applications Index" for links to additional security resources.

See the Landing Page for a starting point and complete overview of Building Secure ASP.NET Applications.

Summary: Applications may choose to store encrypted data such as connection strings and account credentials in the Windows registry. This How To shows you how to store and retrieve encrypted strings in the registry. (7 printed pages)

Contents

Notes
Summary of Steps Step 1. Store the Encrypted Data in the Registry
Step 2. Create an ASP.NET Web Application
Additional Resources

The registry represents one possible location for an application to store database connection strings. Although individual registry keys can be secured with Windows access control lists (ACLs), for added security you should store encrypted connection strings.

This How To describes how to store an encrypted database connection string in the registry and retrieve it from an ASP.NET Web application. It uses the generic encryption and decryption managed class library created in How To: Create an Encryption Library in .NET 1.1, which can be found in Reference section of this guide.

If you have not already created the encryption class library assembly, do so before continuing with the current How To.

For more information about other locations and ways of securely storing database connection strings, see Storing Database Connection Strings Securely in Chapter 12, "Data Access Security."

Notes

  • The connection string, initialization vector and key used for encryption will be stored in the registry as named values beneath the following registry key.
    Copy Code
    HKEY_LOCAL_MACHINE\Software\TestApplication
    
  • The initialization vector and key must be stored in order to allow the connection string to be decrypted.

Summary of Steps

This How To includes the following steps:

  • Step 1. Store the Encrypted Data in the Registry
  • Step 2. Create an ASP.NET Web Application

Step 1. Store the Encrypted Data in the Registry

This procedure creates a Windows application that will be used to encrypt a sample database string and store it in the registry.

To store the encrypted data in the registry

储存加密的数据库连接字符串到注册表

  1. Start Visual Studio .NET and create a new C# Windows project called EncryptionTestApp.
  2. Add an assembly reference to the Encryption.dll assembly.

    To create this assembly, you must perform the steps described in How To: Create an Encryption Library in .NET 1.1 in the Reference section of this guide.

  3. Add the following using statements to the top of Form1.cs beneath the existing using statements.
    Copy Code
    using Encryption;
    using System.Text;
    using Microsoft.Win32;
    
  4. Add the controls in Table 1 to Form1 and arrange them as illustrated in Figure 1.

    Table 1. EncryptionTestApp controls

    Control Text ID
    Label Connection String:  
    TextBox   txtConnectionString
    Label Key:  
    TextBox   txtKey
    Label Initialization Vector:  
    TextBox   txtInitializationVector
    Label Encrypted String  
    TextBox   txtEncryptedString
    Label Decrypted String  
    TextBox   txtDecryptedString
    Button Encrypt btnEncrypt
    Button Decrypt btnDecrypt
    Button Write Registry Data btnWriteRegistryData

    Aa302406.fh11sn01(en-us,MSDN.10).gif

    Figure 1. Encryption Test Harness dialog box

  5. Set the Text property of txtConnectionString to
    Copy Code
    "Server=local; database=pubs; uid=Bob; pwd=Password"
    
  6. Set the Text property of txtKey to
    Copy Code
    "0123456789012345"
    

    The key length is 16 bytes to suite the Triple DES encryption algorithm.

    Although the key used in this example is simple, ideally you should use complex keys. Use the RNGCryptoServiceProvider or PasswordDeriveBytes class for generating complex keys.

  7. Set the Text property of Form1 to
    Copy Code
    "Encryption Test Harness"
    
  8. Double-click the Encrypt button to create a button click event handler and add the following code to the event handler.
    Copy Code
    try
    {
      // Create the encryptor object, specifying 3DES as the
      // encryption algorithm
      Encryptor enc = new Encryptor(EncryptionAlgorithm.TripleDes);
      // Get the connection string as a byte array
      byte[] plainText = 
        Encoding.ASCII.GetBytes(txtConnectionString.Text);
      byte[] key = Encoding.ASCII.GetBytes(txtKey.Text);
    
      // Perform the encryption
      byte[] cipherText = enc.Encrypt(plainText, key);
      // Store the intialization vector, as this will be required
      // for decryption
      txtInitializationVector.Text = Encoding.ASCII.GetString(enc.IV);
    
      // Display the encrypted string
      txtEncryptedString.Text = Convert.ToBase64String(cipherText);
    }
    catch(Exception ex)
    {
      MessageBox.Show("Exception encrypting: " + ex.Message, 
                      "Encryption ");
    }
    
  9. Return to Form1 in Designer mode and double-click the Decrypt button to create a button click event handler.
  10. Add the following code to the Decrypt button event handler.
    Copy Code
    try
    {
      // Set up the Decryptor object
      Decryptor dec = new Decryptor(EncryptionAlgorithm.TripleDes);
    
      // Set the Initialization Vector
      dec.IV = Encoding.ASCII.GetBytes(txtInitializationVector.Text);
    
      byte[] key = Encoding.ASCII.GetBytes(txtKey.Text);
      // Perform the decryption
      byte[] plainText =  dec.Decrypt(Convert.FromBase64String(
                                      txtEncryptedString.Text),
                                      key);
    
      // Display the decrypted string.
      txtDecryptedString.Text = Encoding.ASCII.GetString(plainText);
    }
    catch(Exception ex)
    {
      MessageBox.Show("Exception decrypting. " + ex.Message, 
                      "Encryption Test Harness");
    }
    
  11. Return to Form1 in Designer mode and double-click the Write Registry Data button to create a button click event handler.
  12. Add the following code to the event handler.
    Copy Code
    // Create registry key and named values
    RegistryKey rk = Registry.LocalMachine.OpenSubKey("Software",true);
    rk = rk.CreateSubKey("TestApplication");
    
    // Write encrypted string, initialization vector and key to the 
      registry
    rk.SetValue("connectionString",txtEncryptedString.Text);
    rk.SetValue("initVector",
               Encoding.ASCII.GetBytes(txtInitializationVector.Text));
    rk.SetValue("key", Encoding.ASCII.GetBytes(
                                             txtKey.Text));
    MessageBox.Show("The data has been successfully written to the 
      registry");
    
  13. Run the application, and then click Encrypt.

    The encrypted connection string is displayed in the Encrypted String field.

  14. Click Decrypt.

    The original string is displayed in the Decrypted String field.

  15. Click Write Registry Data.
  16. In the message box, click OK.
  17. Run regedit.exe and view the contents of the following key.
    Copy Code
    HKLM\Software\TestApplication
    

    Confirm that encoded values are present for the connectionString, initVector and key named values.

  18. Close regedit and the test harness application.

Step 2. Create an ASP.NET Web Application

This procedure develops a simple ASP.NET Web application that will retrieve the encrypted connection string from the registry and decrypt it. By default, the ASP.NET process identity used by the Web application will not have access to the registry. Access will need to be explicitly granted.

To create an ASP.NET application

  1. Create a new Visual C# ASP.NET Web Application called EncryptionWebApp.
  2. Add an assembly reference to the Encryption.dll assembly.

    To create this assembly, you must perform the steps described in How To: Create an Encryption Library in .NET 1.1 in the Reference section of this guide.

  3. Open Webform1.aspx.cs and add the following using statements at the top of the file beneath the existing using statements.
    Copy Code
    using Encryption;
    using System.Text;
    using Microsoft.Win32;
    
  4. Add the controls listed in Table 2 to WebForm1.aspx.

    Table 2: WebForm1.aspx controls

    Control Text ID
    Label   lblEncryptedString
    Label   lblDecryptedString
    Button Get Connection String btnGetConnectionString
  5. Double-click the Get Connection String button to create a button click event handler.
  6. Add the following code to the event handler.
    Copy Code
    RegistryKey rk = Registry.LocalMachine.OpenSubKey(
                                    @"Software\TestApplication",false);
    lblEncryptedString.Text = (string)rk.GetValue("connectionString");
    
    string initVector = (string)rk.GetValue("initVector");
    string strKey = (string)rk.GetValue("key");
    
    Decryptor dec = new Decryptor(EncryptionAlgorithm.TripleDes );
    dec.IV = Convert.FromBase64String(initVector);
    
    // Decrypt the string
    byte[] plainText = dec.Decrypt(Convert.FromBase64String(
                                   lblEncryptedString.Text), 
                                   Convert.FromBase64String(strKey));
    
    lblDecryptedString.Text = Encoding.ASCII.GetString(plainText);
    
  7. On the Build menu, click Build Solution.
  8. Right-click Webform1.aspx in Solution Explorer, and then click View in Browser.
  9. Click Get Connection String.

    The encrypted and decrypted connection strings are displayed on the Web form.

  • 上一篇:

  • 下一篇:
  • 【字体: 】【打印此文】【关闭窗口
      相关文章:(只显示最新16条)
    VB.Net获取随机密码的实例
    VB.Net用Salt哈希数据的实例
    用DPAPI加密和解密数据的实例
    Salt加密数据的.Net实例
    Rijndael加密解密的实例
    AES加密的实例
    Rijndael加密的实例
    SHA256 Hash加密的实例
    VB.Net对XML元素进行加密解密的实例
    VB.Net文件CRC32算法的实例
    VB.Net文件SHA1算法的实例
    Blowfish加密算法的实例
    Rijndael类的实例
    TripleDES加解密的实例
    VB.Net实现des加密算法的实例
    VB.Net实现RSA加密的实例

    | 设为首页 | 加入收藏 | 联系站长 | | 友情链接 | 版权申明 |
    乐博网欢迎各种媒体转载我们的原创作品[转载请注明出处];我们鼓励更多VB.Net开发者一起加入研究与探讨;如发现文章访问错误、内容错误或版权疑问、内容有违相关法律(如涉及政治、色情、反动或散布虚假有害信息)等情况,请及时向我们举报,我们将及时纠正!
    联系邮箱:Shiny#vip.qq.com (#替换为@) QQ交流群: 40797788 [闽ICP备05014267号]