Simplified encryption in Microsoft. NET

Source: Internet
Author: User
Tags arrays base64 character set final generator hash implement visual studio
Encryption applies To:
Microsoft®.net
Safety
Microsoft®visual basic®.net
C#

Summary: Learn how to use the encryption capabilities of the. NET Framework to create wrappers that are similar to those described in this article to protect your data.

Download the Cryptosamplecssample.msi and Cryptosamplevbsample.msi code examples associated with this article. (Note that in the sample file, the programmer's comment is in English, which is translated into Chinese for easy Reader's understanding.) )

Directory
Introduction to Hashing
To create a sample hash item
Add "salt" value to hash column
Summary

Do you want to save some confidential information on your computer? If so, this article will introduce you to how to encrypt! Encryption is the encoding of meaningful characters into meaningless characters so that people who should not be able to access the data cannot read them. Encryption technology has existed for many years, even before the computer was born. With the advent of computers, the application of encryption technology in the computer field can generate almost unbreakable code. Microsoft has developed and distributed the cryptographic APIs in Windows 95. With Microsoft. NET, newly created classes can package these complex algorithms into very easy to use properties and methods.

Introduction to Hashing
If you just don't want someone to steal your password, you can create a hash of the password data. Hashing is a one-way algorithm that, once the data is converted, will no longer be able to obtain its original value. Most developers use a database to store passwords. However, people who look up user data in the database can also see these passwords. However, you can use the hashing algorithm to encrypt the password and then store it in the database. Once the user has entered a password, you can use the hashing algorithm again to decrypt it and compare it to the hash stored in the database. One of the drawbacks of hashing is that even if the original data only has one small change, the hash of the data will change very much. The two words pork and porky are very similar, but the result of encrypting with the hashing algorithm is very much the same. You may not see any similarities between the two.

. NET developers can use a variety of hashing algorithm classes. The most commonly used are SHA1 and MD5. Let's take a look at how to generate a hash of ordinary strings such as "Paul" so that no one can recognize it.

Using SHA1 to generate a hash
We create a new routine and then use it to generate a hash of the string "Paul". Open a new Windows application in Visual studio®.net and place a command button on the form. When the Click event occurs on the command button, a method named Hashtext () is invoked. You can add the following code to the form to see the actual effect of this hashing algorithm. Before you write the following code, you need to import the namespace System.Security.Cryptography.

Private Sub Hashtext (ByVal Texttohash as String)
Dim SHA1 as SHA1CryptoServiceProvider
Dim Bytvalue () as Byte
Dim Bythash () as Byte

' Create a new cryptographic service provider object
SHA1 = New SHA1CryptoServiceProvider

' Converts the original string into a byte array
Bytvalue = _
System.Text.Encoding.UTF8.GetBytes (Texttohash)

' Computes a hash and returns an array of bytes
Bythash = Sha1.computehash (bytvalue)

SHA1. Clear ()

' Returns the hash value of the BASE64 encoded string
Debug.WriteLine (convert.tobase64string (Bythash))
End Sub
You can pass a different string value to call the routine to see how the hash value changes. For example, if you pass the string "Paul" to the routine, the Debug window displays the following text:

w2h6uygmjt/nq5zqihcbteaxwv8=
Now change the input value in this procedure to "Pauly". You will see the following output:

proywxj0znmpgf5sbb18+7gsasm=
As you can see, a small change in the input string produces a completely different combination of characters. This is why hashing algorithms work, it makes it hard to find the rules of the input string, and it's hard to figure out what the string looks like from the encrypted character.

Hash can also be generated using MD5
Once you understand how a hash class is used, you'll basically understand all of the hash classes. The following method is used for MD5 hashing algorithms. Note that the code is exactly the same except for the CryptoServiceProvider class.

Private Sub HashTextMD5 (ByVal Texttohash as String)
Dim MD5 as MD5CryptoServiceProvider
Dim Bytvalue () as Byte
Dim Bythash () as Byte

' Create a new cryptographic service provider object
MD5 = New MD5CryptoServiceProvider

' Converts the original string into a byte array
Bytvalue = System.Text.Encoding. _
UTF8. GetBytes (Texttohash)

