[Entlib] how to learn from Microsoft enterprise database 5.0-Step 7: Simple Analysis of the cryptographer encryption module, custom encryption interfaces, and usage-Part 2

Source: Internet
Author: User

In the previous article, I introduced some important classes of the enterprise database cryptographer module, and introduced the extended interfaces provided by the enterprise database cryptographer module. Today I will perform extended development based on these interfaces, implements two encryption and decryption methods (discrete encryption and symmetric encryption) to implement the self-interface ihashprovider and interface isypolicriccryptoprovider respectively.

 

First, let's take a look at the discrete encryption-customhashcryptography.CodeAs follows::

Using system; using system. collections. generic; // The namespace of the namevaluecollection that accepts parameters in the constructor. collections. specialized; using system. LINQ; using system. text; using system. security. cryptography; using Microsoft. practices. enterpriselibrary. common. configuration; // used to bind using Microsoft. practices. enterpriselibrary. security. cryptography; using Microsoft. practices. enterpriselibrary. security. cryptograph Y. configuration; namespace entlibstudy. helper {[configurationelementtype (typeof (customhashproviderdata)] public class customhashcryptography: ihashprovider {// <summary> // constructor, which cannot be omitted here, otherwise, an exception may occur. // </Summary> // <Param name = "attributes"> parameters configured in the configuration file </param> Public mhmhashcryptography (namevaluecollection attributes) {}/// <summary> // compare whether the data and encrypted data are equal // </Summary> /// <Param name = "plaintex T "> unencrypted data </param> /// <Param name =" hashedtext "> encrypted data </param> /// <returns> equal </returns> public bool comparehash (byte [] plaintext, byte [] hashedtext) {var tmphashtext = createhash (plaintext); If (tmphashtext = NULL | hashedtext = NULL) return false; If (tmphashtext. length! = Hashedtext. Length) return false; For (INT I = 0; I <tmphashtext. length; I ++) {If (tmphashtext [I]! = Hashedtext [I]) return false;} return true ;} /// <summary> /// create encryption /// </Summary> /// <Param name = "plaintext"> data to be encrypted </param> /// <returns> encrypted data </returns> Public byte [] createhash (byte [] plaintext) {md5cryptoserviceprovider MD5 = new md5cryptoserviceprovider (); Return md5.computehash (plaintext );}}}

This code is mainly used to implement discrete encryption, but there are several points to note:

