Microsoft enterprise database 5.0 learning path-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.

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 entlibstudy. helper
{
[Configurationelementtype (typeof (customsymmetriccryptoproviderdata)]
Public class custom‑riccryptography: isy‑riccryptoprovider
{
Private string encryptkey = "";
Public customricriccryptography (namevaluecollection attributes)
{
// Obtain the key from the configuration file. If the key does not exist, 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. utf8.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 ();}

Source code download: 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. As Microsoft enterprise database 5.0 is a learning path, this series is intended to introduce the modules of the enterprise database in the form of a small project, so the source code will be updated according to the updates in the series of articles, therefore, 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

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.