' Computes a hash and returns an array of bytes
Bythash = Md5.computehash (bytvalue)

MD5. Clear ()

' Returns the hash value of the BASE64 encoded string
Debug.WriteLine (convert.tobase64string (Bythash))
End Sub
After you enter "Paul", the output of the MD5 hash algorithm looks like this:

nvwbshh1mknctpiosyqytq==
Again, the encrypted string looks a far cry from the original input. These hashing algorithms are useful for creating passwords that have no meaning, and make it difficult for hackers to guess those passwords. The hashing algorithm is used because the password can be encrypted and stored in the database using this algorithm. Then, when the user enters a real password, you decrypt the password and send it over the network to the database to compare it to the password in the database. Keep in mind that hashing is a one-way operation. The original password cannot be recovered after it is encrypted with the hash algorithm.

How to select an algorithm
Both of the hashing algorithms described in this paper perform the same operation. The difference is only in generating the hash key size and the algorithm used. The larger the key used, the more secure the encryption. For example, the encryption key used by MD5 is larger than the key used by SHA1, so the MD5 hash is harder to crack.

Another point to consider for hashing algorithms is whether there is a possibility of conflict from a practical or theoretical point of view. Conflicts are not what we want, because two different words may produce the same hash. SHA1, for example, has no possibility of conflict in practice or theory. MD5 theoretically has the possibility of conflict, but in practice there is no possibility of conflict. Therefore, the choice of which algorithm ultimately depends on the level of security you need.

To create a sample hash item
This article contains two sample hash items to explain in more general terms how to encrypt arbitrary strings using different hashing algorithms. The names of the two sample projects are CryptoSampleVB.sln and CryptoSampleCS.sln respectively. The former is the Visual Basic. NET solution, which is the C # solution. All two solutions include a form similar to Figure 1 that allows you to enter the original string to be encrypted with the hash algorithm, as well as an option button to select the hashing algorithm and a text box that displays the hash result.



Figure 1: Create a universal hash screen to try two hashing algorithms.

When you click the hash (hash) button on this screen, the button's Click event procedure is run. This event procedure invokes a routine named HashString ().