1. On the basis of implementing the ihashprovider interface, to enable this custom encryption, you can add a feature for the class to be called in the configuration tool of the enterprise database: [configurationelementtype (typeof (mhmhashproviderdata)], the namespace of this feature is:Using Microsoft. Practices. enterpriselibrary. Common. configuration ;.

2. This custom encryption must contain a constructor. The parameter type is namevaluecollection. This parameter obtains the specified Configuration Attribute from the configuration file. For details, see:

Note: This namevaluecollection type must reference the namespace: using system. Collections. Specialized;

Without this constructor, an exception is thrown:

Type does not provide a constructor taking a single parameter type of namevaluecollection

3. The methods comparehash and createhash, receive and return are byte arrays.

 

Next, let's take a look at the symmetric encryption customsymmetriccryptography. The specific code is as follows:

Using system; using system. collections. generic; using system. collections. specialized; using system. LINQ; using system. text; using system. security. cryptography; using system. io; using Microsoft. practices. enterpriselibrary. common. configuration; using Microsoft. practices. enterpriselibrary. security. cryptography; using Microsoft. practices. enterpriselibrary. security. cryptography. configuration; namespace entlibstud Y. helper {[configurationelementtype (typeof (types)] public class custom‑riccryptography: encryption {private string encryptkey = ""; Public custom‑riccryptography (namevaluecollection attributes) {// obtain the key from the configuration file, if not, specify the default key encryptkey = string. isnullorempty (attributes ["key"])? "Audio-yo": attributes ["key"];} // default key vector Private Static byte [] keys = {0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef }; /// <summary> /// encryption /// </Summary> /// <Param name = "ciphertext"> data to be encrypted </param> /// <returns> encrypted data </returns> Public byte [] decrypt (byte [] ciphertext) {If (encryptkey. length> 8) {encryptkey = encryptkey. substring (0, 7);} encryptkey = encryptkey. padright (8, ''); byte [] rgbkey = encoding. UTF-8 8.getbytes (encryptkey); byte [] rgbiv = keys; byte [] inputbytearray = ciphertext; descryptoserviceprovider dcsp = new descryptoserviceprovider (); memorystream mstream = new memorystream (); cryptostream cstream = new cryptostream (mstream, dcsp. createdecryptor (rgbkey, rgbiv), cryptostreammode. write); cstream. write (inputbytearray, 0, inputbytearray. length); cstream. flushfinalblock (); Return mstream. toarray ();} /// <summary> /// decrypt /// </Summary> /// <Param name = "plaintext"> encrypt data </param> /// <returns> decrypted data </returns> Public byte [] encrypt (byte [] plaintext) {If (encryptkey. length> 8) {encryptkey = encryptkey. substring (0, 7);} encryptkey = encryptkey. padright (8, ''); byte [] rgbkey = encoding. utf8.getbytes (encryptkey. substring (0, 8); byte [] rgbiv = keys; byte [] inputbytearray = plaintext; descryptoserviceprovider dcsp = new descryptoserviceprovider (); memorystream mstream = new memorystream (); cryptostream cstream = new cryptostream (mstream, dcsp. createencryptor (rgbkey, rgbiv), cryptostreammode. write); cstream. write (inputbytearray, 0, inputbytearray. length); cstream. flushfinalblock (); Return mstream. toarray ();}}}

The attention of symmetric encryption is basically the same as that of discrete encryption. However, I have introduced an encryption key, which is obtained from the configuration file.

 

Third: Apply the custom interface in the project

Two encryption methods have been extended above. Now we need to use these two encryption methods in the actual project. First, open the configuration tool of the Enterprise Library and add the cryptographer module, then, add the two encryption methods defined earlier under hash providers and isypolicric cryptograhpy providers.

Note: The added custom encryption method must be placed in the root directory of the project. If it is placed in a folder under the project, such as helper \ extension, the custom encryption method cannot be found in the configuration file of the enterprise database. For details, see:

After adding the configuration, you can see the following configuration information in Web. config:

<Securitycryptographyconfiguration>  

After the configuration, I added several encryption and decryption methods in the Helper. utils class for the presentation layer call (Obtains encrypted data based on the Instance name and data to be encrypted.), The Code is as follows:

/// <Summary> /// encrypt according to the configuration /// </Summary> /// <Param name = "instance"> Configure Instance name </param> // /<Param name = "encryptstring"> string to be encrypted </param> // <returns> encrypted string </returns> Public static string encode (string instance, string encryptstring) {return cryptographer. encryptsymmetric (instance, encryptstring );} /// <summary> /// decrypt according to the configuration /// </Summary> /// <Param name = "instance"> Configure Instance name </param> // /<Param name = "decryptstring"> string to be decrypted </param> // <returns> decrypted string </returns> Public static string decode (string instance, string decryptstring) {return cryptographer. decryptpolicric (instance, decryptstring );} /// <summary> /// perform discrete encryption based on the configuration /// </Summary> /// <Param name = "instance"> Configure Instance name </param>/ // <Param name = "plaintstring"> string to be encrypted </param> // <returns> decrypted string </returns> Public static string createhash (string instance, string plaintstring) {return cryptographer. createhash (instance, plaintstring );} /// <summary> /// compare whether discrete values are equal /// </Summary> /// <Param name = "instance"> Configure Instance name </param>/ // <Param name = "plaintstring"> unencrypted string </param> /// <Param name = "hashedstring"> encrypted string </param> /// <returns> equal </returns> Public static bool comparehash (string instance, string plaintstring, string hashedstring) {return cryptographer. comparehash (instance, plaintstring, hashedstring );}

The next step is the main project application. In the previous Code, for example, I saved the password of the trainee to the database in plain text. This shows that it is not safe, now I want to replace this code by calling utils. password for encrypted input using the createhash method:

 
/// <Summary> /// obtain the verified student object /// </Summary> /// <Param name = "student"> Student object </param>/ // <returns> whether the verification is successful </returns> private bool getvalidatedstudent (ref model. student) {If (student = NULL) {student = new model. student ();} student. classid = convert. toint32 (ddlclass. selectedvalue); student. SID = txtsid. text. trim (); student. password = helper. utils. createhash ("customhashcryptography", txtpwd. text. trim (); student. name = txtname. text. trim (); student. sex = convert. toint32 (rblsex. selectedvalue); student. birthday = datetime. parse (txtbirthday. text. trim (); return student. isvalid ();}

 

The above is the main content of this article. This article mainly introduces:

1. How to extend the encryption method through the interface provided by the enterprise database cryptographer module, as well as issues needing attention during expansion

2. Use the extended encryption method in the project.

The content of this article is relatively simple. If you find any problems, please point out. Thank you!

 

Source codeDownload: Click here to download

 

Note:

1. The MSSQL database is in the database directory (you need to attach the database yourself), and The SQLite database is in the app_data directory of the web directory. Because of the project size, the bin directory of each project has been deleted, if a project cannot be generated, add the DLL of the relevant enterprise library.

2. Since Microsoft enterprise database 5.0 is the path to learning this series, I am going to introduce the modules of the enterprise database in the form of a small project, so the source code will be based on the seriesArticleSo the source code cannot be the same as the Code posted in the article.

3. The project development environment is vs2010 + sql2005.

4. Administrator Account: Admin

Password: Admin

 

Index of a series of articles on the learning path of Microsoft enterprise database 5.0:

Step 1: getting started

Step 2: Use the vs2010 + data access module to create a multi-database project

Step 3: Add exception handling to the project (record to the database using custom extension)

Step 4: Use the cache to improve the website's performance (entlib caching)

Step 5: Introduce the entlib. validation module information, the implementation level of the validators, and the use of various built-in validators-Part 1

Step 5: Introduce the entlib. validation module information, the implementation level of the validators, and the use of various built-in validators-Part 1

Step 5: Introduce the entlib. validation module information, the implementation level of the validators, and the use of various built-in validators-Part 2

Step 6: Use the validation module for server-side data verification

Step 7: Simple Analysis of the cryptographer encryption module, custom encryption interfaces, and usage-Part 1

Step 7: Simple Analysis of the cryptographer encryption module, custom encryption interfaces, and usage-Part 2

Step 8. Use the configuration setting module and other methods to classify and manage enterprise database configuration information

Step 9: Use the policyinjection module for AOP-PART1-basic usage

Step 9: Use the policyinjection module for AOP-PART2-custom matching rule

Step 9: Use the policyinjection module for AOP-PART3 -- Introduction to built-in call Handler

Step 9: Use the policyinjection module for AOP-PART4 -- create a custom call handler to achieve user operation Logging

Step 10: Use unity to decouple your system-Part1-Why use unity?

Step 10: Use unity to decouple your system-Part2-learn how to use Unity (1)

Step 10. Use unity to decouple your system-Part2-learn how to use Unity (2)

Step 10: Use unity to decouple your system-Part2-learn how to use Unity (3)

Step 10: Use unity to decouple your system-Part3-dependency Injection

Step 10: Use unity to decouple your system-part4 -- unity & piab

Extended learning:

Extended learning and dependency injection in libraries (rebuilding Microsoft Enterprise Library) [go]

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.