' Visual Basic. NET
Private Sub Btnhash_click (ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles Btnhash.click
Txthashed.text = hashstring (Txtoriginal.text)
End Sub
C#
private void Cmdhash_click (object sender,
System.EventArgs e)
{
Txthashed.text = hashstring (Txtoriginal.text);
}
The HashString () method accepts the input value and invokes the Sethash () method. This method determines which cryptographic service provider is used to create an instance of the method and returns the method, based on the settings of the option buttons on the form. A member variable of the HashAlgorithm type named Mhash will be created for the form. The HashAlgorithm type is the base class that creates all the hash cryptographic service providers.

' Visual Basic. NET
Private Mhash as HashAlgorithm

C#
Private HashAlgorithm Mhash;
The Sethash () method looks like this:

' Visual Basic. NET
Private Function Sethash () as HashAlgorithm
If optsha1.checked Then
return New SHA1CryptoServiceProvider
Else
If optmd5.checked Then
return New MD5CryptoServiceProvider
End If
End If
End Function

C#
Private HashAlgorithm Sethash ()
{
if (this.optSHA1.Checked)
return new SHA1CryptoServiceProvider ();
Else
return new MD5CryptoServiceProvider ();
}
Depending on the option button that you select on the form, this method creates and returns a different HashAlgorithm type. The HashString () method performs the actual data encryption on the form:

' Visual Basic. NET
Private Function hashstring (ByVal Value as String) _
As String
Dim Bytvalue () as Byte
Dim Bythash () as Byte

' Create a new cryptographic service provider object
Mhash = Sethash ()

' Converts the original string into a byte array
Bytvalue = System.Text.Encoding.UTF8.GetBytes (Value)

' Computes a hash and returns an array of bytes
Bythash = Mhash.computehash (bytvalue)

Mhash. Clear ()

' Returns the hash value of the BASE64 encoded string
Return convert.tobase64string (Bythash)
End Function


C#
private string HashString (String Value)
{
Mhash = Sethash ();

Converts the original string into a byte array
byte[] Bytvalue = System.Text.Encoding.UTF8.GetBytes (Value);

Computes a hash and returns an array of bytes
byte[] Bythash = Mhash.computehash (Bytvalue);

Mhash. Clear ();

BASE64 encoded string that returns a hash value
Return convert.tobase64string (Bythash);
}
In the HashString method, we created two byte arrays. The first array is used to hold the user's raw string input. We use the System.Text.Encoding.UTF8.GetBytes () method to convert the string into a byte array. After converting the original string into a byte array, the hash value of the string is now computed using the ComputeHash () method of the service provider. This method takes a byte array as input, and then returns an array of bytes in the encrypted format of the string.

Note: It is a good practice to clear the hash variable after completion. So, after you see the hash of the string, we call the clear method.
Now we've got the encrypted byte array, which is exactly the array to return from the method. Because we're going to treat both the original value and the encrypted value as a string data type instead of a byte array, we're going to return the encrypted byte by using the Convert.tobase64string method. This method is responsible for converting a byte array into a BASE64-encoded string. The use of BASE64 encoding is important because it is possible to push this string onto a Web page or store it in a database. Some of the higher-order ASCII characters in the encrypted string will not be displayed or stored correctly without conversion.

Add some "salt" values to the hash
One of the problems exposed by the hashing algorithm so far is that if two users happen to use the same password, the hash value will be exactly the same. If the hacker sees the form where you store the password, you'll find patterns and understand that you're likely to use common words, and hackers will start a dictionary attack to determine those passwords. To make sure that the hash values for any two user passwords are different, one way is to add a unique value to each user's password before encrypting the password. This unique value is called the "salt" value. When you do this, you need to ensure that the salt value you use is stored as part of the user record. If you use a table to store user IDs and passwords, I recommend that you use a different table to store the salt values. In this way, even if the database leaks, the salt value can provide you with a layer of additional security protection.

There are several ways to add salt values to a user's password. The easiest way to do this is to extract some information from the user (such as last name, first name, e-mail address, or employee ID) and add it to the user's password before encrypting it. The disadvantage of this approach is that because you need to store the salt value, if the hacker finds that value, it will know everything you do. Of course, hackers need to spend extra time cracking down on salt, but that's a cinch for hackers.

Another approach is to create a random numeric string using the. NET Framework class RNGCryptoServiceProvider. RNG represents a random number generator. This class can create a random byte array of any length that you specify. You can use this random byte array as the salt value of the hash algorithm. To take this approach, you must safely store the salt value.

In the example shown in Figure 2, you need to enter a string in the text box, select a specific hash type, and then generate a salt value and a hash value that contains the salt value and the original string.


Figure 2: Adding a salt value to the hash value to create a more secure password hash
(You need to store salt values to create the same hash again.) )

The example is essentially the same as the previous example in this article, except that it creates a routine of salt values. Under the button's Click event on this screen, first call a method named CreateSalt () to generate a unique salt value, and then store the value in the Txtsalt text box. After the unique salt value is obtained, the hashstring () method is called and the two values are combined.

' Visual Basic. NET
Private Sub Btnhash_click (ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles Btnhash.click
Txtsalt.text = CreateSalt ()
Txthashed.text = HashString (Txtsalt.text & _
Txtoriginal.text)
End Sub

C#
private void Cmdhash_click (object sender, System.EventArgs e)
{
Txtsalt.text = CreateSalt ();
Txthashed.text = hashstring (Txtoriginal.text);
}
The code for the CreateSalt () method is very simple. It first creates a byte array of 8 bytes long, and then you create a new instance of the RNGCryptoServiceProvider class. Use the GetBytes () method of the object to populate the resulting random character set into a byte array. This byte array is then converted into a BASE64 encoded string and returned from the function.

' Visual Basic. NET
Private Function CreateSalt () as String
Dim Bytsalt (8) as Byte
Dim rng as New RNGCryptoServiceProvider

Rng. GetBytes (Bytsalt)

Return convert.tobase64string (Bytsalt)
End Function

C#
private String CreateSalt ()
{
byte[] Bytsalt = new Byte[8];
RNGCryptoServiceProvider rng;

RNG = new RNGCryptoServiceProvider ();

Rng. GetBytes (Bytsalt);

Return convert.tobase64string (Bytsalt);
}
Data encryption is a two-way road.
If you need to send information back and forth between two or more people or computers, and you want the other person to be able to read the data while others cannot, then encryption is the best way! Encryption algorithms allow you to cover up the data, and other people are less likely to read it mathematically than a specific person can decrypt it. But if you want someone to be able to read the data, you can give it a specific "key" that allows it to decrypt and read the data. There are several encryption/decryption algorithms available in the. NET Framework. This article mainly introduces the symmetric algorithm, including the following kinds:

Des
RC2
Rijndael
TripleDES
The symmetric algorithm (or key algorithm) uses a key and an initialization vector (IV) to secure the data. Both sides of the data must know the key and the initialization vector to be able to encrypt and decrypt the data. You must ensure that the key is secure, otherwise someone else will be able to decrypt the data and read the message. The initialization vector is just a randomly generated character set, which ensures that no two text will generate the same encrypted data. You can export keys using built-in methods for different cryptographic classes in. NET, and it is not part of this article to export the keys.

Other types of cryptographic algorithms are called asymmetric algorithms. An asymmetric algorithm uses a public/private key pair to create encrypted data. The asymmetric algorithm is discussed below.

How to choose different encryption methods in different situations
The symmetric algorithm (or key algorithm) is very fast and is well suited for encrypting large data streams. These algorithms can encrypt data or decrypt data. They are fairly secure, but they can also be broken if there is enough time, because someone might search for each known combination of key values. Because each algorithm uses a fixed key length or ASCII character, the computer program can try each possible combination of keys and finally find the correct one. These types of algorithms are typically used to store and retrieve connection strings for a database.

Asymmetric algorithms (or public-key algorithms) do not have a symmetric algorithm fast, but their code is more difficult to break. These algorithms depend on two keys, one is the private key and the other is the public key. The public key is used to encrypt the message, and the private key is the only key that can decrypt the message. The public and private keys are linked together mathematically, so the two keys must be obtained for a successful encrypted exchange. Because of the possible impact on computer performance, asymmetric algorithms are not very useful for encrypting large amounts of data. A common use of asymmetric algorithms is to encrypt and transmit symmetric keys and initialization vectors to each other. The symmetric algorithm is then used to encrypt and decrypt the data in a message sent back and forth between the two parties.

If you do not intend to restore the original values, especially if you do not want others to find the original values, use a hash value. Hashes can encrypt strings of any length to a fixed set of bytes. This is a one-way operation, so it is usually used for small amounts of data such as passwords. When a user enters a user's password on a secure input screen, the program encrypts the password and stores the hash value in the database. No one can read the password, even if the database is compromised, because the password is encrypted. When a user logs on to the system for input, the same algorithm is used to decrypt the password that the user typed, and if two hash values match, the system can determine that the user entered the same value as the previously stored value.

Encryption exercises
The sample application includes a form that allows you to use the DES and TripleDES cryptographic service providers for encryption exercises. The form is named Frmencrypt, as shown in Figure 3.



Figure 3: The encryption algorithm allows you to encrypt and decrypt values.

On this screen, you first need to click the Gen key (Generate key) button, and then click the Gen IV (Build IV) button. Then enter some data in the Original string (original string) text box and click the Encrypt (Encryption) button. After you click the Encrypt (Encryption) button, the encrypted text appears in the Encrypted string (encrypted string) text box. If you want to use this encrypted string in your own application, you will need to note the generated key and IV, because you need to supply both values to decrypt the connection string for reuse. If the key and IV are lost, the connection string will no longer be restored.

Now look at its source code and learn how to implement encryption and decryption routines. First look at the member variable for the class, which holds the reference to the corresponding cryptographic service provider. The type of the member variable is symmetricalgorithm. All symmetric algorithm classes inherit from this base class.

' Visual Basic. NET
Private MCSP as SymmetricAlgorithm
C#
Private SymmetricAlgorithm MCSP;
Depending on the option buttons that you select on this form, this MCSP variable is assigned to a specific symmetric algorithm class. The Setenc () method is responsible for creating the appropriate type and returning it to a different method.

' Visual Basic. NET
Private Function Setenc () as SymmetricAlgorithm
If optdes.checked Then
return New DESCryptoServiceProvider
Else
If opttripledes.checked Then
return New TripleDESCryptoServiceProvider
End If
End If
End Function

C#
Private SymmetricAlgorithm Setenc ()
{
if (optdes.checked)
return new DESCryptoServiceProvider ();
Else
return new TripleDESCryptoServiceProvider ();
}
As you can see, the DESCryptoServiceProvider object or TripleDESCryptoServiceProvider object is created based on the option buttons that you select on the form.

Encryption and decryption keys are implemented
To use a symmetric algorithm, you must supply the key to use. Each CRYPTOSYMMETRICALGORITHM implementation provides a GenerateKey method. They actually use the random number generator class that is built into the common language runtime (CLR) class. Let's take a look at the Click event handler for the Gen key button, and see how it generates the random key value to use.

' Visual Basic. NET
Private Sub Btnkeygen_click (ByVal sender as _
System.Object, ByVal e as System.EventArgs) _
Handles Btnkeygen.click
MCSP = Setenc ()

Mcsp.generatekey ()

Txtkey.text = convert.tobase64string (Mcsp.key)
End Sub
C#
private void Btnkeygen_click (object sender,
System.EventArgs e)
{
MCSP = Setenc ();

Mcsp.generatekey ();

Txtkey.text = convert.tobase64string (Mcsp.key);
}
After you obtain a specific implementation of a service provider, simply call the GenerateKey method to create a new random key for encryption. The size of the key depends on the specific provider used to encrypt it. For example, the DES key has a size of 64 bits, and the TripleDES key has a size of 192 bits. Each SymmetricAlgorithm class has a KeySize property that returns the key size used to generate the key.

We also need to generate initialization vectors (IV). IV will help the algorithm generate the data block of the final encrypted string. IV is used to start the encryption of the first block. If you do not provide IV, the common data passed between strings will remain the same pattern as long as the key is the same. Therefore, you need to use IV as the "random" component of the encrypted data. In this way, as long as the IV is used differently, even if the key is the same, the same data is encrypted to a completely different value. The following is the source code of the Gen IV (Build IV) button that generated the new IV.

' Visual Basic. NET
Private Sub Btnivgen_click (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Btnivgen.click
Mcsp.generateiv ()

Txtiv.text = convert.tobase64string (MCSP.IV)
End Sub

C#
private void Btnivgen_click (object sender,
System.EventArgs e)
{
Mcsp.generateiv ();

Txtiv.text = convert.tobase64string (MCSP.IV);
}
This code looks very similar to the code that generated the key. There is a GenerateIV () method on each cryptographic service provider class. If IV is not provided, the method generates an IV.

Encrypt data
After you obtain the key and initialization vectors, you can now use the key, IV, and Original string values to create an encrypted version of the original string value. Clicking the Encrypt (Encryption) button will run the following code.

' Visual Basic. NET
Private Sub Btnencrypt_click (_
ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles Cmdencrypt.click
Txtencrypted.text = encryptstring (Txtoriginal.text)
End Sub

C#
private void Cmdencrypt_click (object sender, System.EventArgs e)
{
Txtencrypted.text = encryptstring (Txtoriginal.text);
}
The Click event procedure calls a method named EncryptString (), accepts the value from the Original string (original string) text box, and encrypts it. It then returns the value and places it in the Encrypted string (encrypted string) text box. The following is the code for the EncryptString () method.

' Visual Basic. NET
Private Function encryptstring (ByVal Value as String) _
As String
Dim CT as ICryptoTransform
Dim MS as MemoryStream
Dim CS as CryptoStream
Dim byt () as Byte

ct = Mcsp.createencryptor (Mcsp.key, MCSP.IV)

Byt = Encoding.UTF8.GetBytes (Value)

ms = New MemoryStream
CS = New CryptoStream (MS, CT, CryptoStreamMode.Write)
Cs. Write (byt, 0, Byt. Length)
Cs. FlushFinalBlock ()

Cs. Close ()

Return convert.tobase64string (Ms. ToArray ())
End Function

C#
private string EncryptString (String Value)
{
ICryptoTransform CT;
MemoryStream MS;
CryptoStream CS;
Byte[] byt;

ct = Mcsp.createencryptor (Mcsp.key, MCSP.IV);

Byt = Encoding.UTF8.GetBytes (Value);

ms = new MemoryStream ();
CS = new CryptoStream (MS, CT, cryptostreammode.write);
Cs. Write (byt, 0, Byt. Length);
Cs. FlushFinalBlock ();

Cs. Close ();

Return convert.tobase64string (Ms. ToArray ());
}
Now let's take a look at each line of code and see how it works. The first is a few variables of the encryption process.

Dim CT as ICryptoTransform
Dim MS as MemoryStream
Dim CS as CryptoStream
Dim byt () as Byte
ICryptoTransform is an interface. This interface is required to invoke the CreateEncryptor method on any service provider, and the service provider returns the actual Encryptor object that defines the interface.

You then need to convert the original string into a byte array. Most. NET cryptographic algorithms handle byte arrays instead of strings.

Byt = Encoding.UTF8.GetBytes (Value)
You can now perform the actual encryption. This process needs to create a data stream to write encrypted bytes to. To use the MemoryStream object named MS, the ICryptoTransform object (which is provided to the constructor of the CryptoStream class), and the enumeration constants that describe the pattern (read, write, and so on) that you want to create for the class. After the CryptoStream object CS is created, the data is now written to the memory data stream using the Write method of the CryptoStream object. This is the method of actual encryption, when each block of data is encrypted, the data is written to the MemoryStream object.

ms = New MemoryStream
CS = New CryptoStream (MS, CT, CryptoStreamMode.Write)
Cs. Write (byt, 0, Byt. Length)
Cs. FlushFinalBlock ()

Cs. Close ()
After the MemoryStream is created, the code executes the FlushFinalBlock method on the CryptoStream object to ensure that all data is written to the MemoryStream object. This procedure closes the CryptoStream object.

Finally, the process converts the memory data stream from a byte array back to the string, so that the string can be displayed in a text box on the form. You can use the MemoryStream ToArray () method to get a byte array from the data stream, and then call the Convert.tobase64string () method, which accepts byte array input and encodes the string into readable content using the Base64 encoding method.

Decrypting data
After encrypting the data, it is sometimes necessary to decrypt the data. The process of decrypting data is very simple and similar to the encryption process. You need to provide the keys and initialization vectors used in the encryption process. The Key and IV attributes of the SymmetricAlgorithm class are defined as byte arrays. Therefore, you need to provide the string you created and convert it to a byte array before setting these properties. Let's look at the Decryptstring method used to decrypt the string in the form. This method is called from the Click event handler of the Decrypt (decryption) button on the form.

' Visual Basic. NET
Private Function decryptstring (ByVal Value as String) _
As String
Dim CT as ICryptoTransform
Dim MS as MemoryStream
Dim CS as CryptoStream
Dim byt () as Byte

ct = Mcsp.createdecryptor (Mcsp.key, MCSP.IV)

Byt = convert.frombase64string (Value)

ms = New MemoryStream
CS = New CryptoStream (MS, CT, CryptoStreamMode.Write)
Cs. Write (byt, 0, Byt. Length)
Cs. FlushFinalBlock ()

Cs. Close ()

Return Encoding.UTF8.GetString (Ms. ToArray ())
End Function

C#
private string Decryptstring (String Value)
{
ICryptoTransform CT;
MemoryStream MS;
CryptoStream CS;
Byte[] byt;

ct = Mcsp.createdecryptor (Mcsp.key, MCSP.IV);

Byt = convert.frombase64string (Value);

ms = new MemoryStream ();
CS = new CryptoStream (MS, CT, cryptostreammode.write);
Cs. Write (byt, 0, Byt. Length);
Cs. FlushFinalBlock ();

Cs. Close ();

Return Encoding.UTF8.GetString (Ms. ToArray ());
}
There are only three differences between the Encrypt function and the Decrypt function.

You need to use the CreateDecryptor method of the CryptoServiceProvider class to create the corresponding Ictryptotransform object.
You need to convert the BASE64 encoded string into a byte array. You need to use the Convert.frombase64string method to implement this transformation.
Converts a byte array into the appropriate memory data stream by converting the original byte array. You need to convert the memory data stream from a byte array back to a normal string that can be displayed again on the form. You need to use the Encoding.UTF8.GetString () method to implement this transformation.
Note: The Encoding.UTF8 class comes from the System.Text namespace.
Can you make it simpler?!
Although the code shown so far is not difficult, there are many different classes and interfaces that you may not be accustomed to using. In addition, there are a lot of code to remember. Let's learn how to wrap a cryptography class into a class that is easy to use.

There are two classes in the assembly named Pdsacryptography, Pdsahash and Pdsaencryption respectively. These two classes are used to encapsulate the actual mechanism for creating a hash string or an encrypted string. In addition, they allow you to use enumeration constants to determine which hashing or cryptographic algorithm to use. You don't have to remember all the different names of each of the different cryptographic service providers to get a good list of intellisense® providers.

Wrapping Hash with Pdsahash
The Pdsahash class contains properties Hashtype, Hashobject, originalstring, hashstring, Saltvalue, Usesalt, and Saltlength. The methods associated with this class include Setencryptor, CreateSalt, Reset, and CreateHash. This class creates an enumeration called Pdsahashtype, from which you can select the appropriate hash class to use. The purpose of this class is to simplify the code shown above to the following code.

Private Sub Usepdsahash ()
Dim ph as New pdsahash (PDSAHash.PDSAHashType.MD5)

MessageBox.Show (Ph. CreateHash ("Paul"))
End Sub
I would rather type the above code than remember all the code shown above. As you can see, this piece of code is quite simple, exactly the same as the code described above, and is packaged into an Easy-to-use interface. You can find the complete class from the examples included in this article. The different hashing algorithms that you can create with this class are listed below.

Public Enum Pdsahashtype as Byte
MD5
SHA1
SHA256
SHA384
SHA512
End Enum
Each of these algorithms provides a different level of security for the final hash. The complete list of hash classes in. NET is as follows:

MD5CryptoServiceProvider
SHA1CryptoServiceProvider
SHA256Managed
Sha384managed
Sha512managed
For more information about these different hash types, see the Visual Studio. NET online documentation.

Encrypt using Pdsaencryption Wrapper
Just as the Pdsahash class can wrap all the hash features in the. NET Framework, the Pdsaencryption class can be used to wrap various symmetric algorithm classes in the. NET Framework. The Pdsaencryption class includes the following enumeration types, allowing you to create various encryption/decryption objects.

Public Enum Pdsaencryptiontype as Byte
Des
RC2
Rijndael
TripleDES
End Enum
Similarly, each service provider provides a different level of security for the encrypted string. This is described in detail in the Visual Studio. NET online documentation and is not discussed here.

This class contains properties EncryptionType, Originalstring, encryptedstring, Key, keystring, IV, ivstring, and CryptoProvider. Most of these properties are self-explanatory, but Key and IV are byte arrays, and KeyString and ivstring are string representations of these byte arrays.

The class also contains some methods. such as Encrypt and Decrypt. There are GenerateKey and GenerateIV methods, and if there are no ready-made keys and IV, you can use both methods to create a key and IV. There is also the Setencryptor method, which is used to create new CryptoProvider objects that will be used in various methods.

The purpose of this class is to make encrypting and decrypting strings easier to implement. For example, the following code fragment shows how easy it is to use this class to encrypt a string.

Private Sub Btnhardcoded_click (_
ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles Btnhardcoded.click
Dim PS as New pdsasymmetric (_
PDSASymmetric.PDSAEncryptionType.TripleDES)

MessageBox.Show (PS. Encrypt (_
"Server=localhost;database=northwind;uid=sa;pwd=sa"))
End Sub
Summary
Using classes in the Microsoft. NET Framework makes it easy to save confidential information on your computer. You'll find that multiple classes in the cryptography namespace can do the job well. Creating wrappers for these classes can help you significantly reduce the amount of code you need to write. It is strongly recommended that you create similar wrappers as described in this article.



